1 //===-- SystemZISelLowering.cpp - SystemZ DAG lowering implementation -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the SystemZTargetLowering class.
12 //===----------------------------------------------------------------------===//
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"
28 #define DEBUG_TYPE "systemz-lower"
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) {}
42 // Represents information about a comparison.
44 Comparison(SDValue Op0In, SDValue Op1In)
45 : Op0(Op0In), Op1(Op1In), Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
47 // The operands to the comparison.
50 // The opcode that should be used to compare Op0 and Op1.
53 // A SystemZICMP value. Only used for integer comparisons.
56 // The mask of CC values that Opcode can produce.
59 // The mask of CC values for which the original condition is true.
62 } // end anonymous namespace
64 // Classify VT as either 32 or 64 bit.
65 static bool is32Bit(EVT VT) {
66 switch (VT.getSimpleVT().SimpleTy) {
72 llvm_unreachable("Unsupported type");
76 // Return a version of MachineOperand that can be safely used before the
78 static MachineOperand earlyUseOperand(MachineOperand Op) {
84 SystemZTargetLowering::SystemZTargetLowering(const TargetMachine &TM,
85 const SystemZSubtarget &STI)
86 : TargetLowering(TM), Subtarget(STI) {
87 MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
89 // Set up the register classes.
90 if (Subtarget.hasHighWord())
91 addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
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);
99 addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass);
100 addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass);
102 addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
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);
113 // Compute derived properties from the register classes
114 computeRegisterProperties(Subtarget.getRegisterInfo());
116 // Set up special registers.
117 setStackPointerRegisterToSaveRestore(SystemZ::R15D);
119 // TODO: It may be better to default to latency-oriented scheduling, however
120 // LLVM's current latency-oriented scheduler can't handle physreg definitions
121 // such as SystemZ has with CC, so set this to the register-pressure
122 // scheduler, because it can.
123 setSchedulingPreference(Sched::RegPressure);
125 setBooleanContents(ZeroOrOneBooleanContent);
126 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
128 // Instructions are strings of 2-byte aligned 2-byte values.
129 setMinFunctionAlignment(2);
131 // Handle operations that are handled in a similar way for all types.
132 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
133 I <= MVT::LAST_FP_VALUETYPE;
135 MVT VT = MVT::SimpleValueType(I);
136 if (isTypeLegal(VT)) {
137 // Lower SET_CC into an IPM-based sequence.
138 setOperationAction(ISD::SETCC, VT, Custom);
140 // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
141 setOperationAction(ISD::SELECT, VT, Expand);
143 // Lower SELECT_CC and BR_CC into separate comparisons and branches.
144 setOperationAction(ISD::SELECT_CC, VT, Custom);
145 setOperationAction(ISD::BR_CC, VT, Custom);
149 // Expand jump table branches as address arithmetic followed by an
151 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
153 // Expand BRCOND into a BR_CC (see above).
154 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
156 // Handle integer types.
157 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
158 I <= MVT::LAST_INTEGER_VALUETYPE;
160 MVT VT = MVT::SimpleValueType(I);
161 if (isTypeLegal(VT)) {
162 // Expand individual DIV and REMs into DIVREMs.
163 setOperationAction(ISD::SDIV, VT, Expand);
164 setOperationAction(ISD::UDIV, VT, Expand);
165 setOperationAction(ISD::SREM, VT, Expand);
166 setOperationAction(ISD::UREM, VT, Expand);
167 setOperationAction(ISD::SDIVREM, VT, Custom);
168 setOperationAction(ISD::UDIVREM, VT, Custom);
170 // Lower ATOMIC_LOAD and ATOMIC_STORE into normal volatile loads and
171 // stores, putting a serialization instruction after the stores.
172 setOperationAction(ISD::ATOMIC_LOAD, VT, Custom);
173 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
175 // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
176 // available, or if the operand is constant.
177 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
179 // Use POPCNT on z196 and above.
180 if (Subtarget.hasPopulationCount())
181 setOperationAction(ISD::CTPOP, VT, Custom);
183 setOperationAction(ISD::CTPOP, VT, Expand);
185 // No special instructions for these.
186 setOperationAction(ISD::CTTZ, VT, Expand);
187 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
188 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
189 setOperationAction(ISD::ROTR, VT, Expand);
191 // Use *MUL_LOHI where possible instead of MULH*.
192 setOperationAction(ISD::MULHS, VT, Expand);
193 setOperationAction(ISD::MULHU, VT, Expand);
194 setOperationAction(ISD::SMUL_LOHI, VT, Custom);
195 setOperationAction(ISD::UMUL_LOHI, VT, Custom);
197 // Only z196 and above have native support for conversions to unsigned.
198 if (!Subtarget.hasFPExtension())
199 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
203 // Type legalization will convert 8- and 16-bit atomic operations into
204 // forms that operate on i32s (but still keeping the original memory VT).
205 // Lower them into full i32 operations.
206 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Custom);
207 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Custom);
208 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
209 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
210 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Custom);
211 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Custom);
212 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Custom);
213 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Custom);
214 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Custom);
215 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Custom);
216 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Custom);
217 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
219 // z10 has instructions for signed but not unsigned FP conversion.
220 // Handle unsigned 32-bit types as signed 64-bit types.
221 if (!Subtarget.hasFPExtension()) {
222 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote);
223 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
226 // We have native support for a 64-bit CTLZ, via FLOGR.
227 setOperationAction(ISD::CTLZ, MVT::i32, Promote);
228 setOperationAction(ISD::CTLZ, MVT::i64, Legal);
230 // Give LowerOperation the chance to replace 64-bit ORs with subregs.
231 setOperationAction(ISD::OR, MVT::i64, Custom);
233 // FIXME: Can we support these natively?
234 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
235 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
236 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
238 // We have native instructions for i8, i16 and i32 extensions, but not i1.
239 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
240 for (MVT VT : MVT::integer_valuetypes()) {
241 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
242 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
243 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
246 // Handle the various types of symbolic address.
247 setOperationAction(ISD::ConstantPool, PtrVT, Custom);
248 setOperationAction(ISD::GlobalAddress, PtrVT, Custom);
249 setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom);
250 setOperationAction(ISD::BlockAddress, PtrVT, Custom);
251 setOperationAction(ISD::JumpTable, PtrVT, Custom);
253 // We need to handle dynamic allocations specially because of the
254 // 160-byte area at the bottom of the stack.
255 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
257 // Use custom expanders so that we can force the function to use
259 setOperationAction(ISD::STACKSAVE, MVT::Other, Custom);
260 setOperationAction(ISD::STACKRESTORE, MVT::Other, Custom);
262 // Handle prefetches with PFD or PFDRL.
263 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
265 for (MVT VT : MVT::vector_valuetypes()) {
266 // Assume by default that all vector operations need to be expanded.
267 for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
268 if (getOperationAction(Opcode, VT) == Legal)
269 setOperationAction(Opcode, VT, Expand);
271 // Likewise all truncating stores and extending loads.
272 for (MVT InnerVT : MVT::vector_valuetypes()) {
273 setTruncStoreAction(VT, InnerVT, Expand);
274 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
275 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
276 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
279 if (isTypeLegal(VT)) {
280 // These operations are legal for anything that can be stored in a
281 // vector register, even if there is no native support for the format
282 // as such. In particular, we can do these for v4f32 even though there
283 // are no specific instructions for that format.
284 setOperationAction(ISD::LOAD, VT, Legal);
285 setOperationAction(ISD::STORE, VT, Legal);
286 setOperationAction(ISD::VSELECT, VT, Legal);
287 setOperationAction(ISD::BITCAST, VT, Legal);
288 setOperationAction(ISD::UNDEF, VT, Legal);
290 // Likewise, except that we need to replace the nodes with something
292 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
293 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
297 // Handle integer vector types.
298 for (MVT VT : MVT::integer_vector_valuetypes()) {
299 if (isTypeLegal(VT)) {
300 // These operations have direct equivalents.
301 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Legal);
302 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Legal);
303 setOperationAction(ISD::ADD, VT, Legal);
304 setOperationAction(ISD::SUB, VT, Legal);
305 if (VT != MVT::v2i64)
306 setOperationAction(ISD::MUL, VT, Legal);
307 setOperationAction(ISD::AND, VT, Legal);
308 setOperationAction(ISD::OR, VT, Legal);
309 setOperationAction(ISD::XOR, VT, Legal);
310 setOperationAction(ISD::CTPOP, VT, Custom);
311 setOperationAction(ISD::CTTZ, VT, Legal);
312 setOperationAction(ISD::CTLZ, VT, Legal);
313 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
314 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
316 // Convert a GPR scalar to a vector by inserting it into element 0.
317 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
319 // Use a series of unpacks for extensions.
320 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
321 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
323 // Detect shifts by a scalar amount and convert them into
325 setOperationAction(ISD::SHL, VT, Custom);
326 setOperationAction(ISD::SRA, VT, Custom);
327 setOperationAction(ISD::SRL, VT, Custom);
329 // At present ROTL isn't matched by DAGCombiner. ROTR should be
330 // converted into ROTL.
331 setOperationAction(ISD::ROTL, VT, Expand);
332 setOperationAction(ISD::ROTR, VT, Expand);
334 // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
335 // and inverting the result as necessary.
336 setOperationAction(ISD::SETCC, VT, Custom);
340 if (Subtarget.hasVector()) {
341 // There should be no need to check for float types other than v2f64
342 // since <2 x f32> isn't a legal type.
343 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
344 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
345 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
346 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
349 // Handle floating-point types.
350 for (unsigned I = MVT::FIRST_FP_VALUETYPE;
351 I <= MVT::LAST_FP_VALUETYPE;
353 MVT VT = MVT::SimpleValueType(I);
354 if (isTypeLegal(VT)) {
355 // We can use FI for FRINT.
356 setOperationAction(ISD::FRINT, VT, Legal);
358 // We can use the extended form of FI for other rounding operations.
359 if (Subtarget.hasFPExtension()) {
360 setOperationAction(ISD::FNEARBYINT, VT, Legal);
361 setOperationAction(ISD::FFLOOR, VT, Legal);
362 setOperationAction(ISD::FCEIL, VT, Legal);
363 setOperationAction(ISD::FTRUNC, VT, Legal);
364 setOperationAction(ISD::FROUND, VT, Legal);
367 // No special instructions for these.
368 setOperationAction(ISD::FSIN, VT, Expand);
369 setOperationAction(ISD::FCOS, VT, Expand);
370 setOperationAction(ISD::FSINCOS, VT, Expand);
371 setOperationAction(ISD::FREM, VT, Expand);
372 setOperationAction(ISD::FPOW, VT, Expand);
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);
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);
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);
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);
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);
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);
422 // We have 64-bit FPR<->GPR moves, but need special handling for
424 if (!Subtarget.hasVector()) {
425 setOperationAction(ISD::BITCAST, MVT::i32, Custom);
426 setOperationAction(ISD::BITCAST, MVT::f32, Custom);
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);
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);
441 // Handle intrinsics.
442 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
443 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
445 // We want to use MVC in preference to even a single load/store pair.
446 MaxStoresPerMemcpy = 0;
447 MaxStoresPerMemcpyOptSize = 0;
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;
458 EVT SystemZTargetLowering::getSetCCResultType(const DataLayout &DL,
459 LLVMContext &, EVT VT) const {
462 return VT.changeVectorElementTypeToInteger();
465 bool SystemZTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
466 VT = VT.getScalarType();
471 switch (VT.getSimpleVT().SimpleTy) {
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();
489 bool SystemZTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
490 // We can use CGFI or CLGFI.
491 return isInt<32>(Imm) || isUInt<32>(Imm);
494 bool SystemZTargetLowering::isLegalAddImmediate(int64_t Imm) const {
495 // We can use ALGFI or SLGFI.
496 return isUInt<32>(Imm) || isUInt<32>(-Imm);
499 bool SystemZTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
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.
511 bool SystemZTargetLowering::isLegalAddressingMode(const DataLayout &DL,
512 const AddrMode &AM, Type *Ty,
514 // Punt on globals for now, although they can be used in limited
515 // RELATIVE LONG cases.
519 // Require a 20-bit signed offset.
520 if (!isInt<20>(AM.BaseOffs))
523 // Indexing is OK but no scale factor can be applied.
524 return AM.Scale == 0 || AM.Scale == 1;
527 bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
528 if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
530 unsigned FromBits = FromType->getPrimitiveSizeInBits();
531 unsigned ToBits = ToType->getPrimitiveSizeInBits();
532 return FromBits > ToBits;
535 bool SystemZTargetLowering::isTruncateFree(EVT FromVT, EVT ToVT) const {
536 if (!FromVT.isInteger() || !ToVT.isInteger())
538 unsigned FromBits = FromVT.getSizeInBits();
539 unsigned ToBits = ToVT.getSizeInBits();
540 return FromBits > ToBits;
543 //===----------------------------------------------------------------------===//
544 // Inline asm support
545 //===----------------------------------------------------------------------===//
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;
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'.
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
576 return TargetLowering::getConstraintType(Constraint);
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.
588 Type *type = CallOperandVal->getType();
589 // Look at the constraint type.
590 switch (*constraint) {
592 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
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;
603 case 'f': // Floating-point register
604 if (type->isFloatingPointTy())
605 weight = CW_Register;
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;
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;
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;
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;
632 case 'M': // 0x7fffffff
633 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
634 if (C->getZExtValue() == 0x7fffffff)
635 weight = CW_Constant;
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])) {
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);
655 return std::make_pair(0U, nullptr);
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]) {
665 case 'd': // Data register (equivalent to 'r')
666 case 'r': // General-purpose register
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);
673 case 'a': // Address register
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);
680 case 'h': // High-part register (an LLVM extension)
681 return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
683 case 'f': // Floating-point register
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);
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') {
698 return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
699 SystemZMC::GR32Regs);
701 return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
702 SystemZMC::GR128Regs);
703 return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
704 SystemZMC::GR64Regs);
706 if (Constraint[1] == 'f') {
708 return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
709 SystemZMC::FP32Regs);
711 return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
712 SystemZMC::FP128Regs);
713 return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
714 SystemZMC::FP64Regs);
717 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
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),
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),
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),
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),
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),
763 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
766 //===----------------------------------------------------------------------===//
767 // Calling conventions
768 //===----------------------------------------------------------------------===//
770 #include "SystemZGenCallingConv.inc"
772 bool SystemZTargetLowering::allowTruncateForTailCall(Type *FromType,
773 Type *ToType) const {
774 return isTruncateFree(FromType, ToType);
777 bool SystemZTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
778 return CI->isTailCall();
781 // We do not yet support 128-bit single-element vector types. If the user
782 // attempts to use such types as function argument or return type, prefer
783 // to error out instead of emitting code violating the ABI.
784 static void VerifyVectorType(MVT VT, EVT ArgVT) {
785 if (ArgVT.isVector() && !VT.isVector())
786 report_fatal_error("Unsupported vector argument or return type");
789 static void VerifyVectorTypes(const SmallVectorImpl<ISD::InputArg> &Ins) {
790 for (unsigned i = 0; i < Ins.size(); ++i)
791 VerifyVectorType(Ins[i].VT, Ins[i].ArgVT);
794 static void VerifyVectorTypes(const SmallVectorImpl<ISD::OutputArg> &Outs) {
795 for (unsigned i = 0; i < Outs.size(); ++i)
796 VerifyVectorType(Outs[i].VT, Outs[i].ArgVT);
799 // Value is a value that has been passed to us in the location described by VA
800 // (and so has type VA.getLocVT()). Convert Value to VA.getValVT(), chaining
801 // any loads onto Chain.
802 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDLoc DL,
803 CCValAssign &VA, SDValue Chain,
805 // If the argument has been promoted from a smaller type, insert an
806 // assertion to capture this.
807 if (VA.getLocInfo() == CCValAssign::SExt)
808 Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value,
809 DAG.getValueType(VA.getValVT()));
810 else if (VA.getLocInfo() == CCValAssign::ZExt)
811 Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value,
812 DAG.getValueType(VA.getValVT()));
815 Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
816 else if (VA.getLocInfo() == CCValAssign::Indirect)
817 Value = DAG.getLoad(VA.getValVT(), DL, Chain, Value,
818 MachinePointerInfo(), false, false, false, 0);
819 else if (VA.getLocInfo() == CCValAssign::BCvt) {
820 // If this is a short vector argument loaded from the stack,
821 // extend from i64 to full vector size and then bitcast.
822 assert(VA.getLocVT() == MVT::i64);
823 assert(VA.getValVT().isVector());
824 Value = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i64,
825 Value, DAG.getUNDEF(MVT::i64));
826 Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
828 assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
832 // Value is a value of type VA.getValVT() that we need to copy into
833 // the location described by VA. Return a copy of Value converted to
834 // VA.getValVT(). The caller is responsible for handling indirect values.
835 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDLoc DL,
836 CCValAssign &VA, SDValue Value) {
837 switch (VA.getLocInfo()) {
838 case CCValAssign::SExt:
839 return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
840 case CCValAssign::ZExt:
841 return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
842 case CCValAssign::AExt:
843 return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
844 case CCValAssign::BCvt:
845 // If this is a short vector argument to be stored to the stack,
846 // bitcast to v2i64 and then extract first element.
847 assert(VA.getLocVT() == MVT::i64);
848 assert(VA.getValVT().isVector());
849 Value = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Value);
850 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
851 DAG.getConstant(0, DL, MVT::i32));
852 case CCValAssign::Full:
855 llvm_unreachable("Unhandled getLocInfo()");
859 SDValue SystemZTargetLowering::
860 LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
861 const SmallVectorImpl<ISD::InputArg> &Ins,
862 SDLoc DL, SelectionDAG &DAG,
863 SmallVectorImpl<SDValue> &InVals) const {
864 MachineFunction &MF = DAG.getMachineFunction();
865 MachineFrameInfo *MFI = MF.getFrameInfo();
866 MachineRegisterInfo &MRI = MF.getRegInfo();
867 SystemZMachineFunctionInfo *FuncInfo =
868 MF.getInfo<SystemZMachineFunctionInfo>();
870 static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering());
872 // Detect unsupported vector argument types.
873 if (Subtarget.hasVector())
874 VerifyVectorTypes(Ins);
876 // Assign locations to all of the incoming arguments.
877 SmallVector<CCValAssign, 16> ArgLocs;
878 SystemZCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
879 CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
881 unsigned NumFixedGPRs = 0;
882 unsigned NumFixedFPRs = 0;
883 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
885 CCValAssign &VA = ArgLocs[I];
886 EVT LocVT = VA.getLocVT();
888 // Arguments passed in registers
889 const TargetRegisterClass *RC;
890 switch (LocVT.getSimpleVT().SimpleTy) {
892 // Integers smaller than i64 should be promoted to i64.
893 llvm_unreachable("Unexpected argument type");
896 RC = &SystemZ::GR32BitRegClass;
900 RC = &SystemZ::GR64BitRegClass;
904 RC = &SystemZ::FP32BitRegClass;
908 RC = &SystemZ::FP64BitRegClass;
916 RC = &SystemZ::VR128BitRegClass;
920 unsigned VReg = MRI.createVirtualRegister(RC);
921 MRI.addLiveIn(VA.getLocReg(), VReg);
922 ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
924 assert(VA.isMemLoc() && "Argument not register or memory");
926 // Create the frame index object for this incoming parameter.
927 int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
928 VA.getLocMemOffset(), true);
930 // Create the SelectionDAG nodes corresponding to a load
931 // from this parameter. Unpromoted ints and floats are
932 // passed as right-justified 8-byte values.
933 EVT PtrVT = getPointerTy(DAG.getDataLayout());
934 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
935 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
936 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
937 DAG.getIntPtrConstant(4, DL));
938 ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
939 MachinePointerInfo::getFixedStack(MF, FI), false,
943 // Convert the value of the argument register into the value that's
945 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
949 // Save the number of non-varargs registers for later use by va_start, etc.
950 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
951 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
953 // Likewise the address (in the form of a frame index) of where the
954 // first stack vararg would be. The 1-byte size here is arbitrary.
955 int64_t StackSize = CCInfo.getNextStackOffset();
956 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize, true));
958 // ...and a similar frame index for the caller-allocated save area
959 // that will be used to store the incoming registers.
960 int64_t RegSaveOffset = TFL->getOffsetOfLocalArea();
961 unsigned RegSaveIndex = MFI->CreateFixedObject(1, RegSaveOffset, true);
962 FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
964 // Store the FPR varargs in the reserved frame slots. (We store the
965 // GPRs as part of the prologue.)
966 if (NumFixedFPRs < SystemZ::NumArgFPRs) {
967 SDValue MemOps[SystemZ::NumArgFPRs];
968 for (unsigned I = NumFixedFPRs; I < SystemZ::NumArgFPRs; ++I) {
969 unsigned Offset = TFL->getRegSpillOffset(SystemZ::ArgFPRs[I]);
970 int FI = MFI->CreateFixedObject(8, RegSaveOffset + Offset, true);
971 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
972 unsigned VReg = MF.addLiveIn(SystemZ::ArgFPRs[I],
973 &SystemZ::FP64BitRegClass);
974 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
975 MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
976 MachinePointerInfo::getFixedStack(MF, FI),
979 // Join the stores, which are independent of one another.
980 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
981 makeArrayRef(&MemOps[NumFixedFPRs],
982 SystemZ::NumArgFPRs-NumFixedFPRs));
989 static bool canUseSiblingCall(const CCState &ArgCCInfo,
990 SmallVectorImpl<CCValAssign> &ArgLocs) {
991 // Punt if there are any indirect or stack arguments, or if the call
992 // needs the call-saved argument register R6.
993 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
994 CCValAssign &VA = ArgLocs[I];
995 if (VA.getLocInfo() == CCValAssign::Indirect)
999 unsigned Reg = VA.getLocReg();
1000 if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
1007 SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI,
1008 SmallVectorImpl<SDValue> &InVals) const {
1009 SelectionDAG &DAG = CLI.DAG;
1011 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1012 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1013 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1014 SDValue Chain = CLI.Chain;
1015 SDValue Callee = CLI.Callee;
1016 bool &IsTailCall = CLI.IsTailCall;
1017 CallingConv::ID CallConv = CLI.CallConv;
1018 bool IsVarArg = CLI.IsVarArg;
1019 MachineFunction &MF = DAG.getMachineFunction();
1020 EVT PtrVT = getPointerTy(MF.getDataLayout());
1022 // Detect unsupported vector argument and return types.
1023 if (Subtarget.hasVector()) {
1024 VerifyVectorTypes(Outs);
1025 VerifyVectorTypes(Ins);
1028 // Analyze the operands of the call, assigning locations to each operand.
1029 SmallVector<CCValAssign, 16> ArgLocs;
1030 SystemZCCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1031 ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
1033 // We don't support GuaranteedTailCallOpt, only automatically-detected
1035 if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs))
1038 // Get a count of how many bytes are to be pushed on the stack.
1039 unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1041 // Mark the start of the call.
1043 Chain = DAG.getCALLSEQ_START(Chain,
1044 DAG.getConstant(NumBytes, DL, PtrVT, true),
1047 // Copy argument values to their designated locations.
1048 SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass;
1049 SmallVector<SDValue, 8> MemOpChains;
1051 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1052 CCValAssign &VA = ArgLocs[I];
1053 SDValue ArgValue = OutVals[I];
1055 if (VA.getLocInfo() == CCValAssign::Indirect) {
1056 // Store the argument in a stack slot and pass its address.
1057 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1058 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1059 MemOpChains.push_back(DAG.getStore(
1060 Chain, DL, ArgValue, SpillSlot,
1061 MachinePointerInfo::getFixedStack(MF, FI), false, false, 0));
1062 ArgValue = SpillSlot;
1064 ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
1067 // Queue up the argument copies and emit them at the end.
1068 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1070 assert(VA.isMemLoc() && "Argument not register or memory");
1072 // Work out the address of the stack slot. Unpromoted ints and
1073 // floats are passed as right-justified 8-byte values.
1074 if (!StackPtr.getNode())
1075 StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT);
1076 unsigned Offset = SystemZMC::CallFrameSize + VA.getLocMemOffset();
1077 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1079 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1080 DAG.getIntPtrConstant(Offset, DL));
1083 MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, Address,
1084 MachinePointerInfo(),
1089 // Join the stores, which are independent of one another.
1090 if (!MemOpChains.empty())
1091 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1093 // Accept direct calls by converting symbolic call addresses to the
1094 // associated Target* opcodes. Force %r1 to be used for indirect
1097 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1098 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
1099 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1100 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1101 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
1102 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1103 } else if (IsTailCall) {
1104 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
1105 Glue = Chain.getValue(1);
1106 Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
1109 // Build a sequence of copy-to-reg nodes, chained and glued together.
1110 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
1111 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
1112 RegsToPass[I].second, Glue);
1113 Glue = Chain.getValue(1);
1116 // The first call operand is the chain and the second is the target address.
1117 SmallVector<SDValue, 8> Ops;
1118 Ops.push_back(Chain);
1119 Ops.push_back(Callee);
1121 // Add argument registers to the end of the list so that they are
1122 // known live into the call.
1123 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
1124 Ops.push_back(DAG.getRegister(RegsToPass[I].first,
1125 RegsToPass[I].second.getValueType()));
1127 // Add a register mask operand representing the call-preserved registers.
1128 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1129 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1130 assert(Mask && "Missing call preserved mask for calling convention");
1131 Ops.push_back(DAG.getRegisterMask(Mask));
1133 // Glue the call to the argument copies, if any.
1135 Ops.push_back(Glue);
1138 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1140 return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
1141 Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
1142 Glue = Chain.getValue(1);
1144 // Mark the end of the call, which is glued to the call itself.
1145 Chain = DAG.getCALLSEQ_END(Chain,
1146 DAG.getConstant(NumBytes, DL, PtrVT, true),
1147 DAG.getConstant(0, DL, PtrVT, true),
1149 Glue = Chain.getValue(1);
1151 // Assign locations to each value returned by this call.
1152 SmallVector<CCValAssign, 16> RetLocs;
1153 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1154 RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
1156 // Copy all of the result registers out of their specified physreg.
1157 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1158 CCValAssign &VA = RetLocs[I];
1160 // Copy the value out, gluing the copy to the end of the call sequence.
1161 SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
1162 VA.getLocVT(), Glue);
1163 Chain = RetValue.getValue(1);
1164 Glue = RetValue.getValue(2);
1166 // Convert the value of the return register into the value that's
1168 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
1174 bool SystemZTargetLowering::
1175 CanLowerReturn(CallingConv::ID CallConv,
1176 MachineFunction &MF, bool isVarArg,
1177 const SmallVectorImpl<ISD::OutputArg> &Outs,
1178 LLVMContext &Context) const {
1179 // Detect unsupported vector return types.
1180 if (Subtarget.hasVector())
1181 VerifyVectorTypes(Outs);
1183 SmallVector<CCValAssign, 16> RetLocs;
1184 CCState RetCCInfo(CallConv, isVarArg, MF, RetLocs, Context);
1185 return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ);
1189 SystemZTargetLowering::LowerReturn(SDValue Chain,
1190 CallingConv::ID CallConv, bool IsVarArg,
1191 const SmallVectorImpl<ISD::OutputArg> &Outs,
1192 const SmallVectorImpl<SDValue> &OutVals,
1193 SDLoc DL, SelectionDAG &DAG) const {
1194 MachineFunction &MF = DAG.getMachineFunction();
1196 // Detect unsupported vector return types.
1197 if (Subtarget.hasVector())
1198 VerifyVectorTypes(Outs);
1200 // Assign locations to each returned value.
1201 SmallVector<CCValAssign, 16> RetLocs;
1202 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1203 RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
1205 // Quick exit for void returns
1206 if (RetLocs.empty())
1207 return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
1209 // Copy the result values into the output registers.
1211 SmallVector<SDValue, 4> RetOps;
1212 RetOps.push_back(Chain);
1213 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1214 CCValAssign &VA = RetLocs[I];
1215 SDValue RetValue = OutVals[I];
1217 // Make the return register live on exit.
1218 assert(VA.isRegLoc() && "Can only return in registers!");
1220 // Promote the value as required.
1221 RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
1223 // Chain and glue the copies together.
1224 unsigned Reg = VA.getLocReg();
1225 Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
1226 Glue = Chain.getValue(1);
1227 RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
1230 // Update chain and glue.
1233 RetOps.push_back(Glue);
1235 return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, RetOps);
1238 SDValue SystemZTargetLowering::
1239 prepareVolatileOrAtomicLoad(SDValue Chain, SDLoc DL, SelectionDAG &DAG) const {
1240 return DAG.getNode(SystemZISD::SERIALIZE, DL, MVT::Other, Chain);
1243 // Return true if Op is an intrinsic node with chain that returns the CC value
1244 // as its only (other) argument. Provide the associated SystemZISD opcode and
1245 // the mask of valid CC values if so.
1246 static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
1247 unsigned &CCValid) {
1248 unsigned Id = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1250 case Intrinsic::s390_tbegin:
1251 Opcode = SystemZISD::TBEGIN;
1252 CCValid = SystemZ::CCMASK_TBEGIN;
1255 case Intrinsic::s390_tbegin_nofloat:
1256 Opcode = SystemZISD::TBEGIN_NOFLOAT;
1257 CCValid = SystemZ::CCMASK_TBEGIN;
1260 case Intrinsic::s390_tend:
1261 Opcode = SystemZISD::TEND;
1262 CCValid = SystemZ::CCMASK_TEND;
1270 // Return true if Op is an intrinsic node without chain that returns the
1271 // CC value as its final argument. Provide the associated SystemZISD
1272 // opcode and the mask of valid CC values if so.
1273 static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) {
1274 unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1276 case Intrinsic::s390_vpkshs:
1277 case Intrinsic::s390_vpksfs:
1278 case Intrinsic::s390_vpksgs:
1279 Opcode = SystemZISD::PACKS_CC;
1280 CCValid = SystemZ::CCMASK_VCMP;
1283 case Intrinsic::s390_vpklshs:
1284 case Intrinsic::s390_vpklsfs:
1285 case Intrinsic::s390_vpklsgs:
1286 Opcode = SystemZISD::PACKLS_CC;
1287 CCValid = SystemZ::CCMASK_VCMP;
1290 case Intrinsic::s390_vceqbs:
1291 case Intrinsic::s390_vceqhs:
1292 case Intrinsic::s390_vceqfs:
1293 case Intrinsic::s390_vceqgs:
1294 Opcode = SystemZISD::VICMPES;
1295 CCValid = SystemZ::CCMASK_VCMP;
1298 case Intrinsic::s390_vchbs:
1299 case Intrinsic::s390_vchhs:
1300 case Intrinsic::s390_vchfs:
1301 case Intrinsic::s390_vchgs:
1302 Opcode = SystemZISD::VICMPHS;
1303 CCValid = SystemZ::CCMASK_VCMP;
1306 case Intrinsic::s390_vchlbs:
1307 case Intrinsic::s390_vchlhs:
1308 case Intrinsic::s390_vchlfs:
1309 case Intrinsic::s390_vchlgs:
1310 Opcode = SystemZISD::VICMPHLS;
1311 CCValid = SystemZ::CCMASK_VCMP;
1314 case Intrinsic::s390_vtm:
1315 Opcode = SystemZISD::VTM;
1316 CCValid = SystemZ::CCMASK_VCMP;
1319 case Intrinsic::s390_vfaebs:
1320 case Intrinsic::s390_vfaehs:
1321 case Intrinsic::s390_vfaefs:
1322 Opcode = SystemZISD::VFAE_CC;
1323 CCValid = SystemZ::CCMASK_ANY;
1326 case Intrinsic::s390_vfaezbs:
1327 case Intrinsic::s390_vfaezhs:
1328 case Intrinsic::s390_vfaezfs:
1329 Opcode = SystemZISD::VFAEZ_CC;
1330 CCValid = SystemZ::CCMASK_ANY;
1333 case Intrinsic::s390_vfeebs:
1334 case Intrinsic::s390_vfeehs:
1335 case Intrinsic::s390_vfeefs:
1336 Opcode = SystemZISD::VFEE_CC;
1337 CCValid = SystemZ::CCMASK_ANY;
1340 case Intrinsic::s390_vfeezbs:
1341 case Intrinsic::s390_vfeezhs:
1342 case Intrinsic::s390_vfeezfs:
1343 Opcode = SystemZISD::VFEEZ_CC;
1344 CCValid = SystemZ::CCMASK_ANY;
1347 case Intrinsic::s390_vfenebs:
1348 case Intrinsic::s390_vfenehs:
1349 case Intrinsic::s390_vfenefs:
1350 Opcode = SystemZISD::VFENE_CC;
1351 CCValid = SystemZ::CCMASK_ANY;
1354 case Intrinsic::s390_vfenezbs:
1355 case Intrinsic::s390_vfenezhs:
1356 case Intrinsic::s390_vfenezfs:
1357 Opcode = SystemZISD::VFENEZ_CC;
1358 CCValid = SystemZ::CCMASK_ANY;
1361 case Intrinsic::s390_vistrbs:
1362 case Intrinsic::s390_vistrhs:
1363 case Intrinsic::s390_vistrfs:
1364 Opcode = SystemZISD::VISTR_CC;
1365 CCValid = SystemZ::CCMASK_0 | SystemZ::CCMASK_3;
1368 case Intrinsic::s390_vstrcbs:
1369 case Intrinsic::s390_vstrchs:
1370 case Intrinsic::s390_vstrcfs:
1371 Opcode = SystemZISD::VSTRC_CC;
1372 CCValid = SystemZ::CCMASK_ANY;
1375 case Intrinsic::s390_vstrczbs:
1376 case Intrinsic::s390_vstrczhs:
1377 case Intrinsic::s390_vstrczfs:
1378 Opcode = SystemZISD::VSTRCZ_CC;
1379 CCValid = SystemZ::CCMASK_ANY;
1382 case Intrinsic::s390_vfcedbs:
1383 Opcode = SystemZISD::VFCMPES;
1384 CCValid = SystemZ::CCMASK_VCMP;
1387 case Intrinsic::s390_vfchdbs:
1388 Opcode = SystemZISD::VFCMPHS;
1389 CCValid = SystemZ::CCMASK_VCMP;
1392 case Intrinsic::s390_vfchedbs:
1393 Opcode = SystemZISD::VFCMPHES;
1394 CCValid = SystemZ::CCMASK_VCMP;
1397 case Intrinsic::s390_vftcidb:
1398 Opcode = SystemZISD::VFTCI;
1399 CCValid = SystemZ::CCMASK_VCMP;
1407 // Emit an intrinsic with chain with a glued value instead of its CC result.
1408 static SDValue emitIntrinsicWithChainAndGlue(SelectionDAG &DAG, SDValue Op,
1410 // Copy all operands except the intrinsic ID.
1411 unsigned NumOps = Op.getNumOperands();
1412 SmallVector<SDValue, 6> Ops;
1413 Ops.reserve(NumOps - 1);
1414 Ops.push_back(Op.getOperand(0));
1415 for (unsigned I = 2; I < NumOps; ++I)
1416 Ops.push_back(Op.getOperand(I));
1418 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
1419 SDVTList RawVTs = DAG.getVTList(MVT::Other, MVT::Glue);
1420 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
1421 SDValue OldChain = SDValue(Op.getNode(), 1);
1422 SDValue NewChain = SDValue(Intr.getNode(), 0);
1423 DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
1427 // Emit an intrinsic with a glued value instead of its CC result.
1428 static SDValue emitIntrinsicWithGlue(SelectionDAG &DAG, SDValue Op,
1430 // Copy all operands except the intrinsic ID.
1431 unsigned NumOps = Op.getNumOperands();
1432 SmallVector<SDValue, 6> Ops;
1433 Ops.reserve(NumOps - 1);
1434 for (unsigned I = 1; I < NumOps; ++I)
1435 Ops.push_back(Op.getOperand(I));
1437 if (Op->getNumValues() == 1)
1438 return DAG.getNode(Opcode, SDLoc(Op), MVT::Glue, Ops);
1439 assert(Op->getNumValues() == 2 && "Expected exactly one non-CC result");
1440 SDVTList RawVTs = DAG.getVTList(Op->getValueType(0), MVT::Glue);
1441 return DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
1444 // CC is a comparison that will be implemented using an integer or
1445 // floating-point comparison. Return the condition code mask for
1446 // a branch on true. In the integer case, CCMASK_CMP_UO is set for
1447 // unsigned comparisons and clear for signed ones. In the floating-point
1448 // case, CCMASK_CMP_UO has its normal mask meaning (unordered).
1449 static unsigned CCMaskForCondCode(ISD::CondCode CC) {
1451 case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
1452 case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
1453 case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
1457 llvm_unreachable("Invalid integer condition!");
1466 case ISD::SETO: return SystemZ::CCMASK_CMP_O;
1467 case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
1472 // Return a sequence for getting a 1 from an IPM result when CC has a
1473 // value in CCMask and a 0 when CC has a value in CCValid & ~CCMask.
1474 // The handling of CC values outside CCValid doesn't matter.
1475 static IPMConversion getIPMConversion(unsigned CCValid, unsigned CCMask) {
1476 // Deal with cases where the result can be taken directly from a bit
1477 // of the IPM result.
1478 if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_3)))
1479 return IPMConversion(0, 0, SystemZ::IPM_CC);
1480 if (CCMask == (CCValid & (SystemZ::CCMASK_2 | SystemZ::CCMASK_3)))
1481 return IPMConversion(0, 0, SystemZ::IPM_CC + 1);
1483 // Deal with cases where we can add a value to force the sign bit
1484 // to contain the right value. Putting the bit in 31 means we can
1485 // use SRL rather than RISBG(L), and also makes it easier to get a
1486 // 0/-1 value, so it has priority over the other tests below.
1488 // These sequences rely on the fact that the upper two bits of the
1489 // IPM result are zero.
1490 uint64_t TopBit = uint64_t(1) << 31;
1491 if (CCMask == (CCValid & SystemZ::CCMASK_0))
1492 return IPMConversion(0, -(1 << SystemZ::IPM_CC), 31);
1493 if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_1)))
1494 return IPMConversion(0, -(2 << SystemZ::IPM_CC), 31);
1495 if (CCMask == (CCValid & (SystemZ::CCMASK_0
1497 | SystemZ::CCMASK_2)))
1498 return IPMConversion(0, -(3 << SystemZ::IPM_CC), 31);
1499 if (CCMask == (CCValid & SystemZ::CCMASK_3))
1500 return IPMConversion(0, TopBit - (3 << SystemZ::IPM_CC), 31);
1501 if (CCMask == (CCValid & (SystemZ::CCMASK_1
1503 | SystemZ::CCMASK_3)))
1504 return IPMConversion(0, TopBit - (1 << SystemZ::IPM_CC), 31);
1506 // Next try inverting the value and testing a bit. 0/1 could be
1507 // handled this way too, but we dealt with that case above.
1508 if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_2)))
1509 return IPMConversion(-1, 0, SystemZ::IPM_CC);
1511 // Handle cases where adding a value forces a non-sign bit to contain
1513 if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_2)))
1514 return IPMConversion(0, 1 << SystemZ::IPM_CC, SystemZ::IPM_CC + 1);
1515 if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_3)))
1516 return IPMConversion(0, -(1 << SystemZ::IPM_CC), SystemZ::IPM_CC + 1);
1518 // The remaining cases are 1, 2, 0/1/3 and 0/2/3. All these are
1519 // can be done by inverting the low CC bit and applying one of the
1520 // sign-based extractions above.
1521 if (CCMask == (CCValid & SystemZ::CCMASK_1))
1522 return IPMConversion(1 << SystemZ::IPM_CC, -(1 << SystemZ::IPM_CC), 31);
1523 if (CCMask == (CCValid & SystemZ::CCMASK_2))
1524 return IPMConversion(1 << SystemZ::IPM_CC,
1525 TopBit - (3 << SystemZ::IPM_CC), 31);
1526 if (CCMask == (CCValid & (SystemZ::CCMASK_0
1528 | SystemZ::CCMASK_3)))
1529 return IPMConversion(1 << SystemZ::IPM_CC, -(3 << SystemZ::IPM_CC), 31);
1530 if (CCMask == (CCValid & (SystemZ::CCMASK_0
1532 | SystemZ::CCMASK_3)))
1533 return IPMConversion(1 << SystemZ::IPM_CC,
1534 TopBit - (1 << SystemZ::IPM_CC), 31);
1536 llvm_unreachable("Unexpected CC combination");
1539 // If C can be converted to a comparison against zero, adjust the operands
1541 static void adjustZeroCmp(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1542 if (C.ICmpType == SystemZICMP::UnsignedOnly)
1545 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
1549 int64_t Value = ConstOp1->getSExtValue();
1550 if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
1551 (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
1552 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
1553 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
1554 C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
1555 C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
1559 // If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
1560 // adjust the operands as necessary.
1561 static void adjustSubwordCmp(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1562 // For us to make any changes, it must a comparison between a single-use
1563 // load and a constant.
1564 if (!C.Op0.hasOneUse() ||
1565 C.Op0.getOpcode() != ISD::LOAD ||
1566 C.Op1.getOpcode() != ISD::Constant)
1569 // We must have an 8- or 16-bit load.
1570 auto *Load = cast<LoadSDNode>(C.Op0);
1571 unsigned NumBits = Load->getMemoryVT().getStoreSizeInBits();
1572 if (NumBits != 8 && NumBits != 16)
1575 // The load must be an extending one and the constant must be within the
1576 // range of the unextended value.
1577 auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
1578 uint64_t Value = ConstOp1->getZExtValue();
1579 uint64_t Mask = (1 << NumBits) - 1;
1580 if (Load->getExtensionType() == ISD::SEXTLOAD) {
1581 // Make sure that ConstOp1 is in range of C.Op0.
1582 int64_t SignedValue = ConstOp1->getSExtValue();
1583 if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
1585 if (C.ICmpType != SystemZICMP::SignedOnly) {
1586 // Unsigned comparison between two sign-extended values is equivalent
1587 // to unsigned comparison between two zero-extended values.
1589 } else if (NumBits == 8) {
1590 // Try to treat the comparison as unsigned, so that we can use CLI.
1591 // Adjust CCMask and Value as necessary.
1592 if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
1593 // Test whether the high bit of the byte is set.
1594 Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
1595 else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
1596 // Test whether the high bit of the byte is clear.
1597 Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
1599 // No instruction exists for this combination.
1601 C.ICmpType = SystemZICMP::UnsignedOnly;
1603 } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
1606 assert(C.ICmpType == SystemZICMP::Any &&
1607 "Signedness shouldn't matter here.");
1611 // Make sure that the first operand is an i32 of the right extension type.
1612 ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
1615 if (C.Op0.getValueType() != MVT::i32 ||
1616 Load->getExtensionType() != ExtType)
1617 C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32,
1618 Load->getChain(), Load->getBasePtr(),
1619 Load->getPointerInfo(), Load->getMemoryVT(),
1620 Load->isVolatile(), Load->isNonTemporal(),
1621 Load->isInvariant(), Load->getAlignment());
1623 // Make sure that the second operand is an i32 with the right value.
1624 if (C.Op1.getValueType() != MVT::i32 ||
1625 Value != ConstOp1->getZExtValue())
1626 C.Op1 = DAG.getConstant(Value, DL, MVT::i32);
1629 // Return true if Op is either an unextended load, or a load suitable
1630 // for integer register-memory comparisons of type ICmpType.
1631 static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
1632 auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
1634 // There are no instructions to compare a register with a memory byte.
1635 if (Load->getMemoryVT() == MVT::i8)
1637 // Otherwise decide on extension type.
1638 switch (Load->getExtensionType()) {
1639 case ISD::NON_EXTLOAD:
1642 return ICmpType != SystemZICMP::UnsignedOnly;
1644 return ICmpType != SystemZICMP::SignedOnly;
1652 // Return true if it is better to swap the operands of C.
1653 static bool shouldSwapCmpOperands(const Comparison &C) {
1654 // Leave f128 comparisons alone, since they have no memory forms.
1655 if (C.Op0.getValueType() == MVT::f128)
1658 // Always keep a floating-point constant second, since comparisons with
1659 // zero can use LOAD TEST and comparisons with other constants make a
1660 // natural memory operand.
1661 if (isa<ConstantFPSDNode>(C.Op1))
1664 // Never swap comparisons with zero since there are many ways to optimize
1666 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
1667 if (ConstOp1 && ConstOp1->getZExtValue() == 0)
1670 // Also keep natural memory operands second if the loaded value is
1671 // only used here. Several comparisons have memory forms.
1672 if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
1675 // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
1676 // In that case we generally prefer the memory to be second.
1677 if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
1678 // The only exceptions are when the second operand is a constant and
1679 // we can use things like CHHSI.
1682 // The unsigned memory-immediate instructions can handle 16-bit
1683 // unsigned integers.
1684 if (C.ICmpType != SystemZICMP::SignedOnly &&
1685 isUInt<16>(ConstOp1->getZExtValue()))
1687 // The signed memory-immediate instructions can handle 16-bit
1689 if (C.ICmpType != SystemZICMP::UnsignedOnly &&
1690 isInt<16>(ConstOp1->getSExtValue()))
1695 // Try to promote the use of CGFR and CLGFR.
1696 unsigned Opcode0 = C.Op0.getOpcode();
1697 if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
1699 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
1701 if (C.ICmpType != SystemZICMP::SignedOnly &&
1702 Opcode0 == ISD::AND &&
1703 C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
1704 cast<ConstantSDNode>(C.Op0.getOperand(1))->getZExtValue() == 0xffffffff)
1710 // Return a version of comparison CC mask CCMask in which the LT and GT
1711 // actions are swapped.
1712 static unsigned reverseCCMask(unsigned CCMask) {
1713 return ((CCMask & SystemZ::CCMASK_CMP_EQ) |
1714 (CCMask & SystemZ::CCMASK_CMP_GT ? SystemZ::CCMASK_CMP_LT : 0) |
1715 (CCMask & SystemZ::CCMASK_CMP_LT ? SystemZ::CCMASK_CMP_GT : 0) |
1716 (CCMask & SystemZ::CCMASK_CMP_UO));
1719 // Check whether C tests for equality between X and Y and whether X - Y
1720 // or Y - X is also computed. In that case it's better to compare the
1721 // result of the subtraction against zero.
1722 static void adjustForSubtraction(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1723 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
1724 C.CCMask == SystemZ::CCMASK_CMP_NE) {
1725 for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1727 if (N->getOpcode() == ISD::SUB &&
1728 ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
1729 (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
1730 C.Op0 = SDValue(N, 0);
1731 C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
1738 // Check whether C compares a floating-point value with zero and if that
1739 // floating-point value is also negated. In this case we can use the
1740 // negation to set CC, so avoiding separate LOAD AND TEST and
1741 // LOAD (NEGATIVE/COMPLEMENT) instructions.
1742 static void adjustForFNeg(Comparison &C) {
1743 auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
1744 if (C1 && C1->isZero()) {
1745 for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1747 if (N->getOpcode() == ISD::FNEG) {
1748 C.Op0 = SDValue(N, 0);
1749 C.CCMask = reverseCCMask(C.CCMask);
1756 // Check whether C compares (shl X, 32) with 0 and whether X is
1757 // also sign-extended. In that case it is better to test the result
1758 // of the sign extension using LTGFR.
1760 // This case is important because InstCombine transforms a comparison
1761 // with (sext (trunc X)) into a comparison with (shl X, 32).
1762 static void adjustForLTGFR(Comparison &C) {
1763 // Check for a comparison between (shl X, 32) and 0.
1764 if (C.Op0.getOpcode() == ISD::SHL &&
1765 C.Op0.getValueType() == MVT::i64 &&
1766 C.Op1.getOpcode() == ISD::Constant &&
1767 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1768 auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
1769 if (C1 && C1->getZExtValue() == 32) {
1770 SDValue ShlOp0 = C.Op0.getOperand(0);
1771 // See whether X has any SIGN_EXTEND_INREG uses.
1772 for (auto I = ShlOp0->use_begin(), E = ShlOp0->use_end(); I != E; ++I) {
1774 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
1775 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
1776 C.Op0 = SDValue(N, 0);
1784 // If C compares the truncation of an extending load, try to compare
1785 // the untruncated value instead. This exposes more opportunities to
1787 static void adjustICmpTruncate(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1788 if (C.Op0.getOpcode() == ISD::TRUNCATE &&
1789 C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
1790 C.Op1.getOpcode() == ISD::Constant &&
1791 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1792 auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
1793 if (L->getMemoryVT().getStoreSizeInBits()
1794 <= C.Op0.getValueType().getSizeInBits()) {
1795 unsigned Type = L->getExtensionType();
1796 if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
1797 (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
1798 C.Op0 = C.Op0.getOperand(0);
1799 C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
1805 // Return true if shift operation N has an in-range constant shift value.
1806 // Store it in ShiftVal if so.
1807 static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
1808 auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
1812 uint64_t Amount = Shift->getZExtValue();
1813 if (Amount >= N.getValueType().getSizeInBits())
1820 // Check whether an AND with Mask is suitable for a TEST UNDER MASK
1821 // instruction and whether the CC value is descriptive enough to handle
1822 // a comparison of type Opcode between the AND result and CmpVal.
1823 // CCMask says which comparison result is being tested and BitSize is
1824 // the number of bits in the operands. If TEST UNDER MASK can be used,
1825 // return the corresponding CC mask, otherwise return 0.
1826 static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
1827 uint64_t Mask, uint64_t CmpVal,
1828 unsigned ICmpType) {
1829 assert(Mask != 0 && "ANDs with zero should have been removed by now");
1831 // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
1832 if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
1833 !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
1836 // Work out the masks for the lowest and highest bits.
1837 unsigned HighShift = 63 - countLeadingZeros(Mask);
1838 uint64_t High = uint64_t(1) << HighShift;
1839 uint64_t Low = uint64_t(1) << countTrailingZeros(Mask);
1841 // Signed ordered comparisons are effectively unsigned if the sign
1843 bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
1845 // Check for equality comparisons with 0, or the equivalent.
1847 if (CCMask == SystemZ::CCMASK_CMP_EQ)
1848 return SystemZ::CCMASK_TM_ALL_0;
1849 if (CCMask == SystemZ::CCMASK_CMP_NE)
1850 return SystemZ::CCMASK_TM_SOME_1;
1852 if (EffectivelyUnsigned && CmpVal <= Low) {
1853 if (CCMask == SystemZ::CCMASK_CMP_LT)
1854 return SystemZ::CCMASK_TM_ALL_0;
1855 if (CCMask == SystemZ::CCMASK_CMP_GE)
1856 return SystemZ::CCMASK_TM_SOME_1;
1858 if (EffectivelyUnsigned && CmpVal < Low) {
1859 if (CCMask == SystemZ::CCMASK_CMP_LE)
1860 return SystemZ::CCMASK_TM_ALL_0;
1861 if (CCMask == SystemZ::CCMASK_CMP_GT)
1862 return SystemZ::CCMASK_TM_SOME_1;
1865 // Check for equality comparisons with the mask, or the equivalent.
1866 if (CmpVal == Mask) {
1867 if (CCMask == SystemZ::CCMASK_CMP_EQ)
1868 return SystemZ::CCMASK_TM_ALL_1;
1869 if (CCMask == SystemZ::CCMASK_CMP_NE)
1870 return SystemZ::CCMASK_TM_SOME_0;
1872 if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
1873 if (CCMask == SystemZ::CCMASK_CMP_GT)
1874 return SystemZ::CCMASK_TM_ALL_1;
1875 if (CCMask == SystemZ::CCMASK_CMP_LE)
1876 return SystemZ::CCMASK_TM_SOME_0;
1878 if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
1879 if (CCMask == SystemZ::CCMASK_CMP_GE)
1880 return SystemZ::CCMASK_TM_ALL_1;
1881 if (CCMask == SystemZ::CCMASK_CMP_LT)
1882 return SystemZ::CCMASK_TM_SOME_0;
1885 // Check for ordered comparisons with the top bit.
1886 if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
1887 if (CCMask == SystemZ::CCMASK_CMP_LE)
1888 return SystemZ::CCMASK_TM_MSB_0;
1889 if (CCMask == SystemZ::CCMASK_CMP_GT)
1890 return SystemZ::CCMASK_TM_MSB_1;
1892 if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
1893 if (CCMask == SystemZ::CCMASK_CMP_LT)
1894 return SystemZ::CCMASK_TM_MSB_0;
1895 if (CCMask == SystemZ::CCMASK_CMP_GE)
1896 return SystemZ::CCMASK_TM_MSB_1;
1899 // If there are just two bits, we can do equality checks for Low and High
1901 if (Mask == Low + High) {
1902 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
1903 return SystemZ::CCMASK_TM_MIXED_MSB_0;
1904 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
1905 return SystemZ::CCMASK_TM_MIXED_MSB_0 ^ SystemZ::CCMASK_ANY;
1906 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
1907 return SystemZ::CCMASK_TM_MIXED_MSB_1;
1908 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
1909 return SystemZ::CCMASK_TM_MIXED_MSB_1 ^ SystemZ::CCMASK_ANY;
1912 // Looks like we've exhausted our options.
1916 // See whether C can be implemented as a TEST UNDER MASK instruction.
1917 // Update the arguments with the TM version if so.
1918 static void adjustForTestUnderMask(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
1919 // Check that we have a comparison with a constant.
1920 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
1923 uint64_t CmpVal = ConstOp1->getZExtValue();
1925 // Check whether the nonconstant input is an AND with a constant mask.
1928 ConstantSDNode *Mask = nullptr;
1929 if (C.Op0.getOpcode() == ISD::AND) {
1930 NewC.Op0 = C.Op0.getOperand(0);
1931 NewC.Op1 = C.Op0.getOperand(1);
1932 Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
1935 MaskVal = Mask->getZExtValue();
1937 // There is no instruction to compare with a 64-bit immediate
1938 // so use TMHH instead if possible. We need an unsigned ordered
1939 // comparison with an i64 immediate.
1940 if (NewC.Op0.getValueType() != MVT::i64 ||
1941 NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
1942 NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
1943 NewC.ICmpType == SystemZICMP::SignedOnly)
1945 // Convert LE and GT comparisons into LT and GE.
1946 if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
1947 NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
1948 if (CmpVal == uint64_t(-1))
1951 NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
1953 // If the low N bits of Op1 are zero than the low N bits of Op0 can
1954 // be masked off without changing the result.
1955 MaskVal = -(CmpVal & -CmpVal);
1956 NewC.ICmpType = SystemZICMP::UnsignedOnly;
1961 // Check whether the combination of mask, comparison value and comparison
1962 // type are suitable.
1963 unsigned BitSize = NewC.Op0.getValueType().getSizeInBits();
1964 unsigned NewCCMask, ShiftVal;
1965 if (NewC.ICmpType != SystemZICMP::SignedOnly &&
1966 NewC.Op0.getOpcode() == ISD::SHL &&
1967 isSimpleShift(NewC.Op0, ShiftVal) &&
1968 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
1969 MaskVal >> ShiftVal,
1971 SystemZICMP::Any))) {
1972 NewC.Op0 = NewC.Op0.getOperand(0);
1973 MaskVal >>= ShiftVal;
1974 } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
1975 NewC.Op0.getOpcode() == ISD::SRL &&
1976 isSimpleShift(NewC.Op0, ShiftVal) &&
1977 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
1978 MaskVal << ShiftVal,
1980 SystemZICMP::UnsignedOnly))) {
1981 NewC.Op0 = NewC.Op0.getOperand(0);
1982 MaskVal <<= ShiftVal;
1984 NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
1990 // Go ahead and make the change.
1991 C.Opcode = SystemZISD::TM;
1993 if (Mask && Mask->getZExtValue() == MaskVal)
1994 C.Op1 = SDValue(Mask, 0);
1996 C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
1997 C.CCValid = SystemZ::CCMASK_TM;
1998 C.CCMask = NewCCMask;
2001 // Return a Comparison that tests the condition-code result of intrinsic
2002 // node Call against constant integer CC using comparison code Cond.
2003 // Opcode is the opcode of the SystemZISD operation for the intrinsic
2004 // and CCValid is the set of possible condition-code results.
2005 static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
2006 SDValue Call, unsigned CCValid, uint64_t CC,
2007 ISD::CondCode Cond) {
2008 Comparison C(Call, SDValue());
2010 C.CCValid = CCValid;
2011 if (Cond == ISD::SETEQ)
2012 // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
2013 C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
2014 else if (Cond == ISD::SETNE)
2015 // ...and the inverse of that.
2016 C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
2017 else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
2018 // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
2019 // always true for CC>3.
2020 C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1;
2021 else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
2022 // ...and the inverse of that.
2023 C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0;
2024 else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
2025 // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
2026 // always true for CC>3.
2027 C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1;
2028 else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
2029 // ...and the inverse of that.
2030 C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0;
2032 llvm_unreachable("Unexpected integer comparison type");
2033 C.CCMask &= CCValid;
2037 // Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
2038 static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
2039 ISD::CondCode Cond, SDLoc DL) {
2040 if (CmpOp1.getOpcode() == ISD::Constant) {
2041 uint64_t Constant = cast<ConstantSDNode>(CmpOp1)->getZExtValue();
2042 unsigned Opcode, CCValid;
2043 if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
2044 CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
2045 isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
2046 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2047 if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
2048 CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 &&
2049 isIntrinsicWithCC(CmpOp0, Opcode, CCValid))
2050 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2052 Comparison C(CmpOp0, CmpOp1);
2053 C.CCMask = CCMaskForCondCode(Cond);
2054 if (C.Op0.getValueType().isFloatingPoint()) {
2055 C.CCValid = SystemZ::CCMASK_FCMP;
2056 C.Opcode = SystemZISD::FCMP;
2059 C.CCValid = SystemZ::CCMASK_ICMP;
2060 C.Opcode = SystemZISD::ICMP;
2061 // Choose the type of comparison. Equality and inequality tests can
2062 // use either signed or unsigned comparisons. The choice also doesn't
2063 // matter if both sign bits are known to be clear. In those cases we
2064 // want to give the main isel code the freedom to choose whichever
2066 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
2067 C.CCMask == SystemZ::CCMASK_CMP_NE ||
2068 (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
2069 C.ICmpType = SystemZICMP::Any;
2070 else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
2071 C.ICmpType = SystemZICMP::UnsignedOnly;
2073 C.ICmpType = SystemZICMP::SignedOnly;
2074 C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
2075 adjustZeroCmp(DAG, DL, C);
2076 adjustSubwordCmp(DAG, DL, C);
2077 adjustForSubtraction(DAG, DL, C);
2079 adjustICmpTruncate(DAG, DL, C);
2082 if (shouldSwapCmpOperands(C)) {
2083 std::swap(C.Op0, C.Op1);
2084 C.CCMask = reverseCCMask(C.CCMask);
2087 adjustForTestUnderMask(DAG, DL, C);
2091 // Emit the comparison instruction described by C.
2092 static SDValue emitCmp(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
2093 if (!C.Op1.getNode()) {
2095 switch (C.Op0.getOpcode()) {
2096 case ISD::INTRINSIC_W_CHAIN:
2097 Op = emitIntrinsicWithChainAndGlue(DAG, C.Op0, C.Opcode);
2099 case ISD::INTRINSIC_WO_CHAIN:
2100 Op = emitIntrinsicWithGlue(DAG, C.Op0, C.Opcode);
2103 llvm_unreachable("Invalid comparison operands");
2105 return SDValue(Op.getNode(), Op->getNumValues() - 1);
2107 if (C.Opcode == SystemZISD::ICMP)
2108 return DAG.getNode(SystemZISD::ICMP, DL, MVT::Glue, C.Op0, C.Op1,
2109 DAG.getConstant(C.ICmpType, DL, MVT::i32));
2110 if (C.Opcode == SystemZISD::TM) {
2111 bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
2112 bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_1));
2113 return DAG.getNode(SystemZISD::TM, DL, MVT::Glue, C.Op0, C.Op1,
2114 DAG.getConstant(RegisterOnly, DL, MVT::i32));
2116 return DAG.getNode(C.Opcode, DL, MVT::Glue, C.Op0, C.Op1);
2119 // Implement a 32-bit *MUL_LOHI operation by extending both operands to
2120 // 64 bits. Extend is the extension type to use. Store the high part
2121 // in Hi and the low part in Lo.
2122 static void lowerMUL_LOHI32(SelectionDAG &DAG, SDLoc DL,
2123 unsigned Extend, SDValue Op0, SDValue Op1,
2124 SDValue &Hi, SDValue &Lo) {
2125 Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
2126 Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
2127 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
2128 Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2129 DAG.getConstant(32, DL, MVT::i64));
2130 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
2131 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
2134 // Lower a binary operation that produces two VT results, one in each
2135 // half of a GR128 pair. Op0 and Op1 are the VT operands to the operation,
2136 // Extend extends Op0 to a GR128, and Opcode performs the GR128 operation
2137 // on the extended Op0 and (unextended) Op1. Store the even register result
2138 // in Even and the odd register result in Odd.
2139 static void lowerGR128Binary(SelectionDAG &DAG, SDLoc DL, EVT VT,
2140 unsigned Extend, unsigned Opcode,
2141 SDValue Op0, SDValue Op1,
2142 SDValue &Even, SDValue &Odd) {
2143 SDNode *In128 = DAG.getMachineNode(Extend, DL, MVT::Untyped, Op0);
2144 SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped,
2145 SDValue(In128, 0), Op1);
2146 bool Is32Bit = is32Bit(VT);
2147 Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
2148 Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
2151 // Return an i32 value that is 1 if the CC value produced by Glue is
2152 // in the mask CCMask and 0 otherwise. CC is known to have a value
2153 // in CCValid, so other values can be ignored.
2154 static SDValue emitSETCC(SelectionDAG &DAG, SDLoc DL, SDValue Glue,
2155 unsigned CCValid, unsigned CCMask) {
2156 IPMConversion Conversion = getIPMConversion(CCValid, CCMask);
2157 SDValue Result = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
2159 if (Conversion.XORValue)
2160 Result = DAG.getNode(ISD::XOR, DL, MVT::i32, Result,
2161 DAG.getConstant(Conversion.XORValue, DL, MVT::i32));
2163 if (Conversion.AddValue)
2164 Result = DAG.getNode(ISD::ADD, DL, MVT::i32, Result,
2165 DAG.getConstant(Conversion.AddValue, DL, MVT::i32));
2167 // The SHR/AND sequence should get optimized to an RISBG.
2168 Result = DAG.getNode(ISD::SRL, DL, MVT::i32, Result,
2169 DAG.getConstant(Conversion.Bit, DL, MVT::i32));
2170 if (Conversion.Bit != 31)
2171 Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
2172 DAG.getConstant(1, DL, MVT::i32));
2176 // Return the SystemISD vector comparison operation for CC, or 0 if it cannot
2177 // be done directly. IsFP is true if CC is for a floating-point rather than
2178 // integer comparison.
2179 static unsigned getVectorComparison(ISD::CondCode CC, bool IsFP) {
2183 return IsFP ? SystemZISD::VFCMPE : SystemZISD::VICMPE;
2187 return IsFP ? SystemZISD::VFCMPHE : static_cast<SystemZISD::NodeType>(0);
2191 return IsFP ? SystemZISD::VFCMPH : SystemZISD::VICMPH;
2194 return IsFP ? static_cast<SystemZISD::NodeType>(0) : SystemZISD::VICMPHL;
2201 // Return the SystemZISD vector comparison operation for CC or its inverse,
2202 // or 0 if neither can be done directly. Indicate in Invert whether the
2203 // result is for the inverse of CC. IsFP is true if CC is for a
2204 // floating-point rather than integer comparison.
2205 static unsigned getVectorComparisonOrInvert(ISD::CondCode CC, bool IsFP,
2207 if (unsigned Opcode = getVectorComparison(CC, IsFP)) {
2212 CC = ISD::getSetCCInverse(CC, !IsFP);
2213 if (unsigned Opcode = getVectorComparison(CC, IsFP)) {
2221 // Return a v2f64 that contains the extended form of elements Start and Start+1
2222 // of v4f32 value Op.
2223 static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, SDLoc DL,
2225 int Mask[] = { Start, -1, Start + 1, -1 };
2226 Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
2227 return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
2230 // Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
2231 // producing a result of type VT.
2232 static SDValue getVectorCmp(SelectionDAG &DAG, unsigned Opcode, SDLoc DL,
2233 EVT VT, SDValue CmpOp0, SDValue CmpOp1) {
2234 // There is no hardware support for v4f32, so extend the vector into
2235 // two v2f64s and compare those.
2236 if (CmpOp0.getValueType() == MVT::v4f32) {
2237 SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0);
2238 SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0);
2239 SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1);
2240 SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1);
2241 SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
2242 SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
2243 return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
2245 return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
2248 // Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
2249 // an integer mask of type VT.
2250 static SDValue lowerVectorSETCC(SelectionDAG &DAG, SDLoc DL, EVT VT,
2251 ISD::CondCode CC, SDValue CmpOp0,
2253 bool IsFP = CmpOp0.getValueType().isFloatingPoint();
2254 bool Invert = false;
2257 // Handle tests for order using (or (ogt y x) (oge x y)).
2261 assert(IsFP && "Unexpected integer comparison");
2262 SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0);
2263 SDValue GE = getVectorCmp(DAG, SystemZISD::VFCMPHE, DL, VT, CmpOp0, CmpOp1);
2264 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
2268 // Handle <> tests using (or (ogt y x) (ogt x y)).
2272 assert(IsFP && "Unexpected integer comparison");
2273 SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0);
2274 SDValue GT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp0, CmpOp1);
2275 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
2279 // Otherwise a single comparison is enough. It doesn't really
2280 // matter whether we try the inversion or the swap first, since
2281 // there are no cases where both work.
2283 if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert))
2284 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1);
2286 CC = ISD::getSetCCSwappedOperands(CC);
2287 if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert))
2288 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0);
2290 llvm_unreachable("Unhandled comparison");
2295 SDValue Mask = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
2296 DAG.getConstant(65535, DL, MVT::i32));
2297 Mask = DAG.getNode(ISD::BITCAST, DL, VT, Mask);
2298 Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
2303 SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
2304 SelectionDAG &DAG) const {
2305 SDValue CmpOp0 = Op.getOperand(0);
2306 SDValue CmpOp1 = Op.getOperand(1);
2307 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2309 EVT VT = Op.getValueType();
2311 return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
2313 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2314 SDValue Glue = emitCmp(DAG, DL, C);
2315 return emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
2318 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2319 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2320 SDValue CmpOp0 = Op.getOperand(2);
2321 SDValue CmpOp1 = Op.getOperand(3);
2322 SDValue Dest = Op.getOperand(4);
2325 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2326 SDValue Glue = emitCmp(DAG, DL, C);
2327 return DAG.getNode(SystemZISD::BR_CCMASK, DL, Op.getValueType(),
2328 Op.getOperand(0), DAG.getConstant(C.CCValid, DL, MVT::i32),
2329 DAG.getConstant(C.CCMask, DL, MVT::i32), Dest, Glue);
2332 // Return true if Pos is CmpOp and Neg is the negative of CmpOp,
2333 // allowing Pos and Neg to be wider than CmpOp.
2334 static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
2335 return (Neg.getOpcode() == ISD::SUB &&
2336 Neg.getOperand(0).getOpcode() == ISD::Constant &&
2337 cast<ConstantSDNode>(Neg.getOperand(0))->getZExtValue() == 0 &&
2338 Neg.getOperand(1) == Pos &&
2340 (Pos.getOpcode() == ISD::SIGN_EXTEND &&
2341 Pos.getOperand(0) == CmpOp)));
2344 // Return the absolute or negative absolute of Op; IsNegative decides which.
2345 static SDValue getAbsolute(SelectionDAG &DAG, SDLoc DL, SDValue Op,
2347 Op = DAG.getNode(SystemZISD::IABS, DL, Op.getValueType(), Op);
2349 Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
2350 DAG.getConstant(0, DL, Op.getValueType()), Op);
2354 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
2355 SelectionDAG &DAG) const {
2356 SDValue CmpOp0 = Op.getOperand(0);
2357 SDValue CmpOp1 = Op.getOperand(1);
2358 SDValue TrueOp = Op.getOperand(2);
2359 SDValue FalseOp = Op.getOperand(3);
2360 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2363 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2365 // Check for absolute and negative-absolute selections, including those
2366 // where the comparison value is sign-extended (for LPGFR and LNGFR).
2367 // This check supplements the one in DAGCombiner.
2368 if (C.Opcode == SystemZISD::ICMP &&
2369 C.CCMask != SystemZ::CCMASK_CMP_EQ &&
2370 C.CCMask != SystemZ::CCMASK_CMP_NE &&
2371 C.Op1.getOpcode() == ISD::Constant &&
2372 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2373 if (isAbsolute(C.Op0, TrueOp, FalseOp))
2374 return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
2375 if (isAbsolute(C.Op0, FalseOp, TrueOp))
2376 return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
2379 SDValue Glue = emitCmp(DAG, DL, C);
2381 // Special case for handling -1/0 results. The shifts we use here
2382 // should get optimized with the IPM conversion sequence.
2383 auto *TrueC = dyn_cast<ConstantSDNode>(TrueOp);
2384 auto *FalseC = dyn_cast<ConstantSDNode>(FalseOp);
2385 if (TrueC && FalseC) {
2386 int64_t TrueVal = TrueC->getSExtValue();
2387 int64_t FalseVal = FalseC->getSExtValue();
2388 if ((TrueVal == -1 && FalseVal == 0) || (TrueVal == 0 && FalseVal == -1)) {
2389 // Invert the condition if we want -1 on false.
2391 C.CCMask ^= C.CCValid;
2392 SDValue Result = emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
2393 EVT VT = Op.getValueType();
2394 // Extend the result to VT. Upper bits are ignored.
2396 Result = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Result);
2397 // Sign-extend from the low bit.
2398 SDValue ShAmt = DAG.getConstant(VT.getSizeInBits() - 1, DL, MVT::i32);
2399 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Result, ShAmt);
2400 return DAG.getNode(ISD::SRA, DL, VT, Shl, ShAmt);
2404 SDValue Ops[] = {TrueOp, FalseOp, DAG.getConstant(C.CCValid, DL, MVT::i32),
2405 DAG.getConstant(C.CCMask, DL, MVT::i32), Glue};
2407 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
2408 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VTs, Ops);
2411 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
2412 SelectionDAG &DAG) const {
2414 const GlobalValue *GV = Node->getGlobal();
2415 int64_t Offset = Node->getOffset();
2416 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2417 Reloc::Model RM = DAG.getTarget().getRelocationModel();
2418 CodeModel::Model CM = DAG.getTarget().getCodeModel();
2421 if (Subtarget.isPC32DBLSymbol(GV, RM, CM)) {
2422 // Assign anchors at 1<<12 byte boundaries.
2423 uint64_t Anchor = Offset & ~uint64_t(0xfff);
2424 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
2425 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2427 // The offset can be folded into the address if it is aligned to a halfword.
2429 if (Offset != 0 && (Offset & 1) == 0) {
2430 SDValue Full = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
2431 Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
2435 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
2436 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2437 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2438 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2439 false, false, false, 0);
2442 // If there was a non-zero offset that we didn't fold, create an explicit
2445 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
2446 DAG.getConstant(Offset, DL, PtrVT));
2451 SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
2454 SDValue GOTOffset) const {
2456 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2457 SDValue Chain = DAG.getEntryNode();
2460 // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
2461 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2462 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
2463 Glue = Chain.getValue(1);
2464 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
2465 Glue = Chain.getValue(1);
2467 // The first call operand is the chain and the second is the TLS symbol.
2468 SmallVector<SDValue, 8> Ops;
2469 Ops.push_back(Chain);
2470 Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
2471 Node->getValueType(0),
2474 // Add argument registers to the end of the list so that they are
2475 // known live into the call.
2476 Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
2477 Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
2479 // Add a register mask operand representing the call-preserved registers.
2480 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2481 const uint32_t *Mask =
2482 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
2483 assert(Mask && "Missing call preserved mask for calling convention");
2484 Ops.push_back(DAG.getRegisterMask(Mask));
2486 // Glue the call to the argument copies.
2487 Ops.push_back(Glue);
2490 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2491 Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
2492 Glue = Chain.getValue(1);
2494 // Copy the return value from %r2.
2495 return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
2498 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
2499 SelectionDAG &DAG) const {
2500 if (DAG.getTarget().Options.EmulatedTLS)
2501 return LowerToTLSEmulatedModel(Node, DAG);
2503 const GlobalValue *GV = Node->getGlobal();
2504 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2505 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
2507 // The high part of the thread pointer is in access register 0.
2508 SDValue TPHi = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
2509 DAG.getConstant(0, DL, MVT::i32));
2510 TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
2512 // The low part of the thread pointer is in access register 1.
2513 SDValue TPLo = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
2514 DAG.getConstant(1, DL, MVT::i32));
2515 TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
2517 // Merge them into a single 64-bit address.
2518 SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
2519 DAG.getConstant(32, DL, PtrVT));
2520 SDValue TP = DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
2522 // Get the offset of GA from the thread pointer, based on the TLS model.
2525 case TLSModel::GeneralDynamic: {
2526 // Load the GOT offset of the tls_index (module ID / per-symbol offset).
2527 SystemZConstantPoolValue *CPV =
2528 SystemZConstantPoolValue::Create(GV, SystemZCP::TLSGD);
2530 Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2531 Offset = DAG.getLoad(
2532 PtrVT, DL, DAG.getEntryNode(), Offset,
2533 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2536 // Call __tls_get_offset to retrieve the offset.
2537 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
2541 case TLSModel::LocalDynamic: {
2542 // Load the GOT offset of the module ID.
2543 SystemZConstantPoolValue *CPV =
2544 SystemZConstantPoolValue::Create(GV, SystemZCP::TLSLDM);
2546 Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2547 Offset = DAG.getLoad(
2548 PtrVT, DL, DAG.getEntryNode(), Offset,
2549 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2552 // Call __tls_get_offset to retrieve the module base offset.
2553 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
2555 // Note: The SystemZLDCleanupPass will remove redundant computations
2556 // of the module base offset. Count total number of local-dynamic
2557 // accesses to trigger execution of that pass.
2558 SystemZMachineFunctionInfo* MFI =
2559 DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>();
2560 MFI->incNumLocalDynamicTLSAccesses();
2562 // Add the per-symbol offset.
2563 CPV = SystemZConstantPoolValue::Create(GV, SystemZCP::DTPOFF);
2565 SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, 8);
2566 DTPOffset = DAG.getLoad(
2567 PtrVT, DL, DAG.getEntryNode(), DTPOffset,
2568 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2571 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
2575 case TLSModel::InitialExec: {
2576 // Load the offset from the GOT.
2577 Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2578 SystemZII::MO_INDNTPOFF);
2579 Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
2580 Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset,
2581 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2582 false, false, false, 0);
2586 case TLSModel::LocalExec: {
2587 // Force the offset into the constant pool and load it from there.
2588 SystemZConstantPoolValue *CPV =
2589 SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF);
2591 Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2592 Offset = DAG.getLoad(
2593 PtrVT, DL, DAG.getEntryNode(), Offset,
2594 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
2600 // Add the base and offset together.
2601 return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
2604 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
2605 SelectionDAG &DAG) const {
2607 const BlockAddress *BA = Node->getBlockAddress();
2608 int64_t Offset = Node->getOffset();
2609 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2611 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
2612 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2616 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
2617 SelectionDAG &DAG) const {
2619 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2620 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2622 // Use LARL to load the address of the table.
2623 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2626 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
2627 SelectionDAG &DAG) const {
2629 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2632 if (CP->isMachineConstantPoolEntry())
2633 Result = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2634 CP->getAlignment());
2636 Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2637 CP->getAlignment(), CP->getOffset());
2639 // Use LARL to load the address of the constant pool entry.
2640 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2643 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
2644 SelectionDAG &DAG) const {
2646 SDValue In = Op.getOperand(0);
2647 EVT InVT = In.getValueType();
2648 EVT ResVT = Op.getValueType();
2650 // Convert loads directly. This is normally done by DAGCombiner,
2651 // but we need this case for bitcasts that are created during lowering
2652 // and which are then lowered themselves.
2653 if (auto *LoadN = dyn_cast<LoadSDNode>(In))
2654 return DAG.getLoad(ResVT, DL, LoadN->getChain(), LoadN->getBasePtr(),
2655 LoadN->getMemOperand());
2657 if (InVT == MVT::i32 && ResVT == MVT::f32) {
2659 if (Subtarget.hasHighWord()) {
2660 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
2662 In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
2663 MVT::i64, SDValue(U64, 0), In);
2665 In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
2666 In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
2667 DAG.getConstant(32, DL, MVT::i64));
2669 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
2670 return DAG.getTargetExtractSubreg(SystemZ::subreg_r32,
2671 DL, MVT::f32, Out64);
2673 if (InVT == MVT::f32 && ResVT == MVT::i32) {
2674 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
2675 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_r32, DL,
2676 MVT::f64, SDValue(U64, 0), In);
2677 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
2678 if (Subtarget.hasHighWord())
2679 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
2681 SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
2682 DAG.getConstant(32, DL, MVT::i64));
2683 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
2685 llvm_unreachable("Unexpected bitcast combination");
2688 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
2689 SelectionDAG &DAG) const {
2690 MachineFunction &MF = DAG.getMachineFunction();
2691 SystemZMachineFunctionInfo *FuncInfo =
2692 MF.getInfo<SystemZMachineFunctionInfo>();
2693 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2695 SDValue Chain = Op.getOperand(0);
2696 SDValue Addr = Op.getOperand(1);
2697 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2700 // The initial values of each field.
2701 const unsigned NumFields = 4;
2702 SDValue Fields[NumFields] = {
2703 DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
2704 DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
2705 DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
2706 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
2709 // Store each field into its respective slot.
2710 SDValue MemOps[NumFields];
2711 unsigned Offset = 0;
2712 for (unsigned I = 0; I < NumFields; ++I) {
2713 SDValue FieldAddr = Addr;
2715 FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
2716 DAG.getIntPtrConstant(Offset, DL));
2717 MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
2718 MachinePointerInfo(SV, Offset),
2722 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2725 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
2726 SelectionDAG &DAG) const {
2727 SDValue Chain = Op.getOperand(0);
2728 SDValue DstPtr = Op.getOperand(1);
2729 SDValue SrcPtr = Op.getOperand(2);
2730 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2731 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
2734 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32, DL),
2735 /*Align*/8, /*isVolatile*/false, /*AlwaysInline*/false,
2736 /*isTailCall*/false,
2737 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
2740 SDValue SystemZTargetLowering::
2741 lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
2742 SDValue Chain = Op.getOperand(0);
2743 SDValue Size = Op.getOperand(1);
2746 unsigned SPReg = getStackPointerRegisterToSaveRestore();
2748 // Get a reference to the stack pointer.
2749 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
2751 // Get the new stack pointer value.
2752 SDValue NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, Size);
2754 // Copy the new stack pointer back.
2755 Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
2757 // The allocated data lives above the 160 bytes allocated for the standard
2758 // frame, plus any outgoing stack arguments. We don't know how much that
2759 // amounts to yet, so emit a special ADJDYNALLOC placeholder.
2760 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
2761 SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
2763 SDValue Ops[2] = { Result, Chain };
2764 return DAG.getMergeValues(Ops, DL);
2767 SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
2768 SelectionDAG &DAG) const {
2769 EVT VT = Op.getValueType();
2773 // Just do a normal 64-bit multiplication and extract the results.
2774 // We define this so that it can be used for constant division.
2775 lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
2776 Op.getOperand(1), Ops[1], Ops[0]);
2778 // Do a full 128-bit multiplication based on UMUL_LOHI64:
2780 // (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
2782 // but using the fact that the upper halves are either all zeros
2785 // (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
2787 // and grouping the right terms together since they are quicker than the
2790 // (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
2791 SDValue C63 = DAG.getConstant(63, DL, MVT::i64);
2792 SDValue LL = Op.getOperand(0);
2793 SDValue RL = Op.getOperand(1);
2794 SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
2795 SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
2796 // UMUL_LOHI64 returns the low result in the odd register and the high
2797 // result in the even register. SMUL_LOHI is defined to return the
2798 // low half first, so the results are in reverse order.
2799 lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
2800 LL, RL, Ops[1], Ops[0]);
2801 SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
2802 SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
2803 SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
2804 Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
2806 return DAG.getMergeValues(Ops, DL);
2809 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
2810 SelectionDAG &DAG) const {
2811 EVT VT = Op.getValueType();
2815 // Just do a normal 64-bit multiplication and extract the results.
2816 // We define this so that it can be used for constant division.
2817 lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
2818 Op.getOperand(1), Ops[1], Ops[0]);
2820 // UMUL_LOHI64 returns the low result in the odd register and the high
2821 // result in the even register. UMUL_LOHI is defined to return the
2822 // low half first, so the results are in reverse order.
2823 lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
2824 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
2825 return DAG.getMergeValues(Ops, DL);
2828 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
2829 SelectionDAG &DAG) const {
2830 SDValue Op0 = Op.getOperand(0);
2831 SDValue Op1 = Op.getOperand(1);
2832 EVT VT = Op.getValueType();
2836 // We use DSGF for 32-bit division.
2838 Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
2839 Opcode = SystemZISD::SDIVREM32;
2840 } else if (DAG.ComputeNumSignBits(Op1) > 32) {
2841 Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
2842 Opcode = SystemZISD::SDIVREM32;
2844 Opcode = SystemZISD::SDIVREM64;
2846 // DSG(F) takes a 64-bit dividend, so the even register in the GR128
2847 // input is "don't care". The instruction returns the remainder in
2848 // the even register and the quotient in the odd register.
2850 lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, Opcode,
2851 Op0, Op1, Ops[1], Ops[0]);
2852 return DAG.getMergeValues(Ops, DL);
2855 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
2856 SelectionDAG &DAG) const {
2857 EVT VT = Op.getValueType();
2860 // DL(G) uses a double-width dividend, so we need to clear the even
2861 // register in the GR128 input. The instruction returns the remainder
2862 // in the even register and the quotient in the odd register.
2865 lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_32, SystemZISD::UDIVREM32,
2866 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
2868 lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_64, SystemZISD::UDIVREM64,
2869 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
2870 return DAG.getMergeValues(Ops, DL);
2873 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
2874 assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
2876 // Get the known-zero masks for each operand.
2877 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
2878 APInt KnownZero[2], KnownOne[2];
2879 DAG.computeKnownBits(Ops[0], KnownZero[0], KnownOne[0]);
2880 DAG.computeKnownBits(Ops[1], KnownZero[1], KnownOne[1]);
2882 // See if the upper 32 bits of one operand and the lower 32 bits of the
2883 // other are known zero. They are the low and high operands respectively.
2884 uint64_t Masks[] = { KnownZero[0].getZExtValue(),
2885 KnownZero[1].getZExtValue() };
2887 if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
2889 else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
2894 SDValue LowOp = Ops[Low];
2895 SDValue HighOp = Ops[High];
2897 // If the high part is a constant, we're better off using IILH.
2898 if (HighOp.getOpcode() == ISD::Constant)
2901 // If the low part is a constant that is outside the range of LHI,
2902 // then we're better off using IILF.
2903 if (LowOp.getOpcode() == ISD::Constant) {
2904 int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
2905 if (!isInt<16>(Value))
2909 // Check whether the high part is an AND that doesn't change the
2910 // high 32 bits and just masks out low bits. We can skip it if so.
2911 if (HighOp.getOpcode() == ISD::AND &&
2912 HighOp.getOperand(1).getOpcode() == ISD::Constant) {
2913 SDValue HighOp0 = HighOp.getOperand(0);
2914 uint64_t Mask = cast<ConstantSDNode>(HighOp.getOperand(1))->getZExtValue();
2915 if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
2919 // Take advantage of the fact that all GR32 operations only change the
2920 // low 32 bits by truncating Low to an i32 and inserting it directly
2921 // using a subreg. The interesting cases are those where the truncation
2924 SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
2925 return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
2926 MVT::i64, HighOp, Low32);
2929 SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op,
2930 SelectionDAG &DAG) const {
2931 EVT VT = Op.getValueType();
2933 Op = Op.getOperand(0);
2935 // Handle vector types via VPOPCT.
2936 if (VT.isVector()) {
2937 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op);
2938 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op);
2939 switch (VT.getVectorElementType().getSizeInBits()) {
2943 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
2944 SDValue Shift = DAG.getConstant(8, DL, MVT::i32);
2945 SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift);
2946 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
2947 Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift);
2951 SDValue Tmp = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
2952 DAG.getConstant(0, DL, MVT::i32));
2953 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
2957 SDValue Tmp = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
2958 DAG.getConstant(0, DL, MVT::i32));
2959 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp);
2960 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
2964 llvm_unreachable("Unexpected type");
2969 // Get the known-zero mask for the operand.
2970 APInt KnownZero, KnownOne;
2971 DAG.computeKnownBits(Op, KnownZero, KnownOne);
2972 unsigned NumSignificantBits = (~KnownZero).getActiveBits();
2973 if (NumSignificantBits == 0)
2974 return DAG.getConstant(0, DL, VT);
2976 // Skip known-zero high parts of the operand.
2977 int64_t OrigBitSize = VT.getSizeInBits();
2978 int64_t BitSize = (int64_t)1 << Log2_32_Ceil(NumSignificantBits);
2979 BitSize = std::min(BitSize, OrigBitSize);
2981 // The POPCNT instruction counts the number of bits in each byte.
2982 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op);
2983 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op);
2984 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
2986 // Add up per-byte counts in a binary tree. All bits of Op at
2987 // position larger than BitSize remain zero throughout.
2988 for (int64_t I = BitSize / 2; I >= 8; I = I / 2) {
2989 SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT));
2990 if (BitSize != OrigBitSize)
2991 Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp,
2992 DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT));
2993 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
2996 // Extract overall result from high byte.
2998 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
2999 DAG.getConstant(BitSize - 8, DL, VT));
3004 // Op is an atomic load. Lower it into a normal volatile load.
3005 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
3006 SelectionDAG &DAG) const {
3007 auto *Node = cast<AtomicSDNode>(Op.getNode());
3008 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), Op.getValueType(),
3009 Node->getChain(), Node->getBasePtr(),
3010 Node->getMemoryVT(), Node->getMemOperand());
3013 // Op is an atomic store. Lower it into a normal volatile store followed
3014 // by a serialization.
3015 SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
3016 SelectionDAG &DAG) const {
3017 auto *Node = cast<AtomicSDNode>(Op.getNode());
3018 SDValue Chain = DAG.getTruncStore(Node->getChain(), SDLoc(Op), Node->getVal(),
3019 Node->getBasePtr(), Node->getMemoryVT(),
3020 Node->getMemOperand());
3021 return SDValue(DAG.getMachineNode(SystemZ::Serialize, SDLoc(Op), MVT::Other,
3025 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation. Lower the first
3026 // two into the fullword ATOMIC_LOADW_* operation given by Opcode.
3027 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op,
3029 unsigned Opcode) const {
3030 auto *Node = cast<AtomicSDNode>(Op.getNode());
3032 // 32-bit operations need no code outside the main loop.
3033 EVT NarrowVT = Node->getMemoryVT();
3034 EVT WideVT = MVT::i32;
3035 if (NarrowVT == WideVT)
3038 int64_t BitSize = NarrowVT.getSizeInBits();
3039 SDValue ChainIn = Node->getChain();
3040 SDValue Addr = Node->getBasePtr();
3041 SDValue Src2 = Node->getVal();
3042 MachineMemOperand *MMO = Node->getMemOperand();
3044 EVT PtrVT = Addr.getValueType();
3046 // Convert atomic subtracts of constants into additions.
3047 if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
3048 if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
3049 Opcode = SystemZISD::ATOMIC_LOADW_ADD;
3050 Src2 = DAG.getConstant(-Const->getSExtValue(), DL, Src2.getValueType());
3053 // Get the address of the containing word.
3054 SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
3055 DAG.getConstant(-4, DL, PtrVT));
3057 // Get the number of bits that the word must be rotated left in order
3058 // to bring the field to the top bits of a GR32.
3059 SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
3060 DAG.getConstant(3, DL, PtrVT));
3061 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
3063 // Get the complementing shift amount, for rotating a field in the top
3064 // bits back to its proper position.
3065 SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
3066 DAG.getConstant(0, DL, WideVT), BitShift);
3068 // Extend the source operand to 32 bits and prepare it for the inner loop.
3069 // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
3070 // operations require the source to be shifted in advance. (This shift
3071 // can be folded if the source is constant.) For AND and NAND, the lower
3072 // bits must be set, while for other opcodes they should be left clear.
3073 if (Opcode != SystemZISD::ATOMIC_SWAPW)
3074 Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
3075 DAG.getConstant(32 - BitSize, DL, WideVT));
3076 if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
3077 Opcode == SystemZISD::ATOMIC_LOADW_NAND)
3078 Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
3079 DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT));
3081 // Construct the ATOMIC_LOADW_* node.
3082 SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
3083 SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
3084 DAG.getConstant(BitSize, DL, WideVT) };
3085 SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
3088 // Rotate the result of the final CS so that the field is in the lower
3089 // bits of a GR32, then truncate it.
3090 SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
3091 DAG.getConstant(BitSize, DL, WideVT));
3092 SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
3094 SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
3095 return DAG.getMergeValues(RetOps, DL);
3098 // Op is an ATOMIC_LOAD_SUB operation. Lower 8- and 16-bit operations
3099 // into ATOMIC_LOADW_SUBs and decide whether to convert 32- and 64-bit
3100 // operations into additions.
3101 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
3102 SelectionDAG &DAG) const {
3103 auto *Node = cast<AtomicSDNode>(Op.getNode());
3104 EVT MemVT = Node->getMemoryVT();
3105 if (MemVT == MVT::i32 || MemVT == MVT::i64) {
3106 // A full-width operation.
3107 assert(Op.getValueType() == MemVT && "Mismatched VTs");
3108 SDValue Src2 = Node->getVal();
3112 if (auto *Op2 = dyn_cast<ConstantSDNode>(Src2)) {
3113 // Use an addition if the operand is constant and either LAA(G) is
3114 // available or the negative value is in the range of A(G)FHI.
3115 int64_t Value = (-Op2->getAPIntValue()).getSExtValue();
3116 if (isInt<32>(Value) || Subtarget.hasInterlockedAccess1())
3117 NegSrc2 = DAG.getConstant(Value, DL, MemVT);
3118 } else if (Subtarget.hasInterlockedAccess1())
3119 // Use LAA(G) if available.
3120 NegSrc2 = DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT),
3123 if (NegSrc2.getNode())
3124 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT,
3125 Node->getChain(), Node->getBasePtr(), NegSrc2,
3126 Node->getMemOperand(), Node->getOrdering(),
3127 Node->getSynchScope());
3129 // Use the node as-is.
3133 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
3136 // Node is an 8- or 16-bit ATOMIC_CMP_SWAP operation. Lower the first two
3137 // into a fullword ATOMIC_CMP_SWAPW operation.
3138 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
3139 SelectionDAG &DAG) const {
3140 auto *Node = cast<AtomicSDNode>(Op.getNode());
3142 // We have native support for 32-bit compare and swap.
3143 EVT NarrowVT = Node->getMemoryVT();
3144 EVT WideVT = MVT::i32;
3145 if (NarrowVT == WideVT)
3148 int64_t BitSize = NarrowVT.getSizeInBits();
3149 SDValue ChainIn = Node->getOperand(0);
3150 SDValue Addr = Node->getOperand(1);
3151 SDValue CmpVal = Node->getOperand(2);
3152 SDValue SwapVal = Node->getOperand(3);
3153 MachineMemOperand *MMO = Node->getMemOperand();
3155 EVT PtrVT = Addr.getValueType();
3157 // Get the address of the containing word.
3158 SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
3159 DAG.getConstant(-4, DL, PtrVT));
3161 // Get the number of bits that the word must be rotated left in order
3162 // to bring the field to the top bits of a GR32.
3163 SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
3164 DAG.getConstant(3, DL, PtrVT));
3165 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
3167 // Get the complementing shift amount, for rotating a field in the top
3168 // bits back to its proper position.
3169 SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
3170 DAG.getConstant(0, DL, WideVT), BitShift);
3172 // Construct the ATOMIC_CMP_SWAPW node.
3173 SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
3174 SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
3175 NegBitShift, DAG.getConstant(BitSize, DL, WideVT) };
3176 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
3177 VTList, Ops, NarrowVT, MMO);
3181 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
3182 SelectionDAG &DAG) const {
3183 MachineFunction &MF = DAG.getMachineFunction();
3184 MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
3185 return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
3186 SystemZ::R15D, Op.getValueType());
3189 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
3190 SelectionDAG &DAG) const {
3191 MachineFunction &MF = DAG.getMachineFunction();
3192 MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
3193 return DAG.getCopyToReg(Op.getOperand(0), SDLoc(Op),
3194 SystemZ::R15D, Op.getOperand(1));
3197 SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
3198 SelectionDAG &DAG) const {
3199 bool IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3201 // Just preserve the chain.
3202 return Op.getOperand(0);
3205 bool IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
3206 unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
3207 auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
3210 DAG.getConstant(Code, DL, MVT::i32),
3213 return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, DL,
3214 Node->getVTList(), Ops,
3215 Node->getMemoryVT(), Node->getMemOperand());
3218 // Return an i32 that contains the value of CC immediately after After,
3219 // whose final operand must be MVT::Glue.
3220 static SDValue getCCResult(SelectionDAG &DAG, SDNode *After) {
3222 SDValue Glue = SDValue(After, After->getNumValues() - 1);
3223 SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
3224 return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM,
3225 DAG.getConstant(SystemZ::IPM_CC, DL, MVT::i32));
3229 SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
3230 SelectionDAG &DAG) const {
3231 unsigned Opcode, CCValid;
3232 if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) {
3233 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
3234 SDValue Glued = emitIntrinsicWithChainAndGlue(DAG, Op, Opcode);
3235 SDValue CC = getCCResult(DAG, Glued.getNode());
3236 DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC);
3244 SystemZTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
3245 SelectionDAG &DAG) const {
3246 unsigned Opcode, CCValid;
3247 if (isIntrinsicWithCC(Op, Opcode, CCValid)) {
3248 SDValue Glued = emitIntrinsicWithGlue(DAG, Op, Opcode);
3249 SDValue CC = getCCResult(DAG, Glued.getNode());
3250 if (Op->getNumValues() == 1)
3252 assert(Op->getNumValues() == 2 && "Expected a CC and non-CC result");
3253 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), Op->getVTList(), Glued,
3257 unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3259 case Intrinsic::s390_vpdi:
3260 return DAG.getNode(SystemZISD::PERMUTE_DWORDS, SDLoc(Op), Op.getValueType(),
3261 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3263 case Intrinsic::s390_vperm:
3264 return DAG.getNode(SystemZISD::PERMUTE, SDLoc(Op), Op.getValueType(),
3265 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3267 case Intrinsic::s390_vuphb:
3268 case Intrinsic::s390_vuphh:
3269 case Intrinsic::s390_vuphf:
3270 return DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(Op), Op.getValueType(),
3273 case Intrinsic::s390_vuplhb:
3274 case Intrinsic::s390_vuplhh:
3275 case Intrinsic::s390_vuplhf:
3276 return DAG.getNode(SystemZISD::UNPACKL_HIGH, SDLoc(Op), Op.getValueType(),
3279 case Intrinsic::s390_vuplb:
3280 case Intrinsic::s390_vuplhw:
3281 case Intrinsic::s390_vuplf:
3282 return DAG.getNode(SystemZISD::UNPACK_LOW, SDLoc(Op), Op.getValueType(),
3285 case Intrinsic::s390_vupllb:
3286 case Intrinsic::s390_vupllh:
3287 case Intrinsic::s390_vupllf:
3288 return DAG.getNode(SystemZISD::UNPACKL_LOW, SDLoc(Op), Op.getValueType(),
3291 case Intrinsic::s390_vsumb:
3292 case Intrinsic::s390_vsumh:
3293 case Intrinsic::s390_vsumgh:
3294 case Intrinsic::s390_vsumgf:
3295 case Intrinsic::s390_vsumqf:
3296 case Intrinsic::s390_vsumqg:
3297 return DAG.getNode(SystemZISD::VSUM, SDLoc(Op), Op.getValueType(),
3298 Op.getOperand(1), Op.getOperand(2));
3305 // Says that SystemZISD operation Opcode can be used to perform the equivalent
3306 // of a VPERM with permute vector Bytes. If Opcode takes three operands,
3307 // Operand is the constant third operand, otherwise it is the number of
3308 // bytes in each element of the result.
3312 unsigned char Bytes[SystemZ::VectorBytes];
3316 static const Permute PermuteForms[] = {
3318 { SystemZISD::MERGE_HIGH, 8,
3319 { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } },
3321 { SystemZISD::MERGE_HIGH, 4,
3322 { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } },
3324 { SystemZISD::MERGE_HIGH, 2,
3325 { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } },
3327 { SystemZISD::MERGE_HIGH, 1,
3328 { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } },
3330 { SystemZISD::MERGE_LOW, 8,
3331 { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } },
3333 { SystemZISD::MERGE_LOW, 4,
3334 { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
3336 { SystemZISD::MERGE_LOW, 2,
3337 { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
3339 { SystemZISD::MERGE_LOW, 1,
3340 { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
3342 { SystemZISD::PACK, 4,
3343 { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } },
3345 { SystemZISD::PACK, 2,
3346 { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
3348 { SystemZISD::PACK, 1,
3349 { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
3350 // VPDI V1, V2, 4 (low half of V1, high half of V2)
3351 { SystemZISD::PERMUTE_DWORDS, 4,
3352 { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } },
3353 // VPDI V1, V2, 1 (high half of V1, low half of V2)
3354 { SystemZISD::PERMUTE_DWORDS, 1,
3355 { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } }
3358 // Called after matching a vector shuffle against a particular pattern.
3359 // Both the original shuffle and the pattern have two vector operands.
3360 // OpNos[0] is the operand of the original shuffle that should be used for
3361 // operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything.
3362 // OpNos[1] is the same for operand 1 of the pattern. Resolve these -1s and
3363 // set OpNo0 and OpNo1 to the shuffle operands that should actually be used
3364 // for operands 0 and 1 of the pattern.
3365 static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) {
3369 OpNo0 = OpNo1 = OpNos[1];
3370 } else if (OpNos[1] < 0) {
3371 OpNo0 = OpNo1 = OpNos[0];
3379 // Bytes is a VPERM-like permute vector, except that -1 is used for
3380 // undefined bytes. Return true if the VPERM can be implemented using P.
3381 // When returning true set OpNo0 to the VPERM operand that should be
3382 // used for operand 0 of P and likewise OpNo1 for operand 1 of P.
3384 // For example, if swapping the VPERM operands allows P to match, OpNo0
3385 // will be 1 and OpNo1 will be 0. If instead Bytes only refers to one
3386 // operand, but rewriting it to use two duplicated operands allows it to
3387 // match P, then OpNo0 and OpNo1 will be the same.
3388 static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P,
3389 unsigned &OpNo0, unsigned &OpNo1) {
3390 int OpNos[] = { -1, -1 };
3391 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
3394 // Make sure that the two permute vectors use the same suboperand
3395 // byte number. Only the operand numbers (the high bits) are
3396 // allowed to differ.
3397 if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1))
3399 int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes;
3400 int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes;
3401 // Make sure that the operand mappings are consistent with previous
3403 if (OpNos[ModelOpNo] == 1 - RealOpNo)
3405 OpNos[ModelOpNo] = RealOpNo;
3408 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
3411 // As above, but search for a matching permute.
3412 static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes,
3413 unsigned &OpNo0, unsigned &OpNo1) {
3414 for (auto &P : PermuteForms)
3415 if (matchPermute(Bytes, P, OpNo0, OpNo1))
3420 // Bytes is a VPERM-like permute vector, except that -1 is used for
3421 // undefined bytes. This permute is an operand of an outer permute.
3422 // See whether redistributing the -1 bytes gives a shuffle that can be
3423 // implemented using P. If so, set Transform to a VPERM-like permute vector
3424 // that, when applied to the result of P, gives the original permute in Bytes.
3425 static bool matchDoublePermute(const SmallVectorImpl<int> &Bytes,
3427 SmallVectorImpl<int> &Transform) {
3429 for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) {
3430 int Elt = Bytes[From];
3432 // Byte number From of the result is undefined.
3433 Transform[From] = -1;
3435 while (P.Bytes[To] != Elt) {
3437 if (To == SystemZ::VectorBytes)
3440 Transform[From] = To;
3446 // As above, but search for a matching permute.
3447 static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes,
3448 SmallVectorImpl<int> &Transform) {
3449 for (auto &P : PermuteForms)
3450 if (matchDoublePermute(Bytes, P, Transform))
3455 // Convert the mask of the given VECTOR_SHUFFLE into a byte-level mask,
3456 // as if it had type vNi8.
3457 static void getVPermMask(ShuffleVectorSDNode *VSN,
3458 SmallVectorImpl<int> &Bytes) {
3459 EVT VT = VSN->getValueType(0);
3460 unsigned NumElements = VT.getVectorNumElements();
3461 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3462 Bytes.resize(NumElements * BytesPerElement, -1);
3463 for (unsigned I = 0; I < NumElements; ++I) {
3464 int Index = VSN->getMaskElt(I);
3466 for (unsigned J = 0; J < BytesPerElement; ++J)
3467 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
3471 // Bytes is a VPERM-like permute vector, except that -1 is used for
3472 // undefined bytes. See whether bytes [Start, Start + BytesPerElement) of
3473 // the result come from a contiguous sequence of bytes from one input.
3474 // Set Base to the selector for the first byte if so.
3475 static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start,
3476 unsigned BytesPerElement, int &Base) {
3478 for (unsigned I = 0; I < BytesPerElement; ++I) {
3479 if (Bytes[Start + I] >= 0) {
3480 unsigned Elem = Bytes[Start + I];
3483 // Make sure the bytes would come from one input operand.
3484 if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size())
3486 } else if (unsigned(Base) != Elem - I)
3493 // Bytes is a VPERM-like permute vector, except that -1 is used for
3494 // undefined bytes. Return true if it can be performed using VSLDI.
3495 // When returning true, set StartIndex to the shift amount and OpNo0
3496 // and OpNo1 to the VPERM operands that should be used as the first
3497 // and second shift operand respectively.
3498 static bool isShlDoublePermute(const SmallVectorImpl<int> &Bytes,
3499 unsigned &StartIndex, unsigned &OpNo0,
3501 int OpNos[] = { -1, -1 };
3503 for (unsigned I = 0; I < 16; ++I) {
3504 int Index = Bytes[I];
3506 int ExpectedShift = (Index - I) % SystemZ::VectorBytes;
3507 int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes;
3508 int RealOpNo = unsigned(Index) / SystemZ::VectorBytes;
3510 Shift = ExpectedShift;
3511 else if (Shift != ExpectedShift)
3513 // Make sure that the operand mappings are consistent with previous
3515 if (OpNos[ModelOpNo] == 1 - RealOpNo)
3517 OpNos[ModelOpNo] = RealOpNo;
3521 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
3524 // Create a node that performs P on operands Op0 and Op1, casting the
3525 // operands to the appropriate type. The type of the result is determined by P.
3526 static SDValue getPermuteNode(SelectionDAG &DAG, SDLoc DL,
3527 const Permute &P, SDValue Op0, SDValue Op1) {
3528 // VPDI (PERMUTE_DWORDS) always operates on v2i64s. The input
3529 // elements of a PACK are twice as wide as the outputs.
3530 unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 :
3531 P.Opcode == SystemZISD::PACK ? P.Operand * 2 :
3533 // Cast both operands to the appropriate type.
3534 MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8),
3535 SystemZ::VectorBytes / InBytes);
3536 Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0);
3537 Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1);
3539 if (P.Opcode == SystemZISD::PERMUTE_DWORDS) {
3540 SDValue Op2 = DAG.getConstant(P.Operand, DL, MVT::i32);
3541 Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2);
3542 } else if (P.Opcode == SystemZISD::PACK) {
3543 MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8),
3544 SystemZ::VectorBytes / P.Operand);
3545 Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1);
3547 Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1);
3552 // Bytes is a VPERM-like permute vector, except that -1 is used for
3553 // undefined bytes. Implement it on operands Ops[0] and Ops[1] using
3555 static SDValue getGeneralPermuteNode(SelectionDAG &DAG, SDLoc DL, SDValue *Ops,
3556 const SmallVectorImpl<int> &Bytes) {
3557 for (unsigned I = 0; I < 2; ++I)
3558 Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]);
3560 // First see whether VSLDI can be used.
3561 unsigned StartIndex, OpNo0, OpNo1;
3562 if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1))
3563 return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0],
3564 Ops[OpNo1], DAG.getConstant(StartIndex, DL, MVT::i32));
3566 // Fall back on VPERM. Construct an SDNode for the permute vector.
3567 SDValue IndexNodes[SystemZ::VectorBytes];
3568 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
3570 IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32);
3572 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
3573 SDValue Op2 = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, IndexNodes);
3574 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0], Ops[1], Op2);
3578 // Describes a general N-operand vector shuffle.
3579 struct GeneralShuffle {
3580 GeneralShuffle(EVT vt) : VT(vt) {}
3582 void add(SDValue, unsigned);
3583 SDValue getNode(SelectionDAG &, SDLoc);
3585 // The operands of the shuffle.
3586 SmallVector<SDValue, SystemZ::VectorBytes> Ops;
3588 // Index I is -1 if byte I of the result is undefined. Otherwise the
3589 // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand
3590 // Bytes[I] / SystemZ::VectorBytes.
3591 SmallVector<int, SystemZ::VectorBytes> Bytes;
3593 // The type of the shuffle result.
3598 // Add an extra undefined element to the shuffle.
3599 void GeneralShuffle::addUndef() {
3600 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3601 for (unsigned I = 0; I < BytesPerElement; ++I)
3602 Bytes.push_back(-1);
3605 // Add an extra element to the shuffle, taking it from element Elem of Op.
3606 // A null Op indicates a vector input whose value will be calculated later;
3607 // there is at most one such input per shuffle and it always has the same
3608 // type as the result.
3609 void GeneralShuffle::add(SDValue Op, unsigned Elem) {
3610 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3612 // The source vector can have wider elements than the result,
3613 // either through an explicit TRUNCATE or because of type legalization.
3614 // We want the least significant part.
3615 EVT FromVT = Op.getNode() ? Op.getValueType() : VT;
3616 unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize();
3617 assert(FromBytesPerElement >= BytesPerElement &&
3618 "Invalid EXTRACT_VECTOR_ELT");
3619 unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes +
3620 (FromBytesPerElement - BytesPerElement));
3622 // Look through things like shuffles and bitcasts.
3623 while (Op.getNode()) {
3624 if (Op.getOpcode() == ISD::BITCAST)
3625 Op = Op.getOperand(0);
3626 else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) {
3627 // See whether the bytes we need come from a contiguous part of one
3629 SmallVector<int, SystemZ::VectorBytes> OpBytes;
3630 getVPermMask(cast<ShuffleVectorSDNode>(Op), OpBytes);
3632 if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte))
3638 Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes);
3639 Byte = unsigned(NewByte) % SystemZ::VectorBytes;
3640 } else if (Op.getOpcode() == ISD::UNDEF) {
3647 // Make sure that the source of the extraction is in Ops.
3649 for (; OpNo < Ops.size(); ++OpNo)
3650 if (Ops[OpNo] == Op)
3652 if (OpNo == Ops.size())
3655 // Add the element to Bytes.
3656 unsigned Base = OpNo * SystemZ::VectorBytes + Byte;
3657 for (unsigned I = 0; I < BytesPerElement; ++I)
3658 Bytes.push_back(Base + I);
3661 // Return SDNodes for the completed shuffle.
3662 SDValue GeneralShuffle::getNode(SelectionDAG &DAG, SDLoc DL) {
3663 assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector");
3665 if (Ops.size() == 0)
3666 return DAG.getUNDEF(VT);
3668 // Make sure that there are at least two shuffle operands.
3669 if (Ops.size() == 1)
3670 Ops.push_back(DAG.getUNDEF(MVT::v16i8));
3672 // Create a tree of shuffles, deferring root node until after the loop.
3673 // Try to redistribute the undefined elements of non-root nodes so that
3674 // the non-root shuffles match something like a pack or merge, then adjust
3675 // the parent node's permute vector to compensate for the new order.
3676 // Among other things, this copes with vectors like <2 x i16> that were
3677 // padded with undefined elements during type legalization.
3679 // In the best case this redistribution will lead to the whole tree
3680 // using packs and merges. It should rarely be a loss in other cases.
3681 unsigned Stride = 1;
3682 for (; Stride * 2 < Ops.size(); Stride *= 2) {
3683 for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) {
3684 SDValue SubOps[] = { Ops[I], Ops[I + Stride] };
3686 // Create a mask for just these two operands.
3687 SmallVector<int, SystemZ::VectorBytes> NewBytes(SystemZ::VectorBytes);
3688 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
3689 unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes;
3690 unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes;
3693 else if (OpNo == I + Stride)
3694 NewBytes[J] = SystemZ::VectorBytes + Byte;
3698 // See if it would be better to reorganize NewMask to avoid using VPERM.
3699 SmallVector<int, SystemZ::VectorBytes> NewBytesMap(SystemZ::VectorBytes);
3700 if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) {
3701 Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]);
3702 // Applying NewBytesMap to Ops[I] gets back to NewBytes.
3703 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
3704 if (NewBytes[J] >= 0) {
3705 assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
3706 "Invalid double permute");
3707 Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J];
3709 assert(NewBytesMap[J] < 0 && "Invalid double permute");
3712 // Just use NewBytes on the operands.
3713 Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes);
3714 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J)
3715 if (NewBytes[J] >= 0)
3716 Bytes[J] = I * SystemZ::VectorBytes + J;
3721 // Now we just have 2 inputs. Put the second operand in Ops[1].
3723 Ops[1] = Ops[Stride];
3724 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
3725 if (Bytes[I] >= int(SystemZ::VectorBytes))
3726 Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes;
3729 // Look for an instruction that can do the permute without resorting
3731 unsigned OpNo0, OpNo1;
3733 if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1))
3734 Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]);
3736 Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes);
3737 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3740 // Return true if the given BUILD_VECTOR is a scalar-to-vector conversion.
3741 static bool isScalarToVector(SDValue Op) {
3742 for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I)
3743 if (Op.getOperand(I).getOpcode() != ISD::UNDEF)
3748 // Return a vector of type VT that contains Value in the first element.
3749 // The other elements don't matter.
3750 static SDValue buildScalarToVector(SelectionDAG &DAG, SDLoc DL, EVT VT,
3752 // If we have a constant, replicate it to all elements and let the
3753 // BUILD_VECTOR lowering take care of it.
3754 if (Value.getOpcode() == ISD::Constant ||
3755 Value.getOpcode() == ISD::ConstantFP) {
3756 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Value);
3757 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
3759 if (Value.getOpcode() == ISD::UNDEF)
3760 return DAG.getUNDEF(VT);
3761 return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
3764 // Return a vector of type VT in which Op0 is in element 0 and Op1 is in
3765 // element 1. Used for cases in which replication is cheap.
3766 static SDValue buildMergeScalars(SelectionDAG &DAG, SDLoc DL, EVT VT,
3767 SDValue Op0, SDValue Op1) {
3768 if (Op0.getOpcode() == ISD::UNDEF) {
3769 if (Op1.getOpcode() == ISD::UNDEF)
3770 return DAG.getUNDEF(VT);
3771 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1);
3773 if (Op1.getOpcode() == ISD::UNDEF)
3774 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0);
3775 return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT,
3776 buildScalarToVector(DAG, DL, VT, Op0),
3777 buildScalarToVector(DAG, DL, VT, Op1));
3780 // Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64
3782 static SDValue joinDwords(SelectionDAG &DAG, SDLoc DL, SDValue Op0,
3784 if (Op0.getOpcode() == ISD::UNDEF && Op1.getOpcode() == ISD::UNDEF)
3785 return DAG.getUNDEF(MVT::v2i64);
3786 // If one of the two inputs is undefined then replicate the other one,
3787 // in order to avoid using another register unnecessarily.
3788 if (Op0.getOpcode() == ISD::UNDEF)
3789 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
3790 else if (Op1.getOpcode() == ISD::UNDEF)
3791 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3793 Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3794 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
3796 return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1);
3799 // Try to represent constant BUILD_VECTOR node BVN using a
3800 // SystemZISD::BYTE_MASK-style mask. Store the mask value in Mask
3802 static bool tryBuildVectorByteMask(BuildVectorSDNode *BVN, uint64_t &Mask) {
3803 EVT ElemVT = BVN->getValueType(0).getVectorElementType();
3804 unsigned BytesPerElement = ElemVT.getStoreSize();
3805 for (unsigned I = 0, E = BVN->getNumOperands(); I != E; ++I) {
3806 SDValue Op = BVN->getOperand(I);
3807 if (Op.getOpcode() != ISD::UNDEF) {
3809 if (Op.getOpcode() == ISD::Constant)
3810 Value = dyn_cast<ConstantSDNode>(Op)->getZExtValue();
3811 else if (Op.getOpcode() == ISD::ConstantFP)
3812 Value = (dyn_cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt()
3816 for (unsigned J = 0; J < BytesPerElement; ++J) {
3817 uint64_t Byte = (Value >> (J * 8)) & 0xff;
3819 Mask |= 1ULL << ((E - I - 1) * BytesPerElement + J);
3828 // Try to load a vector constant in which BitsPerElement-bit value Value
3829 // is replicated to fill the vector. VT is the type of the resulting
3830 // constant, which may have elements of a different size from BitsPerElement.
3831 // Return the SDValue of the constant on success, otherwise return
3833 static SDValue tryBuildVectorReplicate(SelectionDAG &DAG,
3834 const SystemZInstrInfo *TII,
3835 SDLoc DL, EVT VT, uint64_t Value,
3836 unsigned BitsPerElement) {
3837 // Signed 16-bit values can be replicated using VREPI.
3838 int64_t SignedValue = SignExtend64(Value, BitsPerElement);
3839 if (isInt<16>(SignedValue)) {
3840 MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement),
3841 SystemZ::VectorBits / BitsPerElement);
3842 SDValue Op = DAG.getNode(SystemZISD::REPLICATE, DL, VecVT,
3843 DAG.getConstant(SignedValue, DL, MVT::i32));
3844 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3846 // See whether rotating the constant left some N places gives a value that
3847 // is one less than a power of 2 (i.e. all zeros followed by all ones).
3848 // If so we can use VGM.
3849 unsigned Start, End;
3850 if (TII->isRxSBGMask(Value, BitsPerElement, Start, End)) {
3851 // isRxSBGMask returns the bit numbers for a full 64-bit value,
3852 // with 0 denoting 1 << 63 and 63 denoting 1. Convert them to
3853 // bit numbers for an BitsPerElement value, so that 0 denotes
3854 // 1 << (BitsPerElement-1).
3855 Start -= 64 - BitsPerElement;
3856 End -= 64 - BitsPerElement;
3857 MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement),
3858 SystemZ::VectorBits / BitsPerElement);
3859 SDValue Op = DAG.getNode(SystemZISD::ROTATE_MASK, DL, VecVT,
3860 DAG.getConstant(Start, DL, MVT::i32),
3861 DAG.getConstant(End, DL, MVT::i32));
3862 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3867 // If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually
3868 // better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for
3869 // the non-EXTRACT_VECTOR_ELT elements. See if the given BUILD_VECTOR
3870 // would benefit from this representation and return it if so.
3871 static SDValue tryBuildVectorShuffle(SelectionDAG &DAG,
3872 BuildVectorSDNode *BVN) {
3873 EVT VT = BVN->getValueType(0);
3874 unsigned NumElements = VT.getVectorNumElements();
3876 // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation
3877 // on byte vectors. If there are non-EXTRACT_VECTOR_ELT elements that still
3878 // need a BUILD_VECTOR, add an additional placeholder operand for that
3879 // BUILD_VECTOR and store its operands in ResidueOps.
3880 GeneralShuffle GS(VT);
3881 SmallVector<SDValue, SystemZ::VectorBytes> ResidueOps;
3882 bool FoundOne = false;
3883 for (unsigned I = 0; I < NumElements; ++I) {
3884 SDValue Op = BVN->getOperand(I);
3885 if (Op.getOpcode() == ISD::TRUNCATE)
3886 Op = Op.getOperand(0);
3887 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3888 Op.getOperand(1).getOpcode() == ISD::Constant) {
3889 unsigned Elem = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
3890 GS.add(Op.getOperand(0), Elem);
3892 } else if (Op.getOpcode() == ISD::UNDEF) {
3895 GS.add(SDValue(), ResidueOps.size());
3896 ResidueOps.push_back(BVN->getOperand(I));
3900 // Nothing to do if there are no EXTRACT_VECTOR_ELTs.
3904 // Create the BUILD_VECTOR for the remaining elements, if any.
3905 if (!ResidueOps.empty()) {
3906 while (ResidueOps.size() < NumElements)
3907 ResidueOps.push_back(DAG.getUNDEF(ResidueOps[0].getValueType()));
3908 for (auto &Op : GS.Ops) {
3909 if (!Op.getNode()) {
3910 Op = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BVN), VT, ResidueOps);
3915 return GS.getNode(DAG, SDLoc(BVN));
3918 // Combine GPR scalar values Elems into a vector of type VT.
3919 static SDValue buildVector(SelectionDAG &DAG, SDLoc DL, EVT VT,
3920 SmallVectorImpl<SDValue> &Elems) {
3921 // See whether there is a single replicated value.
3923 unsigned int NumElements = Elems.size();
3924 unsigned int Count = 0;
3925 for (auto Elem : Elems) {
3926 if (Elem.getOpcode() != ISD::UNDEF) {
3927 if (!Single.getNode())
3929 else if (Elem != Single) {
3936 // There are three cases here:
3938 // - if the only defined element is a loaded one, the best sequence
3939 // is a replicating load.
3941 // - otherwise, if the only defined element is an i64 value, we will
3942 // end up with the same VLVGP sequence regardless of whether we short-cut
3943 // for replication or fall through to the later code.
3945 // - otherwise, if the only defined element is an i32 or smaller value,
3946 // we would need 2 instructions to replicate it: VLVGP followed by VREPx.
3947 // This is only a win if the single defined element is used more than once.
3948 // In other cases we're better off using a single VLVGx.
3949 if (Single.getNode() && (Count > 1 || Single.getOpcode() == ISD::LOAD))
3950 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single);
3952 // The best way of building a v2i64 from two i64s is to use VLVGP.
3953 if (VT == MVT::v2i64)
3954 return joinDwords(DAG, DL, Elems[0], Elems[1]);
3956 // Use a 64-bit merge high to combine two doubles.
3957 if (VT == MVT::v2f64)
3958 return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
3960 // Build v4f32 values directly from the FPRs:
3962 // <Axxx> <Bxxx> <Cxxxx> <Dxxx>
3967 if (VT == MVT::v4f32) {
3968 SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
3969 SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[2], Elems[3]);
3970 // Avoid unnecessary undefs by reusing the other operand.
3971 if (Op01.getOpcode() == ISD::UNDEF)
3973 else if (Op23.getOpcode() == ISD::UNDEF)
3975 // Merging identical replications is a no-op.
3976 if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23)
3978 Op01 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op01);
3979 Op23 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op23);
3980 SDValue Op = DAG.getNode(SystemZISD::MERGE_HIGH,
3981 DL, MVT::v2i64, Op01, Op23);
3982 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3985 // Collect the constant terms.
3986 SmallVector<SDValue, SystemZ::VectorBytes> Constants(NumElements, SDValue());
3987 SmallVector<bool, SystemZ::VectorBytes> Done(NumElements, false);
3989 unsigned NumConstants = 0;
3990 for (unsigned I = 0; I < NumElements; ++I) {
3991 SDValue Elem = Elems[I];
3992 if (Elem.getOpcode() == ISD::Constant ||
3993 Elem.getOpcode() == ISD::ConstantFP) {
3995 Constants[I] = Elem;
3999 // If there was at least one constant, fill in the other elements of
4000 // Constants with undefs to get a full vector constant and use that
4001 // as the starting point.
4003 if (NumConstants > 0) {
4004 for (unsigned I = 0; I < NumElements; ++I)
4005 if (!Constants[I].getNode())
4006 Constants[I] = DAG.getUNDEF(Elems[I].getValueType());
4007 Result = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Constants);
4009 // Otherwise try to use VLVGP to start the sequence in order to
4010 // avoid a false dependency on any previous contents of the vector
4011 // register. This only makes sense if one of the associated elements
4013 unsigned I1 = NumElements / 2 - 1;
4014 unsigned I2 = NumElements - 1;
4015 bool Def1 = (Elems[I1].getOpcode() != ISD::UNDEF);
4016 bool Def2 = (Elems[I2].getOpcode() != ISD::UNDEF);
4018 SDValue Elem1 = Elems[Def1 ? I1 : I2];
4019 SDValue Elem2 = Elems[Def2 ? I2 : I1];
4020 Result = DAG.getNode(ISD::BITCAST, DL, VT,
4021 joinDwords(DAG, DL, Elem1, Elem2));
4025 Result = DAG.getUNDEF(VT);
4028 // Use VLVGx to insert the other elements.
4029 for (unsigned I = 0; I < NumElements; ++I)
4030 if (!Done[I] && Elems[I].getOpcode() != ISD::UNDEF)
4031 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I],
4032 DAG.getConstant(I, DL, MVT::i32));
4036 SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op,
4037 SelectionDAG &DAG) const {
4038 const SystemZInstrInfo *TII =
4039 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4040 auto *BVN = cast<BuildVectorSDNode>(Op.getNode());
4042 EVT VT = Op.getValueType();
4044 if (BVN->isConstant()) {
4045 // Try using VECTOR GENERATE BYTE MASK. This is the architecturally-
4046 // preferred way of creating all-zero and all-one vectors so give it
4047 // priority over other methods below.
4049 if (tryBuildVectorByteMask(BVN, Mask)) {
4050 SDValue Op = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
4051 DAG.getConstant(Mask, DL, MVT::i32));
4052 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4055 // Try using some form of replication.
4056 APInt SplatBits, SplatUndef;
4057 unsigned SplatBitSize;
4059 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
4061 SplatBitSize <= 64) {
4062 // First try assuming that any undefined bits above the highest set bit
4063 // and below the lowest set bit are 1s. This increases the likelihood of
4064 // being able to use a sign-extended element value in VECTOR REPLICATE
4065 // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
4066 uint64_t SplatBitsZ = SplatBits.getZExtValue();
4067 uint64_t SplatUndefZ = SplatUndef.getZExtValue();
4068 uint64_t Lower = (SplatUndefZ
4069 & ((uint64_t(1) << findFirstSet(SplatBitsZ)) - 1));
4070 uint64_t Upper = (SplatUndefZ
4071 & ~((uint64_t(1) << findLastSet(SplatBitsZ)) - 1));
4072 uint64_t Value = SplatBitsZ | Upper | Lower;
4073 SDValue Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value,
4078 // Now try assuming that any undefined bits between the first and
4079 // last defined set bits are set. This increases the chances of
4080 // using a non-wraparound mask.
4081 uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
4082 Value = SplatBitsZ | Middle;
4083 Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value, SplatBitSize);
4088 // Fall back to loading it from memory.
4092 // See if we should use shuffles to construct the vector from other vectors.
4093 SDValue Res = tryBuildVectorShuffle(DAG, BVN);
4097 // Detect SCALAR_TO_VECTOR conversions.
4098 if (isOperationLegal(ISD::SCALAR_TO_VECTOR, VT) && isScalarToVector(Op))
4099 return buildScalarToVector(DAG, DL, VT, Op.getOperand(0));
4101 // Otherwise use buildVector to build the vector up from GPRs.
4102 unsigned NumElements = Op.getNumOperands();
4103 SmallVector<SDValue, SystemZ::VectorBytes> Ops(NumElements);
4104 for (unsigned I = 0; I < NumElements; ++I)
4105 Ops[I] = Op.getOperand(I);
4106 return buildVector(DAG, DL, VT, Ops);
4109 SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
4110 SelectionDAG &DAG) const {
4111 auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode());
4113 EVT VT = Op.getValueType();
4114 unsigned NumElements = VT.getVectorNumElements();
4116 if (VSN->isSplat()) {
4117 SDValue Op0 = Op.getOperand(0);
4118 unsigned Index = VSN->getSplatIndex();
4119 assert(Index < VT.getVectorNumElements() &&
4120 "Splat index should be defined and in first operand");
4121 // See whether the value we're splatting is directly available as a scalar.
4122 if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
4123 Op0.getOpcode() == ISD::BUILD_VECTOR)
4124 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index));
4125 // Otherwise keep it as a vector-to-vector operation.
4126 return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0),
4127 DAG.getConstant(Index, DL, MVT::i32));
4130 GeneralShuffle GS(VT);
4131 for (unsigned I = 0; I < NumElements; ++I) {
4132 int Elt = VSN->getMaskElt(I);
4136 GS.add(Op.getOperand(unsigned(Elt) / NumElements),
4137 unsigned(Elt) % NumElements);
4139 return GS.getNode(DAG, SDLoc(VSN));
4142 SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
4143 SelectionDAG &DAG) const {
4145 // Just insert the scalar into element 0 of an undefined vector.
4146 return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL,
4147 Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
4148 Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32));
4151 SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4152 SelectionDAG &DAG) const {
4153 // Handle insertions of floating-point values.
4155 SDValue Op0 = Op.getOperand(0);
4156 SDValue Op1 = Op.getOperand(1);
4157 SDValue Op2 = Op.getOperand(2);
4158 EVT VT = Op.getValueType();
4160 // Insertions into constant indices of a v2f64 can be done using VPDI.
4161 // However, if the inserted value is a bitcast or a constant then it's
4162 // better to use GPRs, as below.
4163 if (VT == MVT::v2f64 &&
4164 Op1.getOpcode() != ISD::BITCAST &&
4165 Op1.getOpcode() != ISD::ConstantFP &&
4166 Op2.getOpcode() == ISD::Constant) {
4167 uint64_t Index = dyn_cast<ConstantSDNode>(Op2)->getZExtValue();
4168 unsigned Mask = VT.getVectorNumElements() - 1;
4173 // Otherwise bitcast to the equivalent integer form and insert via a GPR.
4174 MVT IntVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
4175 MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements());
4176 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT,
4177 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0),
4178 DAG.getNode(ISD::BITCAST, DL, IntVT, Op1), Op2);
4179 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
4183 SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4184 SelectionDAG &DAG) const {
4185 // Handle extractions of floating-point values.
4187 SDValue Op0 = Op.getOperand(0);
4188 SDValue Op1 = Op.getOperand(1);
4189 EVT VT = Op.getValueType();
4190 EVT VecVT = Op0.getValueType();
4192 // Extractions of constant indices can be done directly.
4193 if (auto *CIndexN = dyn_cast<ConstantSDNode>(Op1)) {
4194 uint64_t Index = CIndexN->getZExtValue();
4195 unsigned Mask = VecVT.getVectorNumElements() - 1;
4200 // Otherwise bitcast to the equivalent integer form and extract via a GPR.
4201 MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
4202 MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements());
4203 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntVT,
4204 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1);
4205 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
4209 SystemZTargetLowering::lowerExtendVectorInreg(SDValue Op, SelectionDAG &DAG,
4210 unsigned UnpackHigh) const {
4211 SDValue PackedOp = Op.getOperand(0);
4212 EVT OutVT = Op.getValueType();
4213 EVT InVT = PackedOp.getValueType();
4214 unsigned ToBits = OutVT.getVectorElementType().getSizeInBits();
4215 unsigned FromBits = InVT.getVectorElementType().getSizeInBits();
4218 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(FromBits),
4219 SystemZ::VectorBits / FromBits);
4220 PackedOp = DAG.getNode(UnpackHigh, SDLoc(PackedOp), OutVT, PackedOp);
4221 } while (FromBits != ToBits);
4225 SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG,
4226 unsigned ByScalar) const {
4227 // Look for cases where a vector shift can use the *_BY_SCALAR form.
4228 SDValue Op0 = Op.getOperand(0);
4229 SDValue Op1 = Op.getOperand(1);
4231 EVT VT = Op.getValueType();
4232 unsigned ElemBitSize = VT.getVectorElementType().getSizeInBits();
4234 // See whether the shift vector is a splat represented as BUILD_VECTOR.
4235 if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) {
4236 APInt SplatBits, SplatUndef;
4237 unsigned SplatBitSize;
4239 // Check for constant splats. Use ElemBitSize as the minimum element
4240 // width and reject splats that need wider elements.
4241 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
4242 ElemBitSize, true) &&
4243 SplatBitSize == ElemBitSize) {
4244 SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff,
4246 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4248 // Check for variable splats.
4249 BitVector UndefElements;
4250 SDValue Splat = BVN->getSplatValue(&UndefElements);
4252 // Since i32 is the smallest legal type, we either need a no-op
4254 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat);
4255 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4259 // See whether the shift vector is a splat represented as SHUFFLE_VECTOR,
4260 // and the shift amount is directly available in a GPR.
4261 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) {
4262 if (VSN->isSplat()) {
4263 SDValue VSNOp0 = VSN->getOperand(0);
4264 unsigned Index = VSN->getSplatIndex();
4265 assert(Index < VT.getVectorNumElements() &&
4266 "Splat index should be defined and in first operand");
4267 if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
4268 VSNOp0.getOpcode() == ISD::BUILD_VECTOR) {
4269 // Since i32 is the smallest legal type, we either need a no-op
4271 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
4272 VSNOp0.getOperand(Index));
4273 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4278 // Otherwise just treat the current form as legal.
4282 SDValue SystemZTargetLowering::LowerOperation(SDValue Op,
4283 SelectionDAG &DAG) const {
4284 switch (Op.getOpcode()) {
4286 return lowerBR_CC(Op, DAG);
4287 case ISD::SELECT_CC:
4288 return lowerSELECT_CC(Op, DAG);
4290 return lowerSETCC(Op, DAG);
4291 case ISD::GlobalAddress:
4292 return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
4293 case ISD::GlobalTLSAddress:
4294 return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
4295 case ISD::BlockAddress:
4296 return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
4297 case ISD::JumpTable:
4298 return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
4299 case ISD::ConstantPool:
4300 return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
4302 return lowerBITCAST(Op, DAG);
4304 return lowerVASTART(Op, DAG);
4306 return lowerVACOPY(Op, DAG);
4307 case ISD::DYNAMIC_STACKALLOC:
4308 return lowerDYNAMIC_STACKALLOC(Op, DAG);
4309 case ISD::SMUL_LOHI:
4310 return lowerSMUL_LOHI(Op, DAG);
4311 case ISD::UMUL_LOHI:
4312 return lowerUMUL_LOHI(Op, DAG);
4314 return lowerSDIVREM(Op, DAG);
4316 return lowerUDIVREM(Op, DAG);
4318 return lowerOR(Op, DAG);
4320 return lowerCTPOP(Op, DAG);
4321 case ISD::CTLZ_ZERO_UNDEF:
4322 return DAG.getNode(ISD::CTLZ, SDLoc(Op),
4323 Op.getValueType(), Op.getOperand(0));
4324 case ISD::CTTZ_ZERO_UNDEF:
4325 return DAG.getNode(ISD::CTTZ, SDLoc(Op),
4326 Op.getValueType(), Op.getOperand(0));
4327 case ISD::ATOMIC_SWAP:
4328 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_SWAPW);
4329 case ISD::ATOMIC_STORE:
4330 return lowerATOMIC_STORE(Op, DAG);
4331 case ISD::ATOMIC_LOAD:
4332 return lowerATOMIC_LOAD(Op, DAG);
4333 case ISD::ATOMIC_LOAD_ADD:
4334 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
4335 case ISD::ATOMIC_LOAD_SUB:
4336 return lowerATOMIC_LOAD_SUB(Op, DAG);
4337 case ISD::ATOMIC_LOAD_AND:
4338 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
4339 case ISD::ATOMIC_LOAD_OR:
4340 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
4341 case ISD::ATOMIC_LOAD_XOR:
4342 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
4343 case ISD::ATOMIC_LOAD_NAND:
4344 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
4345 case ISD::ATOMIC_LOAD_MIN:
4346 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
4347 case ISD::ATOMIC_LOAD_MAX:
4348 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
4349 case ISD::ATOMIC_LOAD_UMIN:
4350 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
4351 case ISD::ATOMIC_LOAD_UMAX:
4352 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
4353 case ISD::ATOMIC_CMP_SWAP:
4354 return lowerATOMIC_CMP_SWAP(Op, DAG);
4355 case ISD::STACKSAVE:
4356 return lowerSTACKSAVE(Op, DAG);
4357 case ISD::STACKRESTORE:
4358 return lowerSTACKRESTORE(Op, DAG);
4360 return lowerPREFETCH(Op, DAG);
4361 case ISD::INTRINSIC_W_CHAIN:
4362 return lowerINTRINSIC_W_CHAIN(Op, DAG);
4363 case ISD::INTRINSIC_WO_CHAIN:
4364 return lowerINTRINSIC_WO_CHAIN(Op, DAG);
4365 case ISD::BUILD_VECTOR:
4366 return lowerBUILD_VECTOR(Op, DAG);
4367 case ISD::VECTOR_SHUFFLE:
4368 return lowerVECTOR_SHUFFLE(Op, DAG);
4369 case ISD::SCALAR_TO_VECTOR:
4370 return lowerSCALAR_TO_VECTOR(Op, DAG);
4371 case ISD::INSERT_VECTOR_ELT:
4372 return lowerINSERT_VECTOR_ELT(Op, DAG);
4373 case ISD::EXTRACT_VECTOR_ELT:
4374 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4375 case ISD::SIGN_EXTEND_VECTOR_INREG:
4376 return lowerExtendVectorInreg(Op, DAG, SystemZISD::UNPACK_HIGH);
4377 case ISD::ZERO_EXTEND_VECTOR_INREG:
4378 return lowerExtendVectorInreg(Op, DAG, SystemZISD::UNPACKL_HIGH);
4380 return lowerShift(Op, DAG, SystemZISD::VSHL_BY_SCALAR);
4382 return lowerShift(Op, DAG, SystemZISD::VSRL_BY_SCALAR);
4384 return lowerShift(Op, DAG, SystemZISD::VSRA_BY_SCALAR);
4386 llvm_unreachable("Unexpected node to lower");
4390 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
4391 #define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME
4392 switch ((SystemZISD::NodeType)Opcode) {
4393 case SystemZISD::FIRST_NUMBER: break;
4399 OPCODE(PCREL_WRAPPER);
4400 OPCODE(PCREL_OFFSET);
4406 OPCODE(SELECT_CCMASK);
4407 OPCODE(ADJDYNALLOC);
4408 OPCODE(EXTRACT_ACCESS);
4410 OPCODE(UMUL_LOHI64);
4427 OPCODE(SEARCH_STRING);
4431 OPCODE(TBEGIN_NOFLOAT);
4434 OPCODE(ROTATE_MASK);
4436 OPCODE(JOIN_DWORDS);
4441 OPCODE(PERMUTE_DWORDS);
4446 OPCODE(UNPACK_HIGH);
4447 OPCODE(UNPACKL_HIGH);
4449 OPCODE(UNPACKL_LOW);
4450 OPCODE(VSHL_BY_SCALAR);
4451 OPCODE(VSRL_BY_SCALAR);
4452 OPCODE(VSRA_BY_SCALAR);
4479 OPCODE(ATOMIC_SWAPW);
4480 OPCODE(ATOMIC_LOADW_ADD);
4481 OPCODE(ATOMIC_LOADW_SUB);
4482 OPCODE(ATOMIC_LOADW_AND);
4483 OPCODE(ATOMIC_LOADW_OR);
4484 OPCODE(ATOMIC_LOADW_XOR);
4485 OPCODE(ATOMIC_LOADW_NAND);
4486 OPCODE(ATOMIC_LOADW_MIN);
4487 OPCODE(ATOMIC_LOADW_MAX);
4488 OPCODE(ATOMIC_LOADW_UMIN);
4489 OPCODE(ATOMIC_LOADW_UMAX);
4490 OPCODE(ATOMIC_CMP_SWAPW);
4497 // Return true if VT is a vector whose elements are a whole number of bytes
4499 static bool canTreatAsByteVector(EVT VT) {
4500 return VT.isVector() && VT.getVectorElementType().getSizeInBits() % 8 == 0;
4503 // Try to simplify an EXTRACT_VECTOR_ELT from a vector of type VecVT
4504 // producing a result of type ResVT. Op is a possibly bitcast version
4505 // of the input vector and Index is the index (based on type VecVT) that
4506 // should be extracted. Return the new extraction if a simplification
4507 // was possible or if Force is true.
4508 SDValue SystemZTargetLowering::combineExtract(SDLoc DL, EVT ResVT, EVT VecVT,
4509 SDValue Op, unsigned Index,
4510 DAGCombinerInfo &DCI,
4512 SelectionDAG &DAG = DCI.DAG;
4514 // The number of bytes being extracted.
4515 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
4518 unsigned Opcode = Op.getOpcode();
4519 if (Opcode == ISD::BITCAST)
4520 // Look through bitcasts.
4521 Op = Op.getOperand(0);
4522 else if (Opcode == ISD::VECTOR_SHUFFLE &&
4523 canTreatAsByteVector(Op.getValueType())) {
4524 // Get a VPERM-like permute mask and see whether the bytes covered
4525 // by the extracted element are a contiguous sequence from one
4527 SmallVector<int, SystemZ::VectorBytes> Bytes;
4528 getVPermMask(cast<ShuffleVectorSDNode>(Op), Bytes);
4530 if (!getShuffleInput(Bytes, Index * BytesPerElement,
4531 BytesPerElement, First))
4534 return DAG.getUNDEF(ResVT);
4535 // Make sure the contiguous sequence starts at a multiple of the
4536 // original element size.
4537 unsigned Byte = unsigned(First) % Bytes.size();
4538 if (Byte % BytesPerElement != 0)
4540 // We can get the extracted value directly from an input.
4541 Index = Byte / BytesPerElement;
4542 Op = Op.getOperand(unsigned(First) / Bytes.size());
4544 } else if (Opcode == ISD::BUILD_VECTOR &&
4545 canTreatAsByteVector(Op.getValueType())) {
4546 // We can only optimize this case if the BUILD_VECTOR elements are
4547 // at least as wide as the extracted value.
4548 EVT OpVT = Op.getValueType();
4549 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
4550 if (OpBytesPerElement < BytesPerElement)
4552 // Make sure that the least-significant bit of the extracted value
4553 // is the least significant bit of an input.
4554 unsigned End = (Index + 1) * BytesPerElement;
4555 if (End % OpBytesPerElement != 0)
4557 // We're extracting the low part of one operand of the BUILD_VECTOR.
4558 Op = Op.getOperand(End / OpBytesPerElement - 1);
4559 if (!Op.getValueType().isInteger()) {
4560 EVT VT = MVT::getIntegerVT(Op.getValueType().getSizeInBits());
4561 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
4562 DCI.AddToWorklist(Op.getNode());
4564 EVT VT = MVT::getIntegerVT(ResVT.getSizeInBits());
4565 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
4567 DCI.AddToWorklist(Op.getNode());
4568 Op = DAG.getNode(ISD::BITCAST, DL, ResVT, Op);
4571 } else if ((Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
4572 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
4573 Opcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
4574 canTreatAsByteVector(Op.getValueType()) &&
4575 canTreatAsByteVector(Op.getOperand(0).getValueType())) {
4576 // Make sure that only the unextended bits are significant.
4577 EVT ExtVT = Op.getValueType();
4578 EVT OpVT = Op.getOperand(0).getValueType();
4579 unsigned ExtBytesPerElement = ExtVT.getVectorElementType().getStoreSize();
4580 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
4581 unsigned Byte = Index * BytesPerElement;
4582 unsigned SubByte = Byte % ExtBytesPerElement;
4583 unsigned MinSubByte = ExtBytesPerElement - OpBytesPerElement;
4584 if (SubByte < MinSubByte ||
4585 SubByte + BytesPerElement > ExtBytesPerElement)
4587 // Get the byte offset of the unextended element
4588 Byte = Byte / ExtBytesPerElement * OpBytesPerElement;
4589 // ...then add the byte offset relative to that element.
4590 Byte += SubByte - MinSubByte;
4591 if (Byte % BytesPerElement != 0)
4593 Op = Op.getOperand(0);
4594 Index = Byte / BytesPerElement;
4600 if (Op.getValueType() != VecVT) {
4601 Op = DAG.getNode(ISD::BITCAST, DL, VecVT, Op);
4602 DCI.AddToWorklist(Op.getNode());
4604 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Op,
4605 DAG.getConstant(Index, DL, MVT::i32));
4610 // Optimize vector operations in scalar value Op on the basis that Op
4611 // is truncated to TruncVT.
4613 SystemZTargetLowering::combineTruncateExtract(SDLoc DL, EVT TruncVT, SDValue Op,
4614 DAGCombinerInfo &DCI) const {
4615 // If we have (trunc (extract_vector_elt X, Y)), try to turn it into
4616 // (extract_vector_elt (bitcast X), Y'), where (bitcast X) has elements
4618 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4619 TruncVT.getSizeInBits() % 8 == 0) {
4620 SDValue Vec = Op.getOperand(0);
4621 EVT VecVT = Vec.getValueType();
4622 if (canTreatAsByteVector(VecVT)) {
4623 if (auto *IndexN = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
4624 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
4625 unsigned TruncBytes = TruncVT.getStoreSize();
4626 if (BytesPerElement % TruncBytes == 0) {
4627 // Calculate the value of Y' in the above description. We are
4628 // splitting the original elements into Scale equal-sized pieces
4629 // and for truncation purposes want the last (least-significant)
4630 // of these pieces for IndexN. This is easiest to do by calculating
4631 // the start index of the following element and then subtracting 1.
4632 unsigned Scale = BytesPerElement / TruncBytes;
4633 unsigned NewIndex = (IndexN->getZExtValue() + 1) * Scale - 1;
4635 // Defer the creation of the bitcast from X to combineExtract,
4636 // which might be able to optimize the extraction.
4637 VecVT = MVT::getVectorVT(MVT::getIntegerVT(TruncBytes * 8),
4638 VecVT.getStoreSize() / TruncBytes);
4639 EVT ResVT = (TruncBytes < 4 ? MVT::i32 : TruncVT);
4640 return combineExtract(DL, ResVT, VecVT, Vec, NewIndex, DCI, true);
4648 SDValue SystemZTargetLowering::PerformDAGCombine(SDNode *N,
4649 DAGCombinerInfo &DCI) const {
4650 SelectionDAG &DAG = DCI.DAG;
4651 unsigned Opcode = N->getOpcode();
4652 if (Opcode == ISD::SIGN_EXTEND) {
4653 // Convert (sext (ashr (shl X, C1), C2)) to
4654 // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
4655 // cheap as narrower ones.
4656 SDValue N0 = N->getOperand(0);
4657 EVT VT = N->getValueType(0);
4658 if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
4659 auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4660 SDValue Inner = N0.getOperand(0);
4661 if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
4662 if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
4663 unsigned Extra = (VT.getSizeInBits() -
4664 N0.getValueType().getSizeInBits());
4665 unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
4666 unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
4667 EVT ShiftVT = N0.getOperand(1).getValueType();
4668 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
4669 Inner.getOperand(0));
4670 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
4671 DAG.getConstant(NewShlAmt, SDLoc(Inner),
4673 return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
4674 DAG.getConstant(NewSraAmt, SDLoc(N0), ShiftVT));
4679 if (Opcode == SystemZISD::MERGE_HIGH ||
4680 Opcode == SystemZISD::MERGE_LOW) {
4681 SDValue Op0 = N->getOperand(0);
4682 SDValue Op1 = N->getOperand(1);
4683 if (Op0.getOpcode() == ISD::BITCAST)
4684 Op0 = Op0.getOperand(0);
4685 if (Op0.getOpcode() == SystemZISD::BYTE_MASK &&
4686 cast<ConstantSDNode>(Op0.getOperand(0))->getZExtValue() == 0) {
4687 // (z_merge_* 0, 0) -> 0. This is mostly useful for using VLLEZF
4689 if (Op1 == N->getOperand(0))
4691 // (z_merge_? 0, X) -> (z_unpackl_? 0, X).
4692 EVT VT = Op1.getValueType();
4693 unsigned ElemBytes = VT.getVectorElementType().getStoreSize();
4694 if (ElemBytes <= 4) {
4695 Opcode = (Opcode == SystemZISD::MERGE_HIGH ?
4696 SystemZISD::UNPACKL_HIGH : SystemZISD::UNPACKL_LOW);
4697 EVT InVT = VT.changeVectorElementTypeToInteger();
4698 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(ElemBytes * 16),
4699 SystemZ::VectorBytes / ElemBytes / 2);
4701 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), InVT, Op1);
4702 DCI.AddToWorklist(Op1.getNode());
4704 SDValue Op = DAG.getNode(Opcode, SDLoc(N), OutVT, Op1);
4705 DCI.AddToWorklist(Op.getNode());
4706 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
4710 // If we have (truncstoreiN (extract_vector_elt X, Y), Z) then it is better
4711 // for the extraction to be done on a vMiN value, so that we can use VSTE.
4712 // If X has wider elements then convert it to:
4713 // (truncstoreiN (extract_vector_elt (bitcast X), Y2), Z).
4714 if (Opcode == ISD::STORE) {
4715 auto *SN = cast<StoreSDNode>(N);
4716 EVT MemVT = SN->getMemoryVT();
4717 if (MemVT.isInteger()) {
4718 SDValue Value = combineTruncateExtract(SDLoc(N), MemVT,
4719 SN->getValue(), DCI);
4720 if (Value.getNode()) {
4721 DCI.AddToWorklist(Value.getNode());
4723 // Rewrite the store with the new form of stored value.
4724 return DAG.getTruncStore(SN->getChain(), SDLoc(SN), Value,
4725 SN->getBasePtr(), SN->getMemoryVT(),
4726 SN->getMemOperand());
4730 // Try to simplify a vector extraction.
4731 if (Opcode == ISD::EXTRACT_VECTOR_ELT) {
4732 if (auto *IndexN = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
4733 SDValue Op0 = N->getOperand(0);
4734 EVT VecVT = Op0.getValueType();
4735 return combineExtract(SDLoc(N), N->getValueType(0), VecVT, Op0,
4736 IndexN->getZExtValue(), DCI, false);
4739 // (join_dwords X, X) == (replicate X)
4740 if (Opcode == SystemZISD::JOIN_DWORDS &&
4741 N->getOperand(0) == N->getOperand(1))
4742 return DAG.getNode(SystemZISD::REPLICATE, SDLoc(N), N->getValueType(0),
4744 // (fround (extract_vector_elt X 0))
4745 // (fround (extract_vector_elt X 1)) ->
4746 // (extract_vector_elt (VROUND X) 0)
4747 // (extract_vector_elt (VROUND X) 1)
4749 // This is a special case since the target doesn't really support v2f32s.
4750 if (Opcode == ISD::FP_ROUND) {
4751 SDValue Op0 = N->getOperand(0);
4752 if (N->getValueType(0) == MVT::f32 &&
4754 Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4755 Op0.getOperand(0).getValueType() == MVT::v2f64 &&
4756 Op0.getOperand(1).getOpcode() == ISD::Constant &&
4757 cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue() == 0) {
4758 SDValue Vec = Op0.getOperand(0);
4759 for (auto *U : Vec->uses()) {
4760 if (U != Op0.getNode() &&
4762 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4763 U->getOperand(0) == Vec &&
4764 U->getOperand(1).getOpcode() == ISD::Constant &&
4765 cast<ConstantSDNode>(U->getOperand(1))->getZExtValue() == 1) {
4766 SDValue OtherRound = SDValue(*U->use_begin(), 0);
4767 if (OtherRound.getOpcode() == ISD::FP_ROUND &&
4768 OtherRound.getOperand(0) == SDValue(U, 0) &&
4769 OtherRound.getValueType() == MVT::f32) {
4770 SDValue VRound = DAG.getNode(SystemZISD::VROUND, SDLoc(N),
4772 DCI.AddToWorklist(VRound.getNode());
4774 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f32,
4775 VRound, DAG.getConstant(2, SDLoc(U), MVT::i32));
4776 DCI.AddToWorklist(Extract1.getNode());
4777 DAG.ReplaceAllUsesOfValueWith(OtherRound, Extract1);
4779 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f32,
4780 VRound, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
4790 //===----------------------------------------------------------------------===//
4792 //===----------------------------------------------------------------------===//
4794 // Create a new basic block after MBB.
4795 static MachineBasicBlock *emitBlockAfter(MachineBasicBlock *MBB) {
4796 MachineFunction &MF = *MBB->getParent();
4797 MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(MBB->getBasicBlock());
4798 MF.insert(std::next(MachineFunction::iterator(MBB)), NewMBB);
4802 // Split MBB after MI and return the new block (the one that contains
4803 // instructions after MI).
4804 static MachineBasicBlock *splitBlockAfter(MachineInstr *MI,
4805 MachineBasicBlock *MBB) {
4806 MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
4807 NewMBB->splice(NewMBB->begin(), MBB,
4808 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
4809 NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
4813 // Split MBB before MI and return the new block (the one that contains MI).
4814 static MachineBasicBlock *splitBlockBefore(MachineInstr *MI,
4815 MachineBasicBlock *MBB) {
4816 MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
4817 NewMBB->splice(NewMBB->begin(), MBB, MI, MBB->end());
4818 NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
4822 // Force base value Base into a register before MI. Return the register.
4823 static unsigned forceReg(MachineInstr *MI, MachineOperand &Base,
4824 const SystemZInstrInfo *TII) {
4826 return Base.getReg();
4828 MachineBasicBlock *MBB = MI->getParent();
4829 MachineFunction &MF = *MBB->getParent();
4830 MachineRegisterInfo &MRI = MF.getRegInfo();
4832 unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
4833 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LA), Reg)
4834 .addOperand(Base).addImm(0).addReg(0);
4838 // Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
4840 SystemZTargetLowering::emitSelect(MachineInstr *MI,
4841 MachineBasicBlock *MBB) const {
4842 const SystemZInstrInfo *TII =
4843 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4845 unsigned DestReg = MI->getOperand(0).getReg();
4846 unsigned TrueReg = MI->getOperand(1).getReg();
4847 unsigned FalseReg = MI->getOperand(2).getReg();
4848 unsigned CCValid = MI->getOperand(3).getImm();
4849 unsigned CCMask = MI->getOperand(4).getImm();
4850 DebugLoc DL = MI->getDebugLoc();
4852 MachineBasicBlock *StartMBB = MBB;
4853 MachineBasicBlock *JoinMBB = splitBlockBefore(MI, MBB);
4854 MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
4857 // BRC CCMask, JoinMBB
4858 // # fallthrough to FalseMBB
4860 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
4861 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
4862 MBB->addSuccessor(JoinMBB);
4863 MBB->addSuccessor(FalseMBB);
4866 // # fallthrough to JoinMBB
4868 MBB->addSuccessor(JoinMBB);
4871 // %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
4874 BuildMI(*MBB, MI, DL, TII->get(SystemZ::PHI), DestReg)
4875 .addReg(TrueReg).addMBB(StartMBB)
4876 .addReg(FalseReg).addMBB(FalseMBB);
4878 MI->eraseFromParent();
4882 // Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
4883 // StoreOpcode is the store to use and Invert says whether the store should
4884 // happen when the condition is false rather than true. If a STORE ON
4885 // CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
4887 SystemZTargetLowering::emitCondStore(MachineInstr *MI,
4888 MachineBasicBlock *MBB,
4889 unsigned StoreOpcode, unsigned STOCOpcode,
4890 bool Invert) const {
4891 const SystemZInstrInfo *TII =
4892 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4894 unsigned SrcReg = MI->getOperand(0).getReg();
4895 MachineOperand Base = MI->getOperand(1);
4896 int64_t Disp = MI->getOperand(2).getImm();
4897 unsigned IndexReg = MI->getOperand(3).getReg();
4898 unsigned CCValid = MI->getOperand(4).getImm();
4899 unsigned CCMask = MI->getOperand(5).getImm();
4900 DebugLoc DL = MI->getDebugLoc();
4902 StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
4904 // Use STOCOpcode if possible. We could use different store patterns in
4905 // order to avoid matching the index register, but the performance trade-offs
4906 // might be more complicated in that case.
4907 if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) {
4910 BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
4911 .addReg(SrcReg).addOperand(Base).addImm(Disp)
4912 .addImm(CCValid).addImm(CCMask);
4913 MI->eraseFromParent();
4917 // Get the condition needed to branch around the store.
4921 MachineBasicBlock *StartMBB = MBB;
4922 MachineBasicBlock *JoinMBB = splitBlockBefore(MI, MBB);
4923 MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
4926 // BRC CCMask, JoinMBB
4927 // # fallthrough to FalseMBB
4929 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
4930 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
4931 MBB->addSuccessor(JoinMBB);
4932 MBB->addSuccessor(FalseMBB);
4935 // store %SrcReg, %Disp(%Index,%Base)
4936 // # fallthrough to JoinMBB
4938 BuildMI(MBB, DL, TII->get(StoreOpcode))
4939 .addReg(SrcReg).addOperand(Base).addImm(Disp).addReg(IndexReg);
4940 MBB->addSuccessor(JoinMBB);
4942 MI->eraseFromParent();
4946 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_LOAD{,W}_*
4947 // or ATOMIC_SWAP{,W} instruction MI. BinOpcode is the instruction that
4948 // performs the binary operation elided by "*", or 0 for ATOMIC_SWAP{,W}.
4949 // BitSize is the width of the field in bits, or 0 if this is a partword
4950 // ATOMIC_LOADW_* or ATOMIC_SWAPW instruction, in which case the bitsize
4951 // is one of the operands. Invert says whether the field should be
4952 // inverted after performing BinOpcode (e.g. for NAND).
4954 SystemZTargetLowering::emitAtomicLoadBinary(MachineInstr *MI,
4955 MachineBasicBlock *MBB,
4958 bool Invert) const {
4959 MachineFunction &MF = *MBB->getParent();
4960 const SystemZInstrInfo *TII =
4961 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4962 MachineRegisterInfo &MRI = MF.getRegInfo();
4963 bool IsSubWord = (BitSize < 32);
4965 // Extract the operands. Base can be a register or a frame index.
4966 // Src2 can be a register or immediate.
4967 unsigned Dest = MI->getOperand(0).getReg();
4968 MachineOperand Base = earlyUseOperand(MI->getOperand(1));
4969 int64_t Disp = MI->getOperand(2).getImm();
4970 MachineOperand Src2 = earlyUseOperand(MI->getOperand(3));
4971 unsigned BitShift = (IsSubWord ? MI->getOperand(4).getReg() : 0);
4972 unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
4973 DebugLoc DL = MI->getDebugLoc();
4975 BitSize = MI->getOperand(6).getImm();
4977 // Subword operations use 32-bit registers.
4978 const TargetRegisterClass *RC = (BitSize <= 32 ?
4979 &SystemZ::GR32BitRegClass :
4980 &SystemZ::GR64BitRegClass);
4981 unsigned LOpcode = BitSize <= 32 ? SystemZ::L : SystemZ::LG;
4982 unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
4984 // Get the right opcodes for the displacement.
4985 LOpcode = TII->getOpcodeForOffset(LOpcode, Disp);
4986 CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
4987 assert(LOpcode && CSOpcode && "Displacement out of range");
4989 // Create virtual registers for temporary results.
4990 unsigned OrigVal = MRI.createVirtualRegister(RC);
4991 unsigned OldVal = MRI.createVirtualRegister(RC);
4992 unsigned NewVal = (BinOpcode || IsSubWord ?
4993 MRI.createVirtualRegister(RC) : Src2.getReg());
4994 unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
4995 unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
4997 // Insert a basic block for the main loop.
4998 MachineBasicBlock *StartMBB = MBB;
4999 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5000 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5004 // %OrigVal = L Disp(%Base)
5005 // # fall through to LoopMMB
5007 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
5008 .addOperand(Base).addImm(Disp).addReg(0);
5009 MBB->addSuccessor(LoopMBB);
5012 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
5013 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
5014 // %RotatedNewVal = OP %RotatedOldVal, %Src2
5015 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
5016 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
5018 // # fall through to DoneMMB
5020 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
5021 .addReg(OrigVal).addMBB(StartMBB)
5022 .addReg(Dest).addMBB(LoopMBB);
5024 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
5025 .addReg(OldVal).addReg(BitShift).addImm(0);
5027 // Perform the operation normally and then invert every bit of the field.
5028 unsigned Tmp = MRI.createVirtualRegister(RC);
5029 BuildMI(MBB, DL, TII->get(BinOpcode), Tmp)
5030 .addReg(RotatedOldVal).addOperand(Src2);
5032 // XILF with the upper BitSize bits set.
5033 BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
5034 .addReg(Tmp).addImm(-1U << (32 - BitSize));
5036 // Use LCGR and add -1 to the result, which is more compact than
5037 // an XILF, XILH pair.
5038 unsigned Tmp2 = MRI.createVirtualRegister(RC);
5039 BuildMI(MBB, DL, TII->get(SystemZ::LCGR), Tmp2).addReg(Tmp);
5040 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), RotatedNewVal)
5041 .addReg(Tmp2).addImm(-1);
5043 } else if (BinOpcode)
5044 // A simply binary operation.
5045 BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
5046 .addReg(RotatedOldVal).addOperand(Src2);
5048 // Use RISBG to rotate Src2 into position and use it to replace the
5049 // field in RotatedOldVal.
5050 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
5051 .addReg(RotatedOldVal).addReg(Src2.getReg())
5052 .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize);
5054 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
5055 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
5056 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
5057 .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
5058 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5059 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
5060 MBB->addSuccessor(LoopMBB);
5061 MBB->addSuccessor(DoneMBB);
5063 MI->eraseFromParent();
5067 // Implement EmitInstrWithCustomInserter for pseudo
5068 // ATOMIC_LOAD{,W}_{,U}{MIN,MAX} instruction MI. CompareOpcode is the
5069 // instruction that should be used to compare the current field with the
5070 // minimum or maximum value. KeepOldMask is the BRC condition-code mask
5071 // for when the current field should be kept. BitSize is the width of
5072 // the field in bits, or 0 if this is a partword ATOMIC_LOADW_* instruction.
5074 SystemZTargetLowering::emitAtomicLoadMinMax(MachineInstr *MI,
5075 MachineBasicBlock *MBB,
5076 unsigned CompareOpcode,
5077 unsigned KeepOldMask,
5078 unsigned BitSize) const {
5079 MachineFunction &MF = *MBB->getParent();
5080 const SystemZInstrInfo *TII =
5081 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5082 MachineRegisterInfo &MRI = MF.getRegInfo();
5083 bool IsSubWord = (BitSize < 32);
5085 // Extract the operands. Base can be a register or a frame index.
5086 unsigned Dest = MI->getOperand(0).getReg();
5087 MachineOperand Base = earlyUseOperand(MI->getOperand(1));
5088 int64_t Disp = MI->getOperand(2).getImm();
5089 unsigned Src2 = MI->getOperand(3).getReg();
5090 unsigned BitShift = (IsSubWord ? MI->getOperand(4).getReg() : 0);
5091 unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
5092 DebugLoc DL = MI->getDebugLoc();
5094 BitSize = MI->getOperand(6).getImm();
5096 // Subword operations use 32-bit registers.
5097 const TargetRegisterClass *RC = (BitSize <= 32 ?
5098 &SystemZ::GR32BitRegClass :
5099 &SystemZ::GR64BitRegClass);
5100 unsigned LOpcode = BitSize <= 32 ? SystemZ::L : SystemZ::LG;
5101 unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
5103 // Get the right opcodes for the displacement.
5104 LOpcode = TII->getOpcodeForOffset(LOpcode, Disp);
5105 CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
5106 assert(LOpcode && CSOpcode && "Displacement out of range");
5108 // Create virtual registers for temporary results.
5109 unsigned OrigVal = MRI.createVirtualRegister(RC);
5110 unsigned OldVal = MRI.createVirtualRegister(RC);
5111 unsigned NewVal = MRI.createVirtualRegister(RC);
5112 unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
5113 unsigned RotatedAltVal = (IsSubWord ? MRI.createVirtualRegister(RC) : Src2);
5114 unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
5116 // Insert 3 basic blocks for the loop.
5117 MachineBasicBlock *StartMBB = MBB;
5118 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5119 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5120 MachineBasicBlock *UseAltMBB = emitBlockAfter(LoopMBB);
5121 MachineBasicBlock *UpdateMBB = emitBlockAfter(UseAltMBB);
5125 // %OrigVal = L Disp(%Base)
5126 // # fall through to LoopMMB
5128 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
5129 .addOperand(Base).addImm(Disp).addReg(0);
5130 MBB->addSuccessor(LoopMBB);
5133 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
5134 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
5135 // CompareOpcode %RotatedOldVal, %Src2
5136 // BRC KeepOldMask, UpdateMBB
5138 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
5139 .addReg(OrigVal).addMBB(StartMBB)
5140 .addReg(Dest).addMBB(UpdateMBB);
5142 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
5143 .addReg(OldVal).addReg(BitShift).addImm(0);
5144 BuildMI(MBB, DL, TII->get(CompareOpcode))
5145 .addReg(RotatedOldVal).addReg(Src2);
5146 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5147 .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
5148 MBB->addSuccessor(UpdateMBB);
5149 MBB->addSuccessor(UseAltMBB);
5152 // %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
5153 // # fall through to UpdateMMB
5156 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
5157 .addReg(RotatedOldVal).addReg(Src2)
5158 .addImm(32).addImm(31 + BitSize).addImm(0);
5159 MBB->addSuccessor(UpdateMBB);
5162 // %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
5163 // [ %RotatedAltVal, UseAltMBB ]
5164 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
5165 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
5167 // # fall through to DoneMMB
5169 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
5170 .addReg(RotatedOldVal).addMBB(LoopMBB)
5171 .addReg(RotatedAltVal).addMBB(UseAltMBB);
5173 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
5174 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
5175 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
5176 .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
5177 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5178 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
5179 MBB->addSuccessor(LoopMBB);
5180 MBB->addSuccessor(DoneMBB);
5182 MI->eraseFromParent();
5186 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_CMP_SWAPW
5189 SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr *MI,
5190 MachineBasicBlock *MBB) const {
5191 MachineFunction &MF = *MBB->getParent();
5192 const SystemZInstrInfo *TII =
5193 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5194 MachineRegisterInfo &MRI = MF.getRegInfo();
5196 // Extract the operands. Base can be a register or a frame index.
5197 unsigned Dest = MI->getOperand(0).getReg();
5198 MachineOperand Base = earlyUseOperand(MI->getOperand(1));
5199 int64_t Disp = MI->getOperand(2).getImm();
5200 unsigned OrigCmpVal = MI->getOperand(3).getReg();
5201 unsigned OrigSwapVal = MI->getOperand(4).getReg();
5202 unsigned BitShift = MI->getOperand(5).getReg();
5203 unsigned NegBitShift = MI->getOperand(6).getReg();
5204 int64_t BitSize = MI->getOperand(7).getImm();
5205 DebugLoc DL = MI->getDebugLoc();
5207 const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
5209 // Get the right opcodes for the displacement.
5210 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
5211 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
5212 assert(LOpcode && CSOpcode && "Displacement out of range");
5214 // Create virtual registers for temporary results.
5215 unsigned OrigOldVal = MRI.createVirtualRegister(RC);
5216 unsigned OldVal = MRI.createVirtualRegister(RC);
5217 unsigned CmpVal = MRI.createVirtualRegister(RC);
5218 unsigned SwapVal = MRI.createVirtualRegister(RC);
5219 unsigned StoreVal = MRI.createVirtualRegister(RC);
5220 unsigned RetryOldVal = MRI.createVirtualRegister(RC);
5221 unsigned RetryCmpVal = MRI.createVirtualRegister(RC);
5222 unsigned RetrySwapVal = MRI.createVirtualRegister(RC);
5224 // Insert 2 basic blocks for the loop.
5225 MachineBasicBlock *StartMBB = MBB;
5226 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5227 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5228 MachineBasicBlock *SetMBB = emitBlockAfter(LoopMBB);
5232 // %OrigOldVal = L Disp(%Base)
5233 // # fall through to LoopMMB
5235 BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
5236 .addOperand(Base).addImm(Disp).addReg(0);
5237 MBB->addSuccessor(LoopMBB);
5240 // %OldVal = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
5241 // %CmpVal = phi [ %OrigCmpVal, EntryBB ], [ %RetryCmpVal, SetMBB ]
5242 // %SwapVal = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
5243 // %Dest = RLL %OldVal, BitSize(%BitShift)
5244 // ^^ The low BitSize bits contain the field
5246 // %RetryCmpVal = RISBG32 %CmpVal, %Dest, 32, 63-BitSize, 0
5247 // ^^ Replace the upper 32-BitSize bits of the
5248 // comparison value with those that we loaded,
5249 // so that we can use a full word comparison.
5250 // CR %Dest, %RetryCmpVal
5252 // # Fall through to SetMBB
5254 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
5255 .addReg(OrigOldVal).addMBB(StartMBB)
5256 .addReg(RetryOldVal).addMBB(SetMBB);
5257 BuildMI(MBB, DL, TII->get(SystemZ::PHI), CmpVal)
5258 .addReg(OrigCmpVal).addMBB(StartMBB)
5259 .addReg(RetryCmpVal).addMBB(SetMBB);
5260 BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
5261 .addReg(OrigSwapVal).addMBB(StartMBB)
5262 .addReg(RetrySwapVal).addMBB(SetMBB);
5263 BuildMI(MBB, DL, TII->get(SystemZ::RLL), Dest)
5264 .addReg(OldVal).addReg(BitShift).addImm(BitSize);
5265 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetryCmpVal)
5266 .addReg(CmpVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
5267 BuildMI(MBB, DL, TII->get(SystemZ::CR))
5268 .addReg(Dest).addReg(RetryCmpVal);
5269 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5270 .addImm(SystemZ::CCMASK_ICMP)
5271 .addImm(SystemZ::CCMASK_CMP_NE).addMBB(DoneMBB);
5272 MBB->addSuccessor(DoneMBB);
5273 MBB->addSuccessor(SetMBB);
5276 // %RetrySwapVal = RISBG32 %SwapVal, %Dest, 32, 63-BitSize, 0
5277 // ^^ Replace the upper 32-BitSize bits of the new
5278 // value with those that we loaded.
5279 // %StoreVal = RLL %RetrySwapVal, -BitSize(%NegBitShift)
5280 // ^^ Rotate the new field to its proper position.
5281 // %RetryOldVal = CS %Dest, %StoreVal, Disp(%Base)
5283 // # fall through to ExitMMB
5285 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
5286 .addReg(SwapVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
5287 BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
5288 .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
5289 BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
5290 .addReg(OldVal).addReg(StoreVal).addOperand(Base).addImm(Disp);
5291 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5292 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
5293 MBB->addSuccessor(LoopMBB);
5294 MBB->addSuccessor(DoneMBB);
5296 MI->eraseFromParent();
5300 // Emit an extension from a GR32 or GR64 to a GR128. ClearEven is true
5301 // if the high register of the GR128 value must be cleared or false if
5302 // it's "don't care". SubReg is subreg_l32 when extending a GR32
5303 // and subreg_l64 when extending a GR64.
5305 SystemZTargetLowering::emitExt128(MachineInstr *MI,
5306 MachineBasicBlock *MBB,
5307 bool ClearEven, unsigned SubReg) const {
5308 MachineFunction &MF = *MBB->getParent();
5309 const SystemZInstrInfo *TII =
5310 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5311 MachineRegisterInfo &MRI = MF.getRegInfo();
5312 DebugLoc DL = MI->getDebugLoc();
5314 unsigned Dest = MI->getOperand(0).getReg();
5315 unsigned Src = MI->getOperand(1).getReg();
5316 unsigned In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
5318 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128);
5320 unsigned NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
5321 unsigned Zero64 = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
5323 BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64)
5325 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128)
5326 .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_h64);
5329 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
5330 .addReg(In128).addReg(Src).addImm(SubReg);
5332 MI->eraseFromParent();
5337 SystemZTargetLowering::emitMemMemWrapper(MachineInstr *MI,
5338 MachineBasicBlock *MBB,
5339 unsigned Opcode) const {
5340 MachineFunction &MF = *MBB->getParent();
5341 const SystemZInstrInfo *TII =
5342 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5343 MachineRegisterInfo &MRI = MF.getRegInfo();
5344 DebugLoc DL = MI->getDebugLoc();
5346 MachineOperand DestBase = earlyUseOperand(MI->getOperand(0));
5347 uint64_t DestDisp = MI->getOperand(1).getImm();
5348 MachineOperand SrcBase = earlyUseOperand(MI->getOperand(2));
5349 uint64_t SrcDisp = MI->getOperand(3).getImm();
5350 uint64_t Length = MI->getOperand(4).getImm();
5352 // When generating more than one CLC, all but the last will need to
5353 // branch to the end when a difference is found.
5354 MachineBasicBlock *EndMBB = (Length > 256 && Opcode == SystemZ::CLC ?
5355 splitBlockAfter(MI, MBB) : nullptr);
5357 // Check for the loop form, in which operand 5 is the trip count.
5358 if (MI->getNumExplicitOperands() > 5) {
5359 bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
5361 uint64_t StartCountReg = MI->getOperand(5).getReg();
5362 uint64_t StartSrcReg = forceReg(MI, SrcBase, TII);
5363 uint64_t StartDestReg = (HaveSingleBase ? StartSrcReg :
5364 forceReg(MI, DestBase, TII));
5366 const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
5367 uint64_t ThisSrcReg = MRI.createVirtualRegister(RC);
5368 uint64_t ThisDestReg = (HaveSingleBase ? ThisSrcReg :
5369 MRI.createVirtualRegister(RC));
5370 uint64_t NextSrcReg = MRI.createVirtualRegister(RC);
5371 uint64_t NextDestReg = (HaveSingleBase ? NextSrcReg :
5372 MRI.createVirtualRegister(RC));
5374 RC = &SystemZ::GR64BitRegClass;
5375 uint64_t ThisCountReg = MRI.createVirtualRegister(RC);
5376 uint64_t NextCountReg = MRI.createVirtualRegister(RC);
5378 MachineBasicBlock *StartMBB = MBB;
5379 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5380 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5381 MachineBasicBlock *NextMBB = (EndMBB ? emitBlockAfter(LoopMBB) : LoopMBB);
5384 // # fall through to LoopMMB
5385 MBB->addSuccessor(LoopMBB);
5388 // %ThisDestReg = phi [ %StartDestReg, StartMBB ],
5389 // [ %NextDestReg, NextMBB ]
5390 // %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
5391 // [ %NextSrcReg, NextMBB ]
5392 // %ThisCountReg = phi [ %StartCountReg, StartMBB ],
5393 // [ %NextCountReg, NextMBB ]
5394 // ( PFD 2, 768+DestDisp(%ThisDestReg) )
5395 // Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
5398 // The prefetch is used only for MVC. The JLH is used only for CLC.
5401 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
5402 .addReg(StartDestReg).addMBB(StartMBB)
5403 .addReg(NextDestReg).addMBB(NextMBB);
5404 if (!HaveSingleBase)
5405 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
5406 .addReg(StartSrcReg).addMBB(StartMBB)
5407 .addReg(NextSrcReg).addMBB(NextMBB);
5408 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
5409 .addReg(StartCountReg).addMBB(StartMBB)
5410 .addReg(NextCountReg).addMBB(NextMBB);
5411 if (Opcode == SystemZ::MVC)
5412 BuildMI(MBB, DL, TII->get(SystemZ::PFD))
5413 .addImm(SystemZ::PFD_WRITE)
5414 .addReg(ThisDestReg).addImm(DestDisp + 768).addReg(0);
5415 BuildMI(MBB, DL, TII->get(Opcode))
5416 .addReg(ThisDestReg).addImm(DestDisp).addImm(256)
5417 .addReg(ThisSrcReg).addImm(SrcDisp);
5419 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5420 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5422 MBB->addSuccessor(EndMBB);
5423 MBB->addSuccessor(NextMBB);
5427 // %NextDestReg = LA 256(%ThisDestReg)
5428 // %NextSrcReg = LA 256(%ThisSrcReg)
5429 // %NextCountReg = AGHI %ThisCountReg, -1
5430 // CGHI %NextCountReg, 0
5432 // # fall through to DoneMMB
5434 // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
5437 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
5438 .addReg(ThisDestReg).addImm(256).addReg(0);
5439 if (!HaveSingleBase)
5440 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
5441 .addReg(ThisSrcReg).addImm(256).addReg(0);
5442 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
5443 .addReg(ThisCountReg).addImm(-1);
5444 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
5445 .addReg(NextCountReg).addImm(0);
5446 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5447 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5449 MBB->addSuccessor(LoopMBB);
5450 MBB->addSuccessor(DoneMBB);
5452 DestBase = MachineOperand::CreateReg(NextDestReg, false);
5453 SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
5457 // Handle any remaining bytes with straight-line code.
5458 while (Length > 0) {
5459 uint64_t ThisLength = std::min(Length, uint64_t(256));
5460 // The previous iteration might have created out-of-range displacements.
5461 // Apply them using LAY if so.
5462 if (!isUInt<12>(DestDisp)) {
5463 unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
5464 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
5465 .addOperand(DestBase).addImm(DestDisp).addReg(0);
5466 DestBase = MachineOperand::CreateReg(Reg, false);
5469 if (!isUInt<12>(SrcDisp)) {
5470 unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
5471 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
5472 .addOperand(SrcBase).addImm(SrcDisp).addReg(0);
5473 SrcBase = MachineOperand::CreateReg(Reg, false);
5476 BuildMI(*MBB, MI, DL, TII->get(Opcode))
5477 .addOperand(DestBase).addImm(DestDisp).addImm(ThisLength)
5478 .addOperand(SrcBase).addImm(SrcDisp);
5479 DestDisp += ThisLength;
5480 SrcDisp += ThisLength;
5481 Length -= ThisLength;
5482 // If there's another CLC to go, branch to the end if a difference
5484 if (EndMBB && Length > 0) {
5485 MachineBasicBlock *NextMBB = splitBlockBefore(MI, MBB);
5486 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5487 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5489 MBB->addSuccessor(EndMBB);
5490 MBB->addSuccessor(NextMBB);
5495 MBB->addSuccessor(EndMBB);
5497 MBB->addLiveIn(SystemZ::CC);
5500 MI->eraseFromParent();
5504 // Decompose string pseudo-instruction MI into a loop that continually performs
5505 // Opcode until CC != 3.
5507 SystemZTargetLowering::emitStringWrapper(MachineInstr *MI,
5508 MachineBasicBlock *MBB,
5509 unsigned Opcode) const {
5510 MachineFunction &MF = *MBB->getParent();
5511 const SystemZInstrInfo *TII =
5512 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5513 MachineRegisterInfo &MRI = MF.getRegInfo();
5514 DebugLoc DL = MI->getDebugLoc();
5516 uint64_t End1Reg = MI->getOperand(0).getReg();
5517 uint64_t Start1Reg = MI->getOperand(1).getReg();
5518 uint64_t Start2Reg = MI->getOperand(2).getReg();
5519 uint64_t CharReg = MI->getOperand(3).getReg();
5521 const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
5522 uint64_t This1Reg = MRI.createVirtualRegister(RC);
5523 uint64_t This2Reg = MRI.createVirtualRegister(RC);
5524 uint64_t End2Reg = MRI.createVirtualRegister(RC);
5526 MachineBasicBlock *StartMBB = MBB;
5527 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5528 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5531 // # fall through to LoopMMB
5532 MBB->addSuccessor(LoopMBB);
5535 // %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
5536 // %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
5538 // %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
5540 // # fall through to DoneMMB
5542 // The load of R0L can be hoisted by post-RA LICM.
5545 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
5546 .addReg(Start1Reg).addMBB(StartMBB)
5547 .addReg(End1Reg).addMBB(LoopMBB);
5548 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
5549 .addReg(Start2Reg).addMBB(StartMBB)
5550 .addReg(End2Reg).addMBB(LoopMBB);
5551 BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
5552 BuildMI(MBB, DL, TII->get(Opcode))
5553 .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
5554 .addReg(This1Reg).addReg(This2Reg);
5555 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5556 .addImm(SystemZ::CCMASK_ANY).addImm(SystemZ::CCMASK_3).addMBB(LoopMBB);
5557 MBB->addSuccessor(LoopMBB);
5558 MBB->addSuccessor(DoneMBB);
5560 DoneMBB->addLiveIn(SystemZ::CC);
5562 MI->eraseFromParent();
5566 // Update TBEGIN instruction with final opcode and register clobbers.
5568 SystemZTargetLowering::emitTransactionBegin(MachineInstr *MI,
5569 MachineBasicBlock *MBB,
5571 bool NoFloat) const {
5572 MachineFunction &MF = *MBB->getParent();
5573 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
5574 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
5577 MI->setDesc(TII->get(Opcode));
5579 // We cannot handle a TBEGIN that clobbers the stack or frame pointer.
5580 // Make sure to add the corresponding GRSM bits if they are missing.
5581 uint64_t Control = MI->getOperand(2).getImm();
5582 static const unsigned GPRControlBit[16] = {
5583 0x8000, 0x8000, 0x4000, 0x4000, 0x2000, 0x2000, 0x1000, 0x1000,
5584 0x0800, 0x0800, 0x0400, 0x0400, 0x0200, 0x0200, 0x0100, 0x0100
5586 Control |= GPRControlBit[15];
5588 Control |= GPRControlBit[11];
5589 MI->getOperand(2).setImm(Control);
5591 // Add GPR clobbers.
5592 for (int I = 0; I < 16; I++) {
5593 if ((Control & GPRControlBit[I]) == 0) {
5594 unsigned Reg = SystemZMC::GR64Regs[I];
5595 MI->addOperand(MachineOperand::CreateReg(Reg, true, true));
5599 // Add FPR/VR clobbers.
5600 if (!NoFloat && (Control & 4) != 0) {
5601 if (Subtarget.hasVector()) {
5602 for (int I = 0; I < 32; I++) {
5603 unsigned Reg = SystemZMC::VR128Regs[I];
5604 MI->addOperand(MachineOperand::CreateReg(Reg, true, true));
5607 for (int I = 0; I < 16; I++) {
5608 unsigned Reg = SystemZMC::FP64Regs[I];
5609 MI->addOperand(MachineOperand::CreateReg(Reg, true, true));
5618 SystemZTargetLowering::emitLoadAndTestCmp0(MachineInstr *MI,
5619 MachineBasicBlock *MBB,
5620 unsigned Opcode) const {
5621 MachineFunction &MF = *MBB->getParent();
5622 MachineRegisterInfo *MRI = &MF.getRegInfo();
5623 const SystemZInstrInfo *TII =
5624 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5625 DebugLoc DL = MI->getDebugLoc();
5627 unsigned SrcReg = MI->getOperand(0).getReg();
5629 // Create new virtual register of the same class as source.
5630 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
5631 unsigned DstReg = MRI->createVirtualRegister(RC);
5633 // Replace pseudo with a normal load-and-test that models the def as
5635 BuildMI(*MBB, MI, DL, TII->get(Opcode), DstReg)
5637 MI->eraseFromParent();
5642 MachineBasicBlock *SystemZTargetLowering::
5643 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const {
5644 switch (MI->getOpcode()) {
5645 case SystemZ::Select32Mux:
5646 case SystemZ::Select32:
5647 case SystemZ::SelectF32:
5648 case SystemZ::Select64:
5649 case SystemZ::SelectF64:
5650 case SystemZ::SelectF128:
5651 return emitSelect(MI, MBB);
5653 case SystemZ::CondStore8Mux:
5654 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
5655 case SystemZ::CondStore8MuxInv:
5656 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
5657 case SystemZ::CondStore16Mux:
5658 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
5659 case SystemZ::CondStore16MuxInv:
5660 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
5661 case SystemZ::CondStore8:
5662 return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
5663 case SystemZ::CondStore8Inv:
5664 return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
5665 case SystemZ::CondStore16:
5666 return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
5667 case SystemZ::CondStore16Inv:
5668 return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
5669 case SystemZ::CondStore32:
5670 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
5671 case SystemZ::CondStore32Inv:
5672 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
5673 case SystemZ::CondStore64:
5674 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
5675 case SystemZ::CondStore64Inv:
5676 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
5677 case SystemZ::CondStoreF32:
5678 return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
5679 case SystemZ::CondStoreF32Inv:
5680 return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
5681 case SystemZ::CondStoreF64:
5682 return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
5683 case SystemZ::CondStoreF64Inv:
5684 return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
5686 case SystemZ::AEXT128_64:
5687 return emitExt128(MI, MBB, false, SystemZ::subreg_l64);
5688 case SystemZ::ZEXT128_32:
5689 return emitExt128(MI, MBB, true, SystemZ::subreg_l32);
5690 case SystemZ::ZEXT128_64:
5691 return emitExt128(MI, MBB, true, SystemZ::subreg_l64);
5693 case SystemZ::ATOMIC_SWAPW:
5694 return emitAtomicLoadBinary(MI, MBB, 0, 0);
5695 case SystemZ::ATOMIC_SWAP_32:
5696 return emitAtomicLoadBinary(MI, MBB, 0, 32);
5697 case SystemZ::ATOMIC_SWAP_64:
5698 return emitAtomicLoadBinary(MI, MBB, 0, 64);
5700 case SystemZ::ATOMIC_LOADW_AR:
5701 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 0);
5702 case SystemZ::ATOMIC_LOADW_AFI:
5703 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 0);
5704 case SystemZ::ATOMIC_LOAD_AR:
5705 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 32);
5706 case SystemZ::ATOMIC_LOAD_AHI:
5707 return emitAtomicLoadBinary(MI, MBB, SystemZ::AHI, 32);
5708 case SystemZ::ATOMIC_LOAD_AFI:
5709 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 32);
5710 case SystemZ::ATOMIC_LOAD_AGR:
5711 return emitAtomicLoadBinary(MI, MBB, SystemZ::AGR, 64);
5712 case SystemZ::ATOMIC_LOAD_AGHI:
5713 return emitAtomicLoadBinary(MI, MBB, SystemZ::AGHI, 64);
5714 case SystemZ::ATOMIC_LOAD_AGFI:
5715 return emitAtomicLoadBinary(MI, MBB, SystemZ::AGFI, 64);
5717 case SystemZ::ATOMIC_LOADW_SR:
5718 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 0);
5719 case SystemZ::ATOMIC_LOAD_SR:
5720 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 32);
5721 case SystemZ::ATOMIC_LOAD_SGR:
5722 return emitAtomicLoadBinary(MI, MBB, SystemZ::SGR, 64);
5724 case SystemZ::ATOMIC_LOADW_NR:
5725 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0);
5726 case SystemZ::ATOMIC_LOADW_NILH:
5727 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0);
5728 case SystemZ::ATOMIC_LOAD_NR:
5729 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32);
5730 case SystemZ::ATOMIC_LOAD_NILL:
5731 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32);
5732 case SystemZ::ATOMIC_LOAD_NILH:
5733 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32);
5734 case SystemZ::ATOMIC_LOAD_NILF:
5735 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32);
5736 case SystemZ::ATOMIC_LOAD_NGR:
5737 return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64);
5738 case SystemZ::ATOMIC_LOAD_NILL64:
5739 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64);
5740 case SystemZ::ATOMIC_LOAD_NILH64:
5741 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64);
5742 case SystemZ::ATOMIC_LOAD_NIHL64:
5743 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64);
5744 case SystemZ::ATOMIC_LOAD_NIHH64:
5745 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64);
5746 case SystemZ::ATOMIC_LOAD_NILF64:
5747 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64);
5748 case SystemZ::ATOMIC_LOAD_NIHF64:
5749 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64);
5751 case SystemZ::ATOMIC_LOADW_OR:
5752 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 0);
5753 case SystemZ::ATOMIC_LOADW_OILH:
5754 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 0);
5755 case SystemZ::ATOMIC_LOAD_OR:
5756 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 32);
5757 case SystemZ::ATOMIC_LOAD_OILL:
5758 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL, 32);
5759 case SystemZ::ATOMIC_LOAD_OILH:
5760 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 32);
5761 case SystemZ::ATOMIC_LOAD_OILF:
5762 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF, 32);
5763 case SystemZ::ATOMIC_LOAD_OGR:
5764 return emitAtomicLoadBinary(MI, MBB, SystemZ::OGR, 64);
5765 case SystemZ::ATOMIC_LOAD_OILL64:
5766 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL64, 64);
5767 case SystemZ::ATOMIC_LOAD_OILH64:
5768 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH64, 64);
5769 case SystemZ::ATOMIC_LOAD_OIHL64:
5770 return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHL64, 64);
5771 case SystemZ::ATOMIC_LOAD_OIHH64:
5772 return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHH64, 64);
5773 case SystemZ::ATOMIC_LOAD_OILF64:
5774 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF64, 64);
5775 case SystemZ::ATOMIC_LOAD_OIHF64:
5776 return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHF64, 64);
5778 case SystemZ::ATOMIC_LOADW_XR:
5779 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 0);
5780 case SystemZ::ATOMIC_LOADW_XILF:
5781 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 0);
5782 case SystemZ::ATOMIC_LOAD_XR:
5783 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 32);
5784 case SystemZ::ATOMIC_LOAD_XILF:
5785 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 32);
5786 case SystemZ::ATOMIC_LOAD_XGR:
5787 return emitAtomicLoadBinary(MI, MBB, SystemZ::XGR, 64);
5788 case SystemZ::ATOMIC_LOAD_XILF64:
5789 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF64, 64);
5790 case SystemZ::ATOMIC_LOAD_XIHF64:
5791 return emitAtomicLoadBinary(MI, MBB, SystemZ::XIHF64, 64);
5793 case SystemZ::ATOMIC_LOADW_NRi:
5794 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0, true);
5795 case SystemZ::ATOMIC_LOADW_NILHi:
5796 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0, true);
5797 case SystemZ::ATOMIC_LOAD_NRi:
5798 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32, true);
5799 case SystemZ::ATOMIC_LOAD_NILLi:
5800 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32, true);
5801 case SystemZ::ATOMIC_LOAD_NILHi:
5802 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32, true);
5803 case SystemZ::ATOMIC_LOAD_NILFi:
5804 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32, true);
5805 case SystemZ::ATOMIC_LOAD_NGRi:
5806 return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64, true);
5807 case SystemZ::ATOMIC_LOAD_NILL64i:
5808 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64, true);
5809 case SystemZ::ATOMIC_LOAD_NILH64i:
5810 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64, true);
5811 case SystemZ::ATOMIC_LOAD_NIHL64i:
5812 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64, true);
5813 case SystemZ::ATOMIC_LOAD_NIHH64i:
5814 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64, true);
5815 case SystemZ::ATOMIC_LOAD_NILF64i:
5816 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64, true);
5817 case SystemZ::ATOMIC_LOAD_NIHF64i:
5818 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64, true);
5820 case SystemZ::ATOMIC_LOADW_MIN:
5821 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
5822 SystemZ::CCMASK_CMP_LE, 0);
5823 case SystemZ::ATOMIC_LOAD_MIN_32:
5824 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
5825 SystemZ::CCMASK_CMP_LE, 32);
5826 case SystemZ::ATOMIC_LOAD_MIN_64:
5827 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
5828 SystemZ::CCMASK_CMP_LE, 64);
5830 case SystemZ::ATOMIC_LOADW_MAX:
5831 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
5832 SystemZ::CCMASK_CMP_GE, 0);
5833 case SystemZ::ATOMIC_LOAD_MAX_32:
5834 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
5835 SystemZ::CCMASK_CMP_GE, 32);
5836 case SystemZ::ATOMIC_LOAD_MAX_64:
5837 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
5838 SystemZ::CCMASK_CMP_GE, 64);
5840 case SystemZ::ATOMIC_LOADW_UMIN:
5841 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
5842 SystemZ::CCMASK_CMP_LE, 0);
5843 case SystemZ::ATOMIC_LOAD_UMIN_32:
5844 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
5845 SystemZ::CCMASK_CMP_LE, 32);
5846 case SystemZ::ATOMIC_LOAD_UMIN_64:
5847 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
5848 SystemZ::CCMASK_CMP_LE, 64);
5850 case SystemZ::ATOMIC_LOADW_UMAX:
5851 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
5852 SystemZ::CCMASK_CMP_GE, 0);
5853 case SystemZ::ATOMIC_LOAD_UMAX_32:
5854 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
5855 SystemZ::CCMASK_CMP_GE, 32);
5856 case SystemZ::ATOMIC_LOAD_UMAX_64:
5857 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
5858 SystemZ::CCMASK_CMP_GE, 64);
5860 case SystemZ::ATOMIC_CMP_SWAPW:
5861 return emitAtomicCmpSwapW(MI, MBB);
5862 case SystemZ::MVCSequence:
5863 case SystemZ::MVCLoop:
5864 return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
5865 case SystemZ::NCSequence:
5866 case SystemZ::NCLoop:
5867 return emitMemMemWrapper(MI, MBB, SystemZ::NC);
5868 case SystemZ::OCSequence:
5869 case SystemZ::OCLoop:
5870 return emitMemMemWrapper(MI, MBB, SystemZ::OC);
5871 case SystemZ::XCSequence:
5872 case SystemZ::XCLoop:
5873 return emitMemMemWrapper(MI, MBB, SystemZ::XC);
5874 case SystemZ::CLCSequence:
5875 case SystemZ::CLCLoop:
5876 return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
5877 case SystemZ::CLSTLoop:
5878 return emitStringWrapper(MI, MBB, SystemZ::CLST);
5879 case SystemZ::MVSTLoop:
5880 return emitStringWrapper(MI, MBB, SystemZ::MVST);
5881 case SystemZ::SRSTLoop:
5882 return emitStringWrapper(MI, MBB, SystemZ::SRST);
5883 case SystemZ::TBEGIN:
5884 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, false);
5885 case SystemZ::TBEGIN_nofloat:
5886 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, true);
5887 case SystemZ::TBEGINC:
5888 return emitTransactionBegin(MI, MBB, SystemZ::TBEGINC, true);
5889 case SystemZ::LTEBRCompare_VecPseudo:
5890 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTEBR);
5891 case SystemZ::LTDBRCompare_VecPseudo:
5892 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTDBR);
5893 case SystemZ::LTXBRCompare_VecPseudo:
5894 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTXBR);
5897 llvm_unreachable("Unexpected instr type to insert");