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::ROTR, VT, Expand);
189 // Use *MUL_LOHI where possible instead of MULH*.
190 setOperationAction(ISD::MULHS, VT, Expand);
191 setOperationAction(ISD::MULHU, VT, Expand);
192 setOperationAction(ISD::SMUL_LOHI, VT, Custom);
193 setOperationAction(ISD::UMUL_LOHI, VT, Custom);
195 // Only z196 and above have native support for conversions to unsigned.
196 if (!Subtarget.hasFPExtension())
197 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
201 // Type legalization will convert 8- and 16-bit atomic operations into
202 // forms that operate on i32s (but still keeping the original memory VT).
203 // Lower them into full i32 operations.
204 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Custom);
205 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Custom);
206 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
207 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
208 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Custom);
209 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Custom);
210 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Custom);
211 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Custom);
212 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Custom);
213 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Custom);
214 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Custom);
215 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
217 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
219 // Traps are legal, as we will convert them to "j .+2".
220 setOperationAction(ISD::TRAP, MVT::Other, Legal);
222 // z10 has instructions for signed but not unsigned FP conversion.
223 // Handle unsigned 32-bit types as signed 64-bit types.
224 if (!Subtarget.hasFPExtension()) {
225 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote);
226 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
229 // We have native support for a 64-bit CTLZ, via FLOGR.
230 setOperationAction(ISD::CTLZ, MVT::i32, Promote);
231 setOperationAction(ISD::CTLZ, MVT::i64, Legal);
233 // Give LowerOperation the chance to replace 64-bit ORs with subregs.
234 setOperationAction(ISD::OR, MVT::i64, Custom);
236 // FIXME: Can we support these natively?
237 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
238 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
239 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
241 // We have native instructions for i8, i16 and i32 extensions, but not i1.
242 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
243 for (MVT VT : MVT::integer_valuetypes()) {
244 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
245 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
246 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
249 // Handle the various types of symbolic address.
250 setOperationAction(ISD::ConstantPool, PtrVT, Custom);
251 setOperationAction(ISD::GlobalAddress, PtrVT, Custom);
252 setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom);
253 setOperationAction(ISD::BlockAddress, PtrVT, Custom);
254 setOperationAction(ISD::JumpTable, PtrVT, Custom);
256 // We need to handle dynamic allocations specially because of the
257 // 160-byte area at the bottom of the stack.
258 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
259 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, PtrVT, Custom);
261 // Use custom expanders so that we can force the function to use
263 setOperationAction(ISD::STACKSAVE, MVT::Other, Custom);
264 setOperationAction(ISD::STACKRESTORE, MVT::Other, Custom);
266 // Handle prefetches with PFD or PFDRL.
267 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
269 for (MVT VT : MVT::vector_valuetypes()) {
270 // Assume by default that all vector operations need to be expanded.
271 for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
272 if (getOperationAction(Opcode, VT) == Legal)
273 setOperationAction(Opcode, VT, Expand);
275 // Likewise all truncating stores and extending loads.
276 for (MVT InnerVT : MVT::vector_valuetypes()) {
277 setTruncStoreAction(VT, InnerVT, Expand);
278 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
279 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
280 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
283 if (isTypeLegal(VT)) {
284 // These operations are legal for anything that can be stored in a
285 // vector register, even if there is no native support for the format
286 // as such. In particular, we can do these for v4f32 even though there
287 // are no specific instructions for that format.
288 setOperationAction(ISD::LOAD, VT, Legal);
289 setOperationAction(ISD::STORE, VT, Legal);
290 setOperationAction(ISD::VSELECT, VT, Legal);
291 setOperationAction(ISD::BITCAST, VT, Legal);
292 setOperationAction(ISD::UNDEF, VT, Legal);
294 // Likewise, except that we need to replace the nodes with something
296 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
297 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
301 // Handle integer vector types.
302 for (MVT VT : MVT::integer_vector_valuetypes()) {
303 if (isTypeLegal(VT)) {
304 // These operations have direct equivalents.
305 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Legal);
306 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Legal);
307 setOperationAction(ISD::ADD, VT, Legal);
308 setOperationAction(ISD::SUB, VT, Legal);
309 if (VT != MVT::v2i64)
310 setOperationAction(ISD::MUL, VT, Legal);
311 setOperationAction(ISD::AND, VT, Legal);
312 setOperationAction(ISD::OR, VT, Legal);
313 setOperationAction(ISD::XOR, VT, Legal);
314 setOperationAction(ISD::CTPOP, VT, Custom);
315 setOperationAction(ISD::CTTZ, VT, Legal);
316 setOperationAction(ISD::CTLZ, VT, Legal);
318 // Convert a GPR scalar to a vector by inserting it into element 0.
319 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
321 // Use a series of unpacks for extensions.
322 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
323 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
325 // Detect shifts by a scalar amount and convert them into
327 setOperationAction(ISD::SHL, VT, Custom);
328 setOperationAction(ISD::SRA, VT, Custom);
329 setOperationAction(ISD::SRL, VT, Custom);
331 // At present ROTL isn't matched by DAGCombiner. ROTR should be
332 // converted into ROTL.
333 setOperationAction(ISD::ROTL, VT, Expand);
334 setOperationAction(ISD::ROTR, VT, Expand);
336 // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
337 // and inverting the result as necessary.
338 setOperationAction(ISD::SETCC, VT, Custom);
342 if (Subtarget.hasVector()) {
343 // There should be no need to check for float types other than v2f64
344 // since <2 x f32> isn't a legal type.
345 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
346 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
347 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
348 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
351 // Handle floating-point types.
352 for (unsigned I = MVT::FIRST_FP_VALUETYPE;
353 I <= MVT::LAST_FP_VALUETYPE;
355 MVT VT = MVT::SimpleValueType(I);
356 if (isTypeLegal(VT)) {
357 // We can use FI for FRINT.
358 setOperationAction(ISD::FRINT, VT, Legal);
360 // We can use the extended form of FI for other rounding operations.
361 if (Subtarget.hasFPExtension()) {
362 setOperationAction(ISD::FNEARBYINT, VT, Legal);
363 setOperationAction(ISD::FFLOOR, VT, Legal);
364 setOperationAction(ISD::FCEIL, VT, Legal);
365 setOperationAction(ISD::FTRUNC, VT, Legal);
366 setOperationAction(ISD::FROUND, VT, Legal);
369 // No special instructions for these.
370 setOperationAction(ISD::FSIN, VT, Expand);
371 setOperationAction(ISD::FCOS, VT, Expand);
372 setOperationAction(ISD::FSINCOS, VT, Expand);
373 setOperationAction(ISD::FREM, VT, Expand);
374 setOperationAction(ISD::FPOW, VT, Expand);
378 // Handle floating-point vector types.
379 if (Subtarget.hasVector()) {
380 // Scalar-to-vector conversion is just a subreg.
381 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
382 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
384 // Some insertions and extractions can be done directly but others
385 // need to go via integers.
386 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
387 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
388 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
389 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
391 // These operations have direct equivalents.
392 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
393 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
394 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
395 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
396 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
397 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
398 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
399 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
400 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
401 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
402 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
403 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
404 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
405 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
408 // We have fused multiply-addition for f32 and f64 but not f128.
409 setOperationAction(ISD::FMA, MVT::f32, Legal);
410 setOperationAction(ISD::FMA, MVT::f64, Legal);
411 setOperationAction(ISD::FMA, MVT::f128, Expand);
413 // Needed so that we don't try to implement f128 constant loads using
414 // a load-and-extend of a f80 constant (in cases where the constant
415 // would fit in an f80).
416 for (MVT VT : MVT::fp_valuetypes())
417 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
419 // Floating-point truncation and stores need to be done separately.
420 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
421 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
422 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
424 // We have 64-bit FPR<->GPR moves, but need special handling for
426 if (!Subtarget.hasVector()) {
427 setOperationAction(ISD::BITCAST, MVT::i32, Custom);
428 setOperationAction(ISD::BITCAST, MVT::f32, Custom);
431 // VASTART and VACOPY need to deal with the SystemZ-specific varargs
432 // structure, but VAEND is a no-op.
433 setOperationAction(ISD::VASTART, MVT::Other, Custom);
434 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
435 setOperationAction(ISD::VAEND, MVT::Other, Expand);
437 // Codes for which we want to perform some z-specific combinations.
438 setTargetDAGCombine(ISD::SIGN_EXTEND);
439 setTargetDAGCombine(ISD::STORE);
440 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
441 setTargetDAGCombine(ISD::FP_ROUND);
442 setTargetDAGCombine(ISD::BSWAP);
443 setTargetDAGCombine(ISD::SHL);
444 setTargetDAGCombine(ISD::SRA);
445 setTargetDAGCombine(ISD::SRL);
446 setTargetDAGCombine(ISD::ROTL);
448 // Handle intrinsics.
449 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
450 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
452 // We want to use MVC in preference to even a single load/store pair.
453 MaxStoresPerMemcpy = 0;
454 MaxStoresPerMemcpyOptSize = 0;
456 // The main memset sequence is a byte store followed by an MVC.
457 // Two STC or MV..I stores win over that, but the kind of fused stores
458 // generated by target-independent code don't when the byte value is
459 // variable. E.g. "STC <reg>;MHI <reg>,257;STH <reg>" is not better
460 // than "STC;MVC". Handle the choice in target-specific code instead.
461 MaxStoresPerMemset = 0;
462 MaxStoresPerMemsetOptSize = 0;
465 EVT SystemZTargetLowering::getSetCCResultType(const DataLayout &DL,
466 LLVMContext &, EVT VT) const {
469 return VT.changeVectorElementTypeToInteger();
472 bool SystemZTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
473 VT = VT.getScalarType();
478 switch (VT.getSimpleVT().SimpleTy) {
491 bool SystemZTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
492 // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
493 return Imm.isZero() || Imm.isNegZero();
496 bool SystemZTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
497 // We can use CGFI or CLGFI.
498 return isInt<32>(Imm) || isUInt<32>(Imm);
501 bool SystemZTargetLowering::isLegalAddImmediate(int64_t Imm) const {
502 // We can use ALGFI or SLGFI.
503 return isUInt<32>(Imm) || isUInt<32>(-Imm);
506 bool SystemZTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
510 // Unaligned accesses should never be slower than the expanded version.
511 // We check specifically for aligned accesses in the few cases where
512 // they are required.
518 bool SystemZTargetLowering::isLegalAddressingMode(const DataLayout &DL,
519 const AddrMode &AM, Type *Ty,
521 // Punt on globals for now, although they can be used in limited
522 // RELATIVE LONG cases.
526 // Require a 20-bit signed offset.
527 if (!isInt<20>(AM.BaseOffs))
530 // Indexing is OK but no scale factor can be applied.
531 return AM.Scale == 0 || AM.Scale == 1;
534 bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
535 if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
537 unsigned FromBits = FromType->getPrimitiveSizeInBits();
538 unsigned ToBits = ToType->getPrimitiveSizeInBits();
539 return FromBits > ToBits;
542 bool SystemZTargetLowering::isTruncateFree(EVT FromVT, EVT ToVT) const {
543 if (!FromVT.isInteger() || !ToVT.isInteger())
545 unsigned FromBits = FromVT.getSizeInBits();
546 unsigned ToBits = ToVT.getSizeInBits();
547 return FromBits > ToBits;
550 //===----------------------------------------------------------------------===//
551 // Inline asm support
552 //===----------------------------------------------------------------------===//
554 TargetLowering::ConstraintType
555 SystemZTargetLowering::getConstraintType(StringRef Constraint) const {
556 if (Constraint.size() == 1) {
557 switch (Constraint[0]) {
558 case 'a': // Address register
559 case 'd': // Data register (equivalent to 'r')
560 case 'f': // Floating-point register
561 case 'h': // High-part register
562 case 'r': // General-purpose register
563 return C_RegisterClass;
565 case 'Q': // Memory with base and unsigned 12-bit displacement
566 case 'R': // Likewise, plus an index
567 case 'S': // Memory with base and signed 20-bit displacement
568 case 'T': // Likewise, plus an index
569 case 'm': // Equivalent to 'T'.
572 case 'I': // Unsigned 8-bit constant
573 case 'J': // Unsigned 12-bit constant
574 case 'K': // Signed 16-bit constant
575 case 'L': // Signed 20-bit displacement (on all targets we support)
576 case 'M': // 0x7fffffff
583 return TargetLowering::getConstraintType(Constraint);
586 TargetLowering::ConstraintWeight SystemZTargetLowering::
587 getSingleConstraintMatchWeight(AsmOperandInfo &info,
588 const char *constraint) const {
589 ConstraintWeight weight = CW_Invalid;
590 Value *CallOperandVal = info.CallOperandVal;
591 // If we don't have a value, we can't do a match,
592 // but allow it at the lowest weight.
595 Type *type = CallOperandVal->getType();
596 // Look at the constraint type.
597 switch (*constraint) {
599 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
602 case 'a': // Address register
603 case 'd': // Data register (equivalent to 'r')
604 case 'h': // High-part register
605 case 'r': // General-purpose register
606 if (CallOperandVal->getType()->isIntegerTy())
607 weight = CW_Register;
610 case 'f': // Floating-point register
611 if (type->isFloatingPointTy())
612 weight = CW_Register;
615 case 'I': // Unsigned 8-bit constant
616 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
617 if (isUInt<8>(C->getZExtValue()))
618 weight = CW_Constant;
621 case 'J': // Unsigned 12-bit constant
622 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
623 if (isUInt<12>(C->getZExtValue()))
624 weight = CW_Constant;
627 case 'K': // Signed 16-bit constant
628 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
629 if (isInt<16>(C->getSExtValue()))
630 weight = CW_Constant;
633 case 'L': // Signed 20-bit displacement (on all targets we support)
634 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
635 if (isInt<20>(C->getSExtValue()))
636 weight = CW_Constant;
639 case 'M': // 0x7fffffff
640 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
641 if (C->getZExtValue() == 0x7fffffff)
642 weight = CW_Constant;
648 // Parse a "{tNNN}" register constraint for which the register type "t"
649 // has already been verified. MC is the class associated with "t" and
650 // Map maps 0-based register numbers to LLVM register numbers.
651 static std::pair<unsigned, const TargetRegisterClass *>
652 parseRegisterNumber(StringRef Constraint, const TargetRegisterClass *RC,
653 const unsigned *Map) {
654 assert(*(Constraint.end()-1) == '}' && "Missing '}'");
655 if (isdigit(Constraint[2])) {
658 Constraint.slice(2, Constraint.size() - 1).getAsInteger(10, Index);
659 if (!Failed && Index < 16 && Map[Index])
660 return std::make_pair(Map[Index], RC);
662 return std::make_pair(0U, nullptr);
665 std::pair<unsigned, const TargetRegisterClass *>
666 SystemZTargetLowering::getRegForInlineAsmConstraint(
667 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
668 if (Constraint.size() == 1) {
669 // GCC Constraint Letters
670 switch (Constraint[0]) {
672 case 'd': // Data register (equivalent to 'r')
673 case 'r': // General-purpose register
675 return std::make_pair(0U, &SystemZ::GR64BitRegClass);
676 else if (VT == MVT::i128)
677 return std::make_pair(0U, &SystemZ::GR128BitRegClass);
678 return std::make_pair(0U, &SystemZ::GR32BitRegClass);
680 case 'a': // Address register
682 return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
683 else if (VT == MVT::i128)
684 return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
685 return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
687 case 'h': // High-part register (an LLVM extension)
688 return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
690 case 'f': // Floating-point register
692 return std::make_pair(0U, &SystemZ::FP64BitRegClass);
693 else if (VT == MVT::f128)
694 return std::make_pair(0U, &SystemZ::FP128BitRegClass);
695 return std::make_pair(0U, &SystemZ::FP32BitRegClass);
698 if (Constraint.size() > 0 && Constraint[0] == '{') {
699 // We need to override the default register parsing for GPRs and FPRs
700 // because the interpretation depends on VT. The internal names of
701 // the registers are also different from the external names
702 // (F0D and F0S instead of F0, etc.).
703 if (Constraint[1] == 'r') {
705 return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
706 SystemZMC::GR32Regs);
708 return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
709 SystemZMC::GR128Regs);
710 return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
711 SystemZMC::GR64Regs);
713 if (Constraint[1] == 'f') {
715 return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
716 SystemZMC::FP32Regs);
718 return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
719 SystemZMC::FP128Regs);
720 return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
721 SystemZMC::FP64Regs);
724 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
727 void SystemZTargetLowering::
728 LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
729 std::vector<SDValue> &Ops,
730 SelectionDAG &DAG) const {
731 // Only support length 1 constraints for now.
732 if (Constraint.length() == 1) {
733 switch (Constraint[0]) {
734 case 'I': // Unsigned 8-bit constant
735 if (auto *C = dyn_cast<ConstantSDNode>(Op))
736 if (isUInt<8>(C->getZExtValue()))
737 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
741 case 'J': // Unsigned 12-bit constant
742 if (auto *C = dyn_cast<ConstantSDNode>(Op))
743 if (isUInt<12>(C->getZExtValue()))
744 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
748 case 'K': // Signed 16-bit constant
749 if (auto *C = dyn_cast<ConstantSDNode>(Op))
750 if (isInt<16>(C->getSExtValue()))
751 Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
755 case 'L': // Signed 20-bit displacement (on all targets we support)
756 if (auto *C = dyn_cast<ConstantSDNode>(Op))
757 if (isInt<20>(C->getSExtValue()))
758 Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
762 case 'M': // 0x7fffffff
763 if (auto *C = dyn_cast<ConstantSDNode>(Op))
764 if (C->getZExtValue() == 0x7fffffff)
765 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
770 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
773 //===----------------------------------------------------------------------===//
774 // Calling conventions
775 //===----------------------------------------------------------------------===//
777 #include "SystemZGenCallingConv.inc"
779 bool SystemZTargetLowering::allowTruncateForTailCall(Type *FromType,
780 Type *ToType) const {
781 return isTruncateFree(FromType, ToType);
784 bool SystemZTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
785 return CI->isTailCall();
788 // We do not yet support 128-bit single-element vector types. If the user
789 // attempts to use such types as function argument or return type, prefer
790 // to error out instead of emitting code violating the ABI.
791 static void VerifyVectorType(MVT VT, EVT ArgVT) {
792 if (ArgVT.isVector() && !VT.isVector())
793 report_fatal_error("Unsupported vector argument or return type");
796 static void VerifyVectorTypes(const SmallVectorImpl<ISD::InputArg> &Ins) {
797 for (unsigned i = 0; i < Ins.size(); ++i)
798 VerifyVectorType(Ins[i].VT, Ins[i].ArgVT);
801 static void VerifyVectorTypes(const SmallVectorImpl<ISD::OutputArg> &Outs) {
802 for (unsigned i = 0; i < Outs.size(); ++i)
803 VerifyVectorType(Outs[i].VT, Outs[i].ArgVT);
806 // Value is a value that has been passed to us in the location described by VA
807 // (and so has type VA.getLocVT()). Convert Value to VA.getValVT(), chaining
808 // any loads onto Chain.
809 static SDValue convertLocVTToValVT(SelectionDAG &DAG, const SDLoc &DL,
810 CCValAssign &VA, SDValue Chain,
812 // If the argument has been promoted from a smaller type, insert an
813 // assertion to capture this.
814 if (VA.getLocInfo() == CCValAssign::SExt)
815 Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value,
816 DAG.getValueType(VA.getValVT()));
817 else if (VA.getLocInfo() == CCValAssign::ZExt)
818 Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value,
819 DAG.getValueType(VA.getValVT()));
822 Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
823 else if (VA.getLocInfo() == CCValAssign::BCvt) {
824 // If this is a short vector argument loaded from the stack,
825 // extend from i64 to full vector size and then bitcast.
826 assert(VA.getLocVT() == MVT::i64);
827 assert(VA.getValVT().isVector());
828 Value = DAG.getBuildVector(MVT::v2i64, DL, {Value, DAG.getUNDEF(MVT::i64)});
829 Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
831 assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
835 // Value is a value of type VA.getValVT() that we need to copy into
836 // the location described by VA. Return a copy of Value converted to
837 // VA.getValVT(). The caller is responsible for handling indirect values.
838 static SDValue convertValVTToLocVT(SelectionDAG &DAG, const SDLoc &DL,
839 CCValAssign &VA, SDValue Value) {
840 switch (VA.getLocInfo()) {
841 case CCValAssign::SExt:
842 return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
843 case CCValAssign::ZExt:
844 return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
845 case CCValAssign::AExt:
846 return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
847 case CCValAssign::BCvt:
848 // If this is a short vector argument to be stored to the stack,
849 // bitcast to v2i64 and then extract first element.
850 assert(VA.getLocVT() == MVT::i64);
851 assert(VA.getValVT().isVector());
852 Value = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Value);
853 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
854 DAG.getConstant(0, DL, MVT::i32));
855 case CCValAssign::Full:
858 llvm_unreachable("Unhandled getLocInfo()");
862 SDValue SystemZTargetLowering::LowerFormalArguments(
863 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
864 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
865 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
866 MachineFunction &MF = DAG.getMachineFunction();
867 MachineFrameInfo *MFI = MF.getFrameInfo();
868 MachineRegisterInfo &MRI = MF.getRegInfo();
869 SystemZMachineFunctionInfo *FuncInfo =
870 MF.getInfo<SystemZMachineFunctionInfo>();
872 static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering());
873 EVT PtrVT = getPointerTy(DAG.getDataLayout());
875 // Detect unsupported vector argument types.
876 if (Subtarget.hasVector())
877 VerifyVectorTypes(Ins);
879 // Assign locations to all of the incoming arguments.
880 SmallVector<CCValAssign, 16> ArgLocs;
881 SystemZCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
882 CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
884 unsigned NumFixedGPRs = 0;
885 unsigned NumFixedFPRs = 0;
886 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
888 CCValAssign &VA = ArgLocs[I];
889 EVT LocVT = VA.getLocVT();
891 // Arguments passed in registers
892 const TargetRegisterClass *RC;
893 switch (LocVT.getSimpleVT().SimpleTy) {
895 // Integers smaller than i64 should be promoted to i64.
896 llvm_unreachable("Unexpected argument type");
899 RC = &SystemZ::GR32BitRegClass;
903 RC = &SystemZ::GR64BitRegClass;
907 RC = &SystemZ::FP32BitRegClass;
911 RC = &SystemZ::FP64BitRegClass;
919 RC = &SystemZ::VR128BitRegClass;
923 unsigned VReg = MRI.createVirtualRegister(RC);
924 MRI.addLiveIn(VA.getLocReg(), VReg);
925 ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
927 assert(VA.isMemLoc() && "Argument not register or memory");
929 // Create the frame index object for this incoming parameter.
930 int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
931 VA.getLocMemOffset(), true);
933 // Create the SelectionDAG nodes corresponding to a load
934 // from this parameter. Unpromoted ints and floats are
935 // passed as right-justified 8-byte values.
936 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
937 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
938 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
939 DAG.getIntPtrConstant(4, DL));
940 ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
941 MachinePointerInfo::getFixedStack(MF, FI));
944 // Convert the value of the argument register into the value that's
946 if (VA.getLocInfo() == CCValAssign::Indirect) {
947 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
948 MachinePointerInfo()));
949 // If the original argument was split (e.g. i128), we need
950 // to load all parts of it here (using the same address).
951 unsigned ArgIndex = Ins[I].OrigArgIndex;
952 assert (Ins[I].PartOffset == 0);
953 while (I + 1 != E && Ins[I + 1].OrigArgIndex == ArgIndex) {
954 CCValAssign &PartVA = ArgLocs[I + 1];
955 unsigned PartOffset = Ins[I + 1].PartOffset;
956 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
957 DAG.getIntPtrConstant(PartOffset, DL));
958 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
959 MachinePointerInfo()));
963 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
967 // Save the number of non-varargs registers for later use by va_start, etc.
968 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
969 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
971 // Likewise the address (in the form of a frame index) of where the
972 // first stack vararg would be. The 1-byte size here is arbitrary.
973 int64_t StackSize = CCInfo.getNextStackOffset();
974 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize, true));
976 // ...and a similar frame index for the caller-allocated save area
977 // that will be used to store the incoming registers.
978 int64_t RegSaveOffset = TFL->getOffsetOfLocalArea();
979 unsigned RegSaveIndex = MFI->CreateFixedObject(1, RegSaveOffset, true);
980 FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
982 // Store the FPR varargs in the reserved frame slots. (We store the
983 // GPRs as part of the prologue.)
984 if (NumFixedFPRs < SystemZ::NumArgFPRs) {
985 SDValue MemOps[SystemZ::NumArgFPRs];
986 for (unsigned I = NumFixedFPRs; I < SystemZ::NumArgFPRs; ++I) {
987 unsigned Offset = TFL->getRegSpillOffset(SystemZ::ArgFPRs[I]);
988 int FI = MFI->CreateFixedObject(8, RegSaveOffset + Offset, true);
989 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
990 unsigned VReg = MF.addLiveIn(SystemZ::ArgFPRs[I],
991 &SystemZ::FP64BitRegClass);
992 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
993 MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
994 MachinePointerInfo::getFixedStack(MF, FI));
996 // Join the stores, which are independent of one another.
997 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
998 makeArrayRef(&MemOps[NumFixedFPRs],
999 SystemZ::NumArgFPRs-NumFixedFPRs));
1006 static bool canUseSiblingCall(const CCState &ArgCCInfo,
1007 SmallVectorImpl<CCValAssign> &ArgLocs,
1008 SmallVectorImpl<ISD::OutputArg> &Outs) {
1009 // Punt if there are any indirect or stack arguments, or if the call
1010 // needs the callee-saved argument register R6, or if the call uses
1011 // the callee-saved register arguments SwiftSelf and SwiftError.
1012 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1013 CCValAssign &VA = ArgLocs[I];
1014 if (VA.getLocInfo() == CCValAssign::Indirect)
1018 unsigned Reg = VA.getLocReg();
1019 if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
1021 if (Outs[I].Flags.isSwiftSelf() || Outs[I].Flags.isSwiftError())
1028 SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI,
1029 SmallVectorImpl<SDValue> &InVals) const {
1030 SelectionDAG &DAG = CLI.DAG;
1032 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1033 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1034 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1035 SDValue Chain = CLI.Chain;
1036 SDValue Callee = CLI.Callee;
1037 bool &IsTailCall = CLI.IsTailCall;
1038 CallingConv::ID CallConv = CLI.CallConv;
1039 bool IsVarArg = CLI.IsVarArg;
1040 MachineFunction &MF = DAG.getMachineFunction();
1041 EVT PtrVT = getPointerTy(MF.getDataLayout());
1043 // Detect unsupported vector argument and return types.
1044 if (Subtarget.hasVector()) {
1045 VerifyVectorTypes(Outs);
1046 VerifyVectorTypes(Ins);
1049 // Analyze the operands of the call, assigning locations to each operand.
1050 SmallVector<CCValAssign, 16> ArgLocs;
1051 SystemZCCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1052 ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
1054 // We don't support GuaranteedTailCallOpt, only automatically-detected
1056 if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs, Outs))
1059 // Get a count of how many bytes are to be pushed on the stack.
1060 unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1062 // Mark the start of the call.
1064 Chain = DAG.getCALLSEQ_START(Chain,
1065 DAG.getConstant(NumBytes, DL, PtrVT, true),
1068 // Copy argument values to their designated locations.
1069 SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass;
1070 SmallVector<SDValue, 8> MemOpChains;
1072 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1073 CCValAssign &VA = ArgLocs[I];
1074 SDValue ArgValue = OutVals[I];
1076 if (VA.getLocInfo() == CCValAssign::Indirect) {
1077 // Store the argument in a stack slot and pass its address.
1078 SDValue SpillSlot = DAG.CreateStackTemporary(Outs[I].ArgVT);
1079 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1080 MemOpChains.push_back(
1081 DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1082 MachinePointerInfo::getFixedStack(MF, FI)));
1083 // If the original argument was split (e.g. i128), we need
1084 // to store all parts of it here (and pass just one address).
1085 unsigned ArgIndex = Outs[I].OrigArgIndex;
1086 assert (Outs[I].PartOffset == 0);
1087 while (I + 1 != E && Outs[I + 1].OrigArgIndex == ArgIndex) {
1088 SDValue PartValue = OutVals[I + 1];
1089 unsigned PartOffset = Outs[I + 1].PartOffset;
1090 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
1091 DAG.getIntPtrConstant(PartOffset, DL));
1092 MemOpChains.push_back(
1093 DAG.getStore(Chain, DL, PartValue, Address,
1094 MachinePointerInfo::getFixedStack(MF, FI)));
1097 ArgValue = SpillSlot;
1099 ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
1102 // Queue up the argument copies and emit them at the end.
1103 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1105 assert(VA.isMemLoc() && "Argument not register or memory");
1107 // Work out the address of the stack slot. Unpromoted ints and
1108 // floats are passed as right-justified 8-byte values.
1109 if (!StackPtr.getNode())
1110 StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT);
1111 unsigned Offset = SystemZMC::CallFrameSize + VA.getLocMemOffset();
1112 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1114 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1115 DAG.getIntPtrConstant(Offset, DL));
1118 MemOpChains.push_back(
1119 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
1123 // Join the stores, which are independent of one another.
1124 if (!MemOpChains.empty())
1125 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1127 // Accept direct calls by converting symbolic call addresses to the
1128 // associated Target* opcodes. Force %r1 to be used for indirect
1131 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1132 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
1133 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1134 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1135 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
1136 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1137 } else if (IsTailCall) {
1138 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
1139 Glue = Chain.getValue(1);
1140 Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
1143 // Build a sequence of copy-to-reg nodes, chained and glued together.
1144 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
1145 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
1146 RegsToPass[I].second, Glue);
1147 Glue = Chain.getValue(1);
1150 // The first call operand is the chain and the second is the target address.
1151 SmallVector<SDValue, 8> Ops;
1152 Ops.push_back(Chain);
1153 Ops.push_back(Callee);
1155 // Add argument registers to the end of the list so that they are
1156 // known live into the call.
1157 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
1158 Ops.push_back(DAG.getRegister(RegsToPass[I].first,
1159 RegsToPass[I].second.getValueType()));
1161 // Add a register mask operand representing the call-preserved registers.
1162 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1163 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1164 assert(Mask && "Missing call preserved mask for calling convention");
1165 Ops.push_back(DAG.getRegisterMask(Mask));
1167 // Glue the call to the argument copies, if any.
1169 Ops.push_back(Glue);
1172 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1174 return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
1175 Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
1176 Glue = Chain.getValue(1);
1178 // Mark the end of the call, which is glued to the call itself.
1179 Chain = DAG.getCALLSEQ_END(Chain,
1180 DAG.getConstant(NumBytes, DL, PtrVT, true),
1181 DAG.getConstant(0, DL, PtrVT, true),
1183 Glue = Chain.getValue(1);
1185 // Assign locations to each value returned by this call.
1186 SmallVector<CCValAssign, 16> RetLocs;
1187 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1188 RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
1190 // Copy all of the result registers out of their specified physreg.
1191 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1192 CCValAssign &VA = RetLocs[I];
1194 // Copy the value out, gluing the copy to the end of the call sequence.
1195 SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
1196 VA.getLocVT(), Glue);
1197 Chain = RetValue.getValue(1);
1198 Glue = RetValue.getValue(2);
1200 // Convert the value of the return register into the value that's
1202 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
1208 bool SystemZTargetLowering::
1209 CanLowerReturn(CallingConv::ID CallConv,
1210 MachineFunction &MF, bool isVarArg,
1211 const SmallVectorImpl<ISD::OutputArg> &Outs,
1212 LLVMContext &Context) const {
1213 // Detect unsupported vector return types.
1214 if (Subtarget.hasVector())
1215 VerifyVectorTypes(Outs);
1217 // Special case that we cannot easily detect in RetCC_SystemZ since
1218 // i128 is not a legal type.
1219 for (auto &Out : Outs)
1220 if (Out.ArgVT == MVT::i128)
1223 SmallVector<CCValAssign, 16> RetLocs;
1224 CCState RetCCInfo(CallConv, isVarArg, MF, RetLocs, Context);
1225 return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ);
1229 SystemZTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1231 const SmallVectorImpl<ISD::OutputArg> &Outs,
1232 const SmallVectorImpl<SDValue> &OutVals,
1233 const SDLoc &DL, SelectionDAG &DAG) const {
1234 MachineFunction &MF = DAG.getMachineFunction();
1236 // Detect unsupported vector return types.
1237 if (Subtarget.hasVector())
1238 VerifyVectorTypes(Outs);
1240 // Assign locations to each returned value.
1241 SmallVector<CCValAssign, 16> RetLocs;
1242 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1243 RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
1245 // Quick exit for void returns
1246 if (RetLocs.empty())
1247 return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
1249 // Copy the result values into the output registers.
1251 SmallVector<SDValue, 4> RetOps;
1252 RetOps.push_back(Chain);
1253 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1254 CCValAssign &VA = RetLocs[I];
1255 SDValue RetValue = OutVals[I];
1257 // Make the return register live on exit.
1258 assert(VA.isRegLoc() && "Can only return in registers!");
1260 // Promote the value as required.
1261 RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
1263 // Chain and glue the copies together.
1264 unsigned Reg = VA.getLocReg();
1265 Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
1266 Glue = Chain.getValue(1);
1267 RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
1270 // Update chain and glue.
1273 RetOps.push_back(Glue);
1275 return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, RetOps);
1278 SDValue SystemZTargetLowering::prepareVolatileOrAtomicLoad(
1279 SDValue Chain, const SDLoc &DL, SelectionDAG &DAG) const {
1280 return DAG.getNode(SystemZISD::SERIALIZE, DL, MVT::Other, Chain);
1283 // Return true if Op is an intrinsic node with chain that returns the CC value
1284 // as its only (other) argument. Provide the associated SystemZISD opcode and
1285 // the mask of valid CC values if so.
1286 static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
1287 unsigned &CCValid) {
1288 unsigned Id = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1290 case Intrinsic::s390_tbegin:
1291 Opcode = SystemZISD::TBEGIN;
1292 CCValid = SystemZ::CCMASK_TBEGIN;
1295 case Intrinsic::s390_tbegin_nofloat:
1296 Opcode = SystemZISD::TBEGIN_NOFLOAT;
1297 CCValid = SystemZ::CCMASK_TBEGIN;
1300 case Intrinsic::s390_tend:
1301 Opcode = SystemZISD::TEND;
1302 CCValid = SystemZ::CCMASK_TEND;
1310 // Return true if Op is an intrinsic node without chain that returns the
1311 // CC value as its final argument. Provide the associated SystemZISD
1312 // opcode and the mask of valid CC values if so.
1313 static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) {
1314 unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1316 case Intrinsic::s390_vpkshs:
1317 case Intrinsic::s390_vpksfs:
1318 case Intrinsic::s390_vpksgs:
1319 Opcode = SystemZISD::PACKS_CC;
1320 CCValid = SystemZ::CCMASK_VCMP;
1323 case Intrinsic::s390_vpklshs:
1324 case Intrinsic::s390_vpklsfs:
1325 case Intrinsic::s390_vpklsgs:
1326 Opcode = SystemZISD::PACKLS_CC;
1327 CCValid = SystemZ::CCMASK_VCMP;
1330 case Intrinsic::s390_vceqbs:
1331 case Intrinsic::s390_vceqhs:
1332 case Intrinsic::s390_vceqfs:
1333 case Intrinsic::s390_vceqgs:
1334 Opcode = SystemZISD::VICMPES;
1335 CCValid = SystemZ::CCMASK_VCMP;
1338 case Intrinsic::s390_vchbs:
1339 case Intrinsic::s390_vchhs:
1340 case Intrinsic::s390_vchfs:
1341 case Intrinsic::s390_vchgs:
1342 Opcode = SystemZISD::VICMPHS;
1343 CCValid = SystemZ::CCMASK_VCMP;
1346 case Intrinsic::s390_vchlbs:
1347 case Intrinsic::s390_vchlhs:
1348 case Intrinsic::s390_vchlfs:
1349 case Intrinsic::s390_vchlgs:
1350 Opcode = SystemZISD::VICMPHLS;
1351 CCValid = SystemZ::CCMASK_VCMP;
1354 case Intrinsic::s390_vtm:
1355 Opcode = SystemZISD::VTM;
1356 CCValid = SystemZ::CCMASK_VCMP;
1359 case Intrinsic::s390_vfaebs:
1360 case Intrinsic::s390_vfaehs:
1361 case Intrinsic::s390_vfaefs:
1362 Opcode = SystemZISD::VFAE_CC;
1363 CCValid = SystemZ::CCMASK_ANY;
1366 case Intrinsic::s390_vfaezbs:
1367 case Intrinsic::s390_vfaezhs:
1368 case Intrinsic::s390_vfaezfs:
1369 Opcode = SystemZISD::VFAEZ_CC;
1370 CCValid = SystemZ::CCMASK_ANY;
1373 case Intrinsic::s390_vfeebs:
1374 case Intrinsic::s390_vfeehs:
1375 case Intrinsic::s390_vfeefs:
1376 Opcode = SystemZISD::VFEE_CC;
1377 CCValid = SystemZ::CCMASK_ANY;
1380 case Intrinsic::s390_vfeezbs:
1381 case Intrinsic::s390_vfeezhs:
1382 case Intrinsic::s390_vfeezfs:
1383 Opcode = SystemZISD::VFEEZ_CC;
1384 CCValid = SystemZ::CCMASK_ANY;
1387 case Intrinsic::s390_vfenebs:
1388 case Intrinsic::s390_vfenehs:
1389 case Intrinsic::s390_vfenefs:
1390 Opcode = SystemZISD::VFENE_CC;
1391 CCValid = SystemZ::CCMASK_ANY;
1394 case Intrinsic::s390_vfenezbs:
1395 case Intrinsic::s390_vfenezhs:
1396 case Intrinsic::s390_vfenezfs:
1397 Opcode = SystemZISD::VFENEZ_CC;
1398 CCValid = SystemZ::CCMASK_ANY;
1401 case Intrinsic::s390_vistrbs:
1402 case Intrinsic::s390_vistrhs:
1403 case Intrinsic::s390_vistrfs:
1404 Opcode = SystemZISD::VISTR_CC;
1405 CCValid = SystemZ::CCMASK_0 | SystemZ::CCMASK_3;
1408 case Intrinsic::s390_vstrcbs:
1409 case Intrinsic::s390_vstrchs:
1410 case Intrinsic::s390_vstrcfs:
1411 Opcode = SystemZISD::VSTRC_CC;
1412 CCValid = SystemZ::CCMASK_ANY;
1415 case Intrinsic::s390_vstrczbs:
1416 case Intrinsic::s390_vstrczhs:
1417 case Intrinsic::s390_vstrczfs:
1418 Opcode = SystemZISD::VSTRCZ_CC;
1419 CCValid = SystemZ::CCMASK_ANY;
1422 case Intrinsic::s390_vfcedbs:
1423 Opcode = SystemZISD::VFCMPES;
1424 CCValid = SystemZ::CCMASK_VCMP;
1427 case Intrinsic::s390_vfchdbs:
1428 Opcode = SystemZISD::VFCMPHS;
1429 CCValid = SystemZ::CCMASK_VCMP;
1432 case Intrinsic::s390_vfchedbs:
1433 Opcode = SystemZISD::VFCMPHES;
1434 CCValid = SystemZ::CCMASK_VCMP;
1437 case Intrinsic::s390_vftcidb:
1438 Opcode = SystemZISD::VFTCI;
1439 CCValid = SystemZ::CCMASK_VCMP;
1442 case Intrinsic::s390_tdc:
1443 Opcode = SystemZISD::TDC;
1444 CCValid = SystemZ::CCMASK_TDC;
1452 // Emit an intrinsic with chain with a glued value instead of its CC result.
1453 static SDValue emitIntrinsicWithChainAndGlue(SelectionDAG &DAG, SDValue Op,
1455 // Copy all operands except the intrinsic ID.
1456 unsigned NumOps = Op.getNumOperands();
1457 SmallVector<SDValue, 6> Ops;
1458 Ops.reserve(NumOps - 1);
1459 Ops.push_back(Op.getOperand(0));
1460 for (unsigned I = 2; I < NumOps; ++I)
1461 Ops.push_back(Op.getOperand(I));
1463 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
1464 SDVTList RawVTs = DAG.getVTList(MVT::Other, MVT::Glue);
1465 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
1466 SDValue OldChain = SDValue(Op.getNode(), 1);
1467 SDValue NewChain = SDValue(Intr.getNode(), 0);
1468 DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
1472 // Emit an intrinsic with a glued value instead of its CC result.
1473 static SDValue emitIntrinsicWithGlue(SelectionDAG &DAG, SDValue Op,
1475 // Copy all operands except the intrinsic ID.
1476 unsigned NumOps = Op.getNumOperands();
1477 SmallVector<SDValue, 6> Ops;
1478 Ops.reserve(NumOps - 1);
1479 for (unsigned I = 1; I < NumOps; ++I)
1480 Ops.push_back(Op.getOperand(I));
1482 if (Op->getNumValues() == 1)
1483 return DAG.getNode(Opcode, SDLoc(Op), MVT::Glue, Ops);
1484 assert(Op->getNumValues() == 2 && "Expected exactly one non-CC result");
1485 SDVTList RawVTs = DAG.getVTList(Op->getValueType(0), MVT::Glue);
1486 return DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
1489 // CC is a comparison that will be implemented using an integer or
1490 // floating-point comparison. Return the condition code mask for
1491 // a branch on true. In the integer case, CCMASK_CMP_UO is set for
1492 // unsigned comparisons and clear for signed ones. In the floating-point
1493 // case, CCMASK_CMP_UO has its normal mask meaning (unordered).
1494 static unsigned CCMaskForCondCode(ISD::CondCode CC) {
1496 case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
1497 case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
1498 case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
1502 llvm_unreachable("Invalid integer condition!");
1511 case ISD::SETO: return SystemZ::CCMASK_CMP_O;
1512 case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
1517 // Return a sequence for getting a 1 from an IPM result when CC has a
1518 // value in CCMask and a 0 when CC has a value in CCValid & ~CCMask.
1519 // The handling of CC values outside CCValid doesn't matter.
1520 static IPMConversion getIPMConversion(unsigned CCValid, unsigned CCMask) {
1521 // Deal with cases where the result can be taken directly from a bit
1522 // of the IPM result.
1523 if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_3)))
1524 return IPMConversion(0, 0, SystemZ::IPM_CC);
1525 if (CCMask == (CCValid & (SystemZ::CCMASK_2 | SystemZ::CCMASK_3)))
1526 return IPMConversion(0, 0, SystemZ::IPM_CC + 1);
1528 // Deal with cases where we can add a value to force the sign bit
1529 // to contain the right value. Putting the bit in 31 means we can
1530 // use SRL rather than RISBG(L), and also makes it easier to get a
1531 // 0/-1 value, so it has priority over the other tests below.
1533 // These sequences rely on the fact that the upper two bits of the
1534 // IPM result are zero.
1535 uint64_t TopBit = uint64_t(1) << 31;
1536 if (CCMask == (CCValid & SystemZ::CCMASK_0))
1537 return IPMConversion(0, -(1 << SystemZ::IPM_CC), 31);
1538 if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_1)))
1539 return IPMConversion(0, -(2 << SystemZ::IPM_CC), 31);
1540 if (CCMask == (CCValid & (SystemZ::CCMASK_0
1542 | SystemZ::CCMASK_2)))
1543 return IPMConversion(0, -(3 << SystemZ::IPM_CC), 31);
1544 if (CCMask == (CCValid & SystemZ::CCMASK_3))
1545 return IPMConversion(0, TopBit - (3 << SystemZ::IPM_CC), 31);
1546 if (CCMask == (CCValid & (SystemZ::CCMASK_1
1548 | SystemZ::CCMASK_3)))
1549 return IPMConversion(0, TopBit - (1 << SystemZ::IPM_CC), 31);
1551 // Next try inverting the value and testing a bit. 0/1 could be
1552 // handled this way too, but we dealt with that case above.
1553 if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_2)))
1554 return IPMConversion(-1, 0, SystemZ::IPM_CC);
1556 // Handle cases where adding a value forces a non-sign bit to contain
1558 if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_2)))
1559 return IPMConversion(0, 1 << SystemZ::IPM_CC, SystemZ::IPM_CC + 1);
1560 if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_3)))
1561 return IPMConversion(0, -(1 << SystemZ::IPM_CC), SystemZ::IPM_CC + 1);
1563 // The remaining cases are 1, 2, 0/1/3 and 0/2/3. All these are
1564 // can be done by inverting the low CC bit and applying one of the
1565 // sign-based extractions above.
1566 if (CCMask == (CCValid & SystemZ::CCMASK_1))
1567 return IPMConversion(1 << SystemZ::IPM_CC, -(1 << SystemZ::IPM_CC), 31);
1568 if (CCMask == (CCValid & SystemZ::CCMASK_2))
1569 return IPMConversion(1 << SystemZ::IPM_CC,
1570 TopBit - (3 << SystemZ::IPM_CC), 31);
1571 if (CCMask == (CCValid & (SystemZ::CCMASK_0
1573 | SystemZ::CCMASK_3)))
1574 return IPMConversion(1 << SystemZ::IPM_CC, -(3 << SystemZ::IPM_CC), 31);
1575 if (CCMask == (CCValid & (SystemZ::CCMASK_0
1577 | SystemZ::CCMASK_3)))
1578 return IPMConversion(1 << SystemZ::IPM_CC,
1579 TopBit - (1 << SystemZ::IPM_CC), 31);
1581 llvm_unreachable("Unexpected CC combination");
1584 // If C can be converted to a comparison against zero, adjust the operands
1586 static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
1587 if (C.ICmpType == SystemZICMP::UnsignedOnly)
1590 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
1594 int64_t Value = ConstOp1->getSExtValue();
1595 if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
1596 (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
1597 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
1598 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
1599 C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
1600 C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
1604 // If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
1605 // adjust the operands as necessary.
1606 static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL,
1608 // For us to make any changes, it must a comparison between a single-use
1609 // load and a constant.
1610 if (!C.Op0.hasOneUse() ||
1611 C.Op0.getOpcode() != ISD::LOAD ||
1612 C.Op1.getOpcode() != ISD::Constant)
1615 // We must have an 8- or 16-bit load.
1616 auto *Load = cast<LoadSDNode>(C.Op0);
1617 unsigned NumBits = Load->getMemoryVT().getStoreSizeInBits();
1618 if (NumBits != 8 && NumBits != 16)
1621 // The load must be an extending one and the constant must be within the
1622 // range of the unextended value.
1623 auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
1624 uint64_t Value = ConstOp1->getZExtValue();
1625 uint64_t Mask = (1 << NumBits) - 1;
1626 if (Load->getExtensionType() == ISD::SEXTLOAD) {
1627 // Make sure that ConstOp1 is in range of C.Op0.
1628 int64_t SignedValue = ConstOp1->getSExtValue();
1629 if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
1631 if (C.ICmpType != SystemZICMP::SignedOnly) {
1632 // Unsigned comparison between two sign-extended values is equivalent
1633 // to unsigned comparison between two zero-extended values.
1635 } else if (NumBits == 8) {
1636 // Try to treat the comparison as unsigned, so that we can use CLI.
1637 // Adjust CCMask and Value as necessary.
1638 if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
1639 // Test whether the high bit of the byte is set.
1640 Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
1641 else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
1642 // Test whether the high bit of the byte is clear.
1643 Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
1645 // No instruction exists for this combination.
1647 C.ICmpType = SystemZICMP::UnsignedOnly;
1649 } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
1652 // If the constant is in range, we can use any comparison.
1653 C.ICmpType = SystemZICMP::Any;
1657 // Make sure that the first operand is an i32 of the right extension type.
1658 ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
1661 if (C.Op0.getValueType() != MVT::i32 ||
1662 Load->getExtensionType() != ExtType)
1663 C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32, Load->getChain(),
1664 Load->getBasePtr(), Load->getPointerInfo(),
1665 Load->getMemoryVT(), Load->getAlignment(),
1666 Load->getMemOperand()->getFlags());
1668 // Make sure that the second operand is an i32 with the right value.
1669 if (C.Op1.getValueType() != MVT::i32 ||
1670 Value != ConstOp1->getZExtValue())
1671 C.Op1 = DAG.getConstant(Value, DL, MVT::i32);
1674 // Return true if Op is either an unextended load, or a load suitable
1675 // for integer register-memory comparisons of type ICmpType.
1676 static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
1677 auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
1679 // There are no instructions to compare a register with a memory byte.
1680 if (Load->getMemoryVT() == MVT::i8)
1682 // Otherwise decide on extension type.
1683 switch (Load->getExtensionType()) {
1684 case ISD::NON_EXTLOAD:
1687 return ICmpType != SystemZICMP::UnsignedOnly;
1689 return ICmpType != SystemZICMP::SignedOnly;
1697 // Return true if it is better to swap the operands of C.
1698 static bool shouldSwapCmpOperands(const Comparison &C) {
1699 // Leave f128 comparisons alone, since they have no memory forms.
1700 if (C.Op0.getValueType() == MVT::f128)
1703 // Always keep a floating-point constant second, since comparisons with
1704 // zero can use LOAD TEST and comparisons with other constants make a
1705 // natural memory operand.
1706 if (isa<ConstantFPSDNode>(C.Op1))
1709 // Never swap comparisons with zero since there are many ways to optimize
1711 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
1712 if (ConstOp1 && ConstOp1->getZExtValue() == 0)
1715 // Also keep natural memory operands second if the loaded value is
1716 // only used here. Several comparisons have memory forms.
1717 if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
1720 // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
1721 // In that case we generally prefer the memory to be second.
1722 if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
1723 // The only exceptions are when the second operand is a constant and
1724 // we can use things like CHHSI.
1727 // The unsigned memory-immediate instructions can handle 16-bit
1728 // unsigned integers.
1729 if (C.ICmpType != SystemZICMP::SignedOnly &&
1730 isUInt<16>(ConstOp1->getZExtValue()))
1732 // The signed memory-immediate instructions can handle 16-bit
1734 if (C.ICmpType != SystemZICMP::UnsignedOnly &&
1735 isInt<16>(ConstOp1->getSExtValue()))
1740 // Try to promote the use of CGFR and CLGFR.
1741 unsigned Opcode0 = C.Op0.getOpcode();
1742 if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
1744 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
1746 if (C.ICmpType != SystemZICMP::SignedOnly &&
1747 Opcode0 == ISD::AND &&
1748 C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
1749 cast<ConstantSDNode>(C.Op0.getOperand(1))->getZExtValue() == 0xffffffff)
1755 // Return a version of comparison CC mask CCMask in which the LT and GT
1756 // actions are swapped.
1757 static unsigned reverseCCMask(unsigned CCMask) {
1758 return ((CCMask & SystemZ::CCMASK_CMP_EQ) |
1759 (CCMask & SystemZ::CCMASK_CMP_GT ? SystemZ::CCMASK_CMP_LT : 0) |
1760 (CCMask & SystemZ::CCMASK_CMP_LT ? SystemZ::CCMASK_CMP_GT : 0) |
1761 (CCMask & SystemZ::CCMASK_CMP_UO));
1764 // Check whether C tests for equality between X and Y and whether X - Y
1765 // or Y - X is also computed. In that case it's better to compare the
1766 // result of the subtraction against zero.
1767 static void adjustForSubtraction(SelectionDAG &DAG, const SDLoc &DL,
1769 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
1770 C.CCMask == SystemZ::CCMASK_CMP_NE) {
1771 for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1773 if (N->getOpcode() == ISD::SUB &&
1774 ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
1775 (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
1776 C.Op0 = SDValue(N, 0);
1777 C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
1784 // Check whether C compares a floating-point value with zero and if that
1785 // floating-point value is also negated. In this case we can use the
1786 // negation to set CC, so avoiding separate LOAD AND TEST and
1787 // LOAD (NEGATIVE/COMPLEMENT) instructions.
1788 static void adjustForFNeg(Comparison &C) {
1789 auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
1790 if (C1 && C1->isZero()) {
1791 for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1793 if (N->getOpcode() == ISD::FNEG) {
1794 C.Op0 = SDValue(N, 0);
1795 C.CCMask = reverseCCMask(C.CCMask);
1802 // Check whether C compares (shl X, 32) with 0 and whether X is
1803 // also sign-extended. In that case it is better to test the result
1804 // of the sign extension using LTGFR.
1806 // This case is important because InstCombine transforms a comparison
1807 // with (sext (trunc X)) into a comparison with (shl X, 32).
1808 static void adjustForLTGFR(Comparison &C) {
1809 // Check for a comparison between (shl X, 32) and 0.
1810 if (C.Op0.getOpcode() == ISD::SHL &&
1811 C.Op0.getValueType() == MVT::i64 &&
1812 C.Op1.getOpcode() == ISD::Constant &&
1813 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1814 auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
1815 if (C1 && C1->getZExtValue() == 32) {
1816 SDValue ShlOp0 = C.Op0.getOperand(0);
1817 // See whether X has any SIGN_EXTEND_INREG uses.
1818 for (auto I = ShlOp0->use_begin(), E = ShlOp0->use_end(); I != E; ++I) {
1820 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
1821 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
1822 C.Op0 = SDValue(N, 0);
1830 // If C compares the truncation of an extending load, try to compare
1831 // the untruncated value instead. This exposes more opportunities to
1833 static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL,
1835 if (C.Op0.getOpcode() == ISD::TRUNCATE &&
1836 C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
1837 C.Op1.getOpcode() == ISD::Constant &&
1838 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1839 auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
1840 if (L->getMemoryVT().getStoreSizeInBits()
1841 <= C.Op0.getValueType().getSizeInBits()) {
1842 unsigned Type = L->getExtensionType();
1843 if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
1844 (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
1845 C.Op0 = C.Op0.getOperand(0);
1846 C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
1852 // Return true if shift operation N has an in-range constant shift value.
1853 // Store it in ShiftVal if so.
1854 static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
1855 auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
1859 uint64_t Amount = Shift->getZExtValue();
1860 if (Amount >= N.getValueType().getSizeInBits())
1867 // Check whether an AND with Mask is suitable for a TEST UNDER MASK
1868 // instruction and whether the CC value is descriptive enough to handle
1869 // a comparison of type Opcode between the AND result and CmpVal.
1870 // CCMask says which comparison result is being tested and BitSize is
1871 // the number of bits in the operands. If TEST UNDER MASK can be used,
1872 // return the corresponding CC mask, otherwise return 0.
1873 static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
1874 uint64_t Mask, uint64_t CmpVal,
1875 unsigned ICmpType) {
1876 assert(Mask != 0 && "ANDs with zero should have been removed by now");
1878 // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
1879 if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
1880 !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
1883 // Work out the masks for the lowest and highest bits.
1884 unsigned HighShift = 63 - countLeadingZeros(Mask);
1885 uint64_t High = uint64_t(1) << HighShift;
1886 uint64_t Low = uint64_t(1) << countTrailingZeros(Mask);
1888 // Signed ordered comparisons are effectively unsigned if the sign
1890 bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
1892 // Check for equality comparisons with 0, or the equivalent.
1894 if (CCMask == SystemZ::CCMASK_CMP_EQ)
1895 return SystemZ::CCMASK_TM_ALL_0;
1896 if (CCMask == SystemZ::CCMASK_CMP_NE)
1897 return SystemZ::CCMASK_TM_SOME_1;
1899 if (EffectivelyUnsigned && CmpVal > 0 && CmpVal <= Low) {
1900 if (CCMask == SystemZ::CCMASK_CMP_LT)
1901 return SystemZ::CCMASK_TM_ALL_0;
1902 if (CCMask == SystemZ::CCMASK_CMP_GE)
1903 return SystemZ::CCMASK_TM_SOME_1;
1905 if (EffectivelyUnsigned && CmpVal < Low) {
1906 if (CCMask == SystemZ::CCMASK_CMP_LE)
1907 return SystemZ::CCMASK_TM_ALL_0;
1908 if (CCMask == SystemZ::CCMASK_CMP_GT)
1909 return SystemZ::CCMASK_TM_SOME_1;
1912 // Check for equality comparisons with the mask, or the equivalent.
1913 if (CmpVal == Mask) {
1914 if (CCMask == SystemZ::CCMASK_CMP_EQ)
1915 return SystemZ::CCMASK_TM_ALL_1;
1916 if (CCMask == SystemZ::CCMASK_CMP_NE)
1917 return SystemZ::CCMASK_TM_SOME_0;
1919 if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
1920 if (CCMask == SystemZ::CCMASK_CMP_GT)
1921 return SystemZ::CCMASK_TM_ALL_1;
1922 if (CCMask == SystemZ::CCMASK_CMP_LE)
1923 return SystemZ::CCMASK_TM_SOME_0;
1925 if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
1926 if (CCMask == SystemZ::CCMASK_CMP_GE)
1927 return SystemZ::CCMASK_TM_ALL_1;
1928 if (CCMask == SystemZ::CCMASK_CMP_LT)
1929 return SystemZ::CCMASK_TM_SOME_0;
1932 // Check for ordered comparisons with the top bit.
1933 if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
1934 if (CCMask == SystemZ::CCMASK_CMP_LE)
1935 return SystemZ::CCMASK_TM_MSB_0;
1936 if (CCMask == SystemZ::CCMASK_CMP_GT)
1937 return SystemZ::CCMASK_TM_MSB_1;
1939 if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
1940 if (CCMask == SystemZ::CCMASK_CMP_LT)
1941 return SystemZ::CCMASK_TM_MSB_0;
1942 if (CCMask == SystemZ::CCMASK_CMP_GE)
1943 return SystemZ::CCMASK_TM_MSB_1;
1946 // If there are just two bits, we can do equality checks for Low and High
1948 if (Mask == Low + High) {
1949 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
1950 return SystemZ::CCMASK_TM_MIXED_MSB_0;
1951 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
1952 return SystemZ::CCMASK_TM_MIXED_MSB_0 ^ SystemZ::CCMASK_ANY;
1953 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
1954 return SystemZ::CCMASK_TM_MIXED_MSB_1;
1955 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
1956 return SystemZ::CCMASK_TM_MIXED_MSB_1 ^ SystemZ::CCMASK_ANY;
1959 // Looks like we've exhausted our options.
1963 // See whether C can be implemented as a TEST UNDER MASK instruction.
1964 // Update the arguments with the TM version if so.
1965 static void adjustForTestUnderMask(SelectionDAG &DAG, const SDLoc &DL,
1967 // Check that we have a comparison with a constant.
1968 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
1971 uint64_t CmpVal = ConstOp1->getZExtValue();
1973 // Check whether the nonconstant input is an AND with a constant mask.
1976 ConstantSDNode *Mask = nullptr;
1977 if (C.Op0.getOpcode() == ISD::AND) {
1978 NewC.Op0 = C.Op0.getOperand(0);
1979 NewC.Op1 = C.Op0.getOperand(1);
1980 Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
1983 MaskVal = Mask->getZExtValue();
1985 // There is no instruction to compare with a 64-bit immediate
1986 // so use TMHH instead if possible. We need an unsigned ordered
1987 // comparison with an i64 immediate.
1988 if (NewC.Op0.getValueType() != MVT::i64 ||
1989 NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
1990 NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
1991 NewC.ICmpType == SystemZICMP::SignedOnly)
1993 // Convert LE and GT comparisons into LT and GE.
1994 if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
1995 NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
1996 if (CmpVal == uint64_t(-1))
1999 NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
2001 // If the low N bits of Op1 are zero than the low N bits of Op0 can
2002 // be masked off without changing the result.
2003 MaskVal = -(CmpVal & -CmpVal);
2004 NewC.ICmpType = SystemZICMP::UnsignedOnly;
2009 // Check whether the combination of mask, comparison value and comparison
2010 // type are suitable.
2011 unsigned BitSize = NewC.Op0.getValueType().getSizeInBits();
2012 unsigned NewCCMask, ShiftVal;
2013 if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2014 NewC.Op0.getOpcode() == ISD::SHL &&
2015 isSimpleShift(NewC.Op0, ShiftVal) &&
2016 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2017 MaskVal >> ShiftVal,
2019 SystemZICMP::Any))) {
2020 NewC.Op0 = NewC.Op0.getOperand(0);
2021 MaskVal >>= ShiftVal;
2022 } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2023 NewC.Op0.getOpcode() == ISD::SRL &&
2024 isSimpleShift(NewC.Op0, ShiftVal) &&
2025 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2026 MaskVal << ShiftVal,
2028 SystemZICMP::UnsignedOnly))) {
2029 NewC.Op0 = NewC.Op0.getOperand(0);
2030 MaskVal <<= ShiftVal;
2032 NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
2038 // Go ahead and make the change.
2039 C.Opcode = SystemZISD::TM;
2041 if (Mask && Mask->getZExtValue() == MaskVal)
2042 C.Op1 = SDValue(Mask, 0);
2044 C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
2045 C.CCValid = SystemZ::CCMASK_TM;
2046 C.CCMask = NewCCMask;
2049 // Return a Comparison that tests the condition-code result of intrinsic
2050 // node Call against constant integer CC using comparison code Cond.
2051 // Opcode is the opcode of the SystemZISD operation for the intrinsic
2052 // and CCValid is the set of possible condition-code results.
2053 static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
2054 SDValue Call, unsigned CCValid, uint64_t CC,
2055 ISD::CondCode Cond) {
2056 Comparison C(Call, SDValue());
2058 C.CCValid = CCValid;
2059 if (Cond == ISD::SETEQ)
2060 // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
2061 C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
2062 else if (Cond == ISD::SETNE)
2063 // ...and the inverse of that.
2064 C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
2065 else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
2066 // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
2067 // always true for CC>3.
2068 C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1;
2069 else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
2070 // ...and the inverse of that.
2071 C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0;
2072 else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
2073 // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
2074 // always true for CC>3.
2075 C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1;
2076 else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
2077 // ...and the inverse of that.
2078 C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0;
2080 llvm_unreachable("Unexpected integer comparison type");
2081 C.CCMask &= CCValid;
2085 // Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
2086 static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
2087 ISD::CondCode Cond, const SDLoc &DL) {
2088 if (CmpOp1.getOpcode() == ISD::Constant) {
2089 uint64_t Constant = cast<ConstantSDNode>(CmpOp1)->getZExtValue();
2090 unsigned Opcode, CCValid;
2091 if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
2092 CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
2093 isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
2094 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2095 if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
2096 CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 &&
2097 isIntrinsicWithCC(CmpOp0, Opcode, CCValid))
2098 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2100 Comparison C(CmpOp0, CmpOp1);
2101 C.CCMask = CCMaskForCondCode(Cond);
2102 if (C.Op0.getValueType().isFloatingPoint()) {
2103 C.CCValid = SystemZ::CCMASK_FCMP;
2104 C.Opcode = SystemZISD::FCMP;
2107 C.CCValid = SystemZ::CCMASK_ICMP;
2108 C.Opcode = SystemZISD::ICMP;
2109 // Choose the type of comparison. Equality and inequality tests can
2110 // use either signed or unsigned comparisons. The choice also doesn't
2111 // matter if both sign bits are known to be clear. In those cases we
2112 // want to give the main isel code the freedom to choose whichever
2114 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
2115 C.CCMask == SystemZ::CCMASK_CMP_NE ||
2116 (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
2117 C.ICmpType = SystemZICMP::Any;
2118 else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
2119 C.ICmpType = SystemZICMP::UnsignedOnly;
2121 C.ICmpType = SystemZICMP::SignedOnly;
2122 C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
2123 adjustZeroCmp(DAG, DL, C);
2124 adjustSubwordCmp(DAG, DL, C);
2125 adjustForSubtraction(DAG, DL, C);
2127 adjustICmpTruncate(DAG, DL, C);
2130 if (shouldSwapCmpOperands(C)) {
2131 std::swap(C.Op0, C.Op1);
2132 C.CCMask = reverseCCMask(C.CCMask);
2135 adjustForTestUnderMask(DAG, DL, C);
2139 // Emit the comparison instruction described by C.
2140 static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
2141 if (!C.Op1.getNode()) {
2143 switch (C.Op0.getOpcode()) {
2144 case ISD::INTRINSIC_W_CHAIN:
2145 Op = emitIntrinsicWithChainAndGlue(DAG, C.Op0, C.Opcode);
2147 case ISD::INTRINSIC_WO_CHAIN:
2148 Op = emitIntrinsicWithGlue(DAG, C.Op0, C.Opcode);
2151 llvm_unreachable("Invalid comparison operands");
2153 return SDValue(Op.getNode(), Op->getNumValues() - 1);
2155 if (C.Opcode == SystemZISD::ICMP)
2156 return DAG.getNode(SystemZISD::ICMP, DL, MVT::Glue, C.Op0, C.Op1,
2157 DAG.getConstant(C.ICmpType, DL, MVT::i32));
2158 if (C.Opcode == SystemZISD::TM) {
2159 bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
2160 bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_1));
2161 return DAG.getNode(SystemZISD::TM, DL, MVT::Glue, C.Op0, C.Op1,
2162 DAG.getConstant(RegisterOnly, DL, MVT::i32));
2164 return DAG.getNode(C.Opcode, DL, MVT::Glue, C.Op0, C.Op1);
2167 // Implement a 32-bit *MUL_LOHI operation by extending both operands to
2168 // 64 bits. Extend is the extension type to use. Store the high part
2169 // in Hi and the low part in Lo.
2170 static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend,
2171 SDValue Op0, SDValue Op1, SDValue &Hi,
2173 Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
2174 Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
2175 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
2176 Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2177 DAG.getConstant(32, DL, MVT::i64));
2178 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
2179 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
2182 // Lower a binary operation that produces two VT results, one in each
2183 // half of a GR128 pair. Op0 and Op1 are the VT operands to the operation,
2184 // Extend extends Op0 to a GR128, and Opcode performs the GR128 operation
2185 // on the extended Op0 and (unextended) Op1. Store the even register result
2186 // in Even and the odd register result in Odd.
2187 static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
2188 unsigned Extend, unsigned Opcode, SDValue Op0,
2189 SDValue Op1, SDValue &Even, SDValue &Odd) {
2190 SDNode *In128 = DAG.getMachineNode(Extend, DL, MVT::Untyped, Op0);
2191 SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped,
2192 SDValue(In128, 0), Op1);
2193 bool Is32Bit = is32Bit(VT);
2194 Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
2195 Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
2198 // Return an i32 value that is 1 if the CC value produced by Glue is
2199 // in the mask CCMask and 0 otherwise. CC is known to have a value
2200 // in CCValid, so other values can be ignored.
2201 static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue Glue,
2202 unsigned CCValid, unsigned CCMask) {
2203 IPMConversion Conversion = getIPMConversion(CCValid, CCMask);
2204 SDValue Result = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
2206 if (Conversion.XORValue)
2207 Result = DAG.getNode(ISD::XOR, DL, MVT::i32, Result,
2208 DAG.getConstant(Conversion.XORValue, DL, MVT::i32));
2210 if (Conversion.AddValue)
2211 Result = DAG.getNode(ISD::ADD, DL, MVT::i32, Result,
2212 DAG.getConstant(Conversion.AddValue, DL, MVT::i32));
2214 // The SHR/AND sequence should get optimized to an RISBG.
2215 Result = DAG.getNode(ISD::SRL, DL, MVT::i32, Result,
2216 DAG.getConstant(Conversion.Bit, DL, MVT::i32));
2217 if (Conversion.Bit != 31)
2218 Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
2219 DAG.getConstant(1, DL, MVT::i32));
2223 // Return the SystemISD vector comparison operation for CC, or 0 if it cannot
2224 // be done directly. IsFP is true if CC is for a floating-point rather than
2225 // integer comparison.
2226 static unsigned getVectorComparison(ISD::CondCode CC, bool IsFP) {
2230 return IsFP ? SystemZISD::VFCMPE : SystemZISD::VICMPE;
2234 return IsFP ? SystemZISD::VFCMPHE : static_cast<SystemZISD::NodeType>(0);
2238 return IsFP ? SystemZISD::VFCMPH : SystemZISD::VICMPH;
2241 return IsFP ? static_cast<SystemZISD::NodeType>(0) : SystemZISD::VICMPHL;
2248 // Return the SystemZISD vector comparison operation for CC or its inverse,
2249 // or 0 if neither can be done directly. Indicate in Invert whether the
2250 // result is for the inverse of CC. IsFP is true if CC is for a
2251 // floating-point rather than integer comparison.
2252 static unsigned getVectorComparisonOrInvert(ISD::CondCode CC, bool IsFP,
2254 if (unsigned Opcode = getVectorComparison(CC, IsFP)) {
2259 CC = ISD::getSetCCInverse(CC, !IsFP);
2260 if (unsigned Opcode = getVectorComparison(CC, IsFP)) {
2268 // Return a v2f64 that contains the extended form of elements Start and Start+1
2269 // of v4f32 value Op.
2270 static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL,
2272 int Mask[] = { Start, -1, Start + 1, -1 };
2273 Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
2274 return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
2277 // Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
2278 // producing a result of type VT.
2279 static SDValue getVectorCmp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &DL,
2280 EVT VT, SDValue CmpOp0, SDValue CmpOp1) {
2281 // There is no hardware support for v4f32, so extend the vector into
2282 // two v2f64s and compare those.
2283 if (CmpOp0.getValueType() == MVT::v4f32) {
2284 SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0);
2285 SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0);
2286 SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1);
2287 SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1);
2288 SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
2289 SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
2290 return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
2292 return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
2295 // Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
2296 // an integer mask of type VT.
2297 static SDValue lowerVectorSETCC(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
2298 ISD::CondCode CC, SDValue CmpOp0,
2300 bool IsFP = CmpOp0.getValueType().isFloatingPoint();
2301 bool Invert = false;
2304 // Handle tests for order using (or (ogt y x) (oge x y)).
2308 assert(IsFP && "Unexpected integer comparison");
2309 SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0);
2310 SDValue GE = getVectorCmp(DAG, SystemZISD::VFCMPHE, DL, VT, CmpOp0, CmpOp1);
2311 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
2315 // Handle <> tests using (or (ogt y x) (ogt x y)).
2319 assert(IsFP && "Unexpected integer comparison");
2320 SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0);
2321 SDValue GT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp0, CmpOp1);
2322 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
2326 // Otherwise a single comparison is enough. It doesn't really
2327 // matter whether we try the inversion or the swap first, since
2328 // there are no cases where both work.
2330 if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert))
2331 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1);
2333 CC = ISD::getSetCCSwappedOperands(CC);
2334 if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert))
2335 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0);
2337 llvm_unreachable("Unhandled comparison");
2342 SDValue Mask = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
2343 DAG.getConstant(65535, DL, MVT::i32));
2344 Mask = DAG.getNode(ISD::BITCAST, DL, VT, Mask);
2345 Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
2350 SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
2351 SelectionDAG &DAG) const {
2352 SDValue CmpOp0 = Op.getOperand(0);
2353 SDValue CmpOp1 = Op.getOperand(1);
2354 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2356 EVT VT = Op.getValueType();
2358 return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
2360 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2361 SDValue Glue = emitCmp(DAG, DL, C);
2362 return emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
2365 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2366 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2367 SDValue CmpOp0 = Op.getOperand(2);
2368 SDValue CmpOp1 = Op.getOperand(3);
2369 SDValue Dest = Op.getOperand(4);
2372 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2373 SDValue Glue = emitCmp(DAG, DL, C);
2374 return DAG.getNode(SystemZISD::BR_CCMASK, DL, Op.getValueType(),
2375 Op.getOperand(0), DAG.getConstant(C.CCValid, DL, MVT::i32),
2376 DAG.getConstant(C.CCMask, DL, MVT::i32), Dest, Glue);
2379 // Return true if Pos is CmpOp and Neg is the negative of CmpOp,
2380 // allowing Pos and Neg to be wider than CmpOp.
2381 static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
2382 return (Neg.getOpcode() == ISD::SUB &&
2383 Neg.getOperand(0).getOpcode() == ISD::Constant &&
2384 cast<ConstantSDNode>(Neg.getOperand(0))->getZExtValue() == 0 &&
2385 Neg.getOperand(1) == Pos &&
2387 (Pos.getOpcode() == ISD::SIGN_EXTEND &&
2388 Pos.getOperand(0) == CmpOp)));
2391 // Return the absolute or negative absolute of Op; IsNegative decides which.
2392 static SDValue getAbsolute(SelectionDAG &DAG, const SDLoc &DL, SDValue Op,
2394 Op = DAG.getNode(SystemZISD::IABS, DL, Op.getValueType(), Op);
2396 Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
2397 DAG.getConstant(0, DL, Op.getValueType()), Op);
2401 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
2402 SelectionDAG &DAG) const {
2403 SDValue CmpOp0 = Op.getOperand(0);
2404 SDValue CmpOp1 = Op.getOperand(1);
2405 SDValue TrueOp = Op.getOperand(2);
2406 SDValue FalseOp = Op.getOperand(3);
2407 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2410 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2412 // Check for absolute and negative-absolute selections, including those
2413 // where the comparison value is sign-extended (for LPGFR and LNGFR).
2414 // This check supplements the one in DAGCombiner.
2415 if (C.Opcode == SystemZISD::ICMP &&
2416 C.CCMask != SystemZ::CCMASK_CMP_EQ &&
2417 C.CCMask != SystemZ::CCMASK_CMP_NE &&
2418 C.Op1.getOpcode() == ISD::Constant &&
2419 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2420 if (isAbsolute(C.Op0, TrueOp, FalseOp))
2421 return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
2422 if (isAbsolute(C.Op0, FalseOp, TrueOp))
2423 return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
2426 SDValue Glue = emitCmp(DAG, DL, C);
2428 // Special case for handling -1/0 results. The shifts we use here
2429 // should get optimized with the IPM conversion sequence.
2430 auto *TrueC = dyn_cast<ConstantSDNode>(TrueOp);
2431 auto *FalseC = dyn_cast<ConstantSDNode>(FalseOp);
2432 if (TrueC && FalseC) {
2433 int64_t TrueVal = TrueC->getSExtValue();
2434 int64_t FalseVal = FalseC->getSExtValue();
2435 if ((TrueVal == -1 && FalseVal == 0) || (TrueVal == 0 && FalseVal == -1)) {
2436 // Invert the condition if we want -1 on false.
2438 C.CCMask ^= C.CCValid;
2439 SDValue Result = emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
2440 EVT VT = Op.getValueType();
2441 // Extend the result to VT. Upper bits are ignored.
2443 Result = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Result);
2444 // Sign-extend from the low bit.
2445 SDValue ShAmt = DAG.getConstant(VT.getSizeInBits() - 1, DL, MVT::i32);
2446 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Result, ShAmt);
2447 return DAG.getNode(ISD::SRA, DL, VT, Shl, ShAmt);
2451 SDValue Ops[] = {TrueOp, FalseOp, DAG.getConstant(C.CCValid, DL, MVT::i32),
2452 DAG.getConstant(C.CCMask, DL, MVT::i32), Glue};
2454 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
2455 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VTs, Ops);
2458 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
2459 SelectionDAG &DAG) const {
2461 const GlobalValue *GV = Node->getGlobal();
2462 int64_t Offset = Node->getOffset();
2463 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2464 CodeModel::Model CM = DAG.getTarget().getCodeModel();
2467 if (Subtarget.isPC32DBLSymbol(GV, CM)) {
2468 // Assign anchors at 1<<12 byte boundaries.
2469 uint64_t Anchor = Offset & ~uint64_t(0xfff);
2470 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
2471 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2473 // The offset can be folded into the address if it is aligned to a halfword.
2475 if (Offset != 0 && (Offset & 1) == 0) {
2476 SDValue Full = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
2477 Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
2481 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
2482 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2483 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2484 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2487 // If there was a non-zero offset that we didn't fold, create an explicit
2490 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
2491 DAG.getConstant(Offset, DL, PtrVT));
2496 SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
2499 SDValue GOTOffset) const {
2501 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2502 SDValue Chain = DAG.getEntryNode();
2505 // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
2506 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2507 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
2508 Glue = Chain.getValue(1);
2509 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
2510 Glue = Chain.getValue(1);
2512 // The first call operand is the chain and the second is the TLS symbol.
2513 SmallVector<SDValue, 8> Ops;
2514 Ops.push_back(Chain);
2515 Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
2516 Node->getValueType(0),
2519 // Add argument registers to the end of the list so that they are
2520 // known live into the call.
2521 Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
2522 Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
2524 // Add a register mask operand representing the call-preserved registers.
2525 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2526 const uint32_t *Mask =
2527 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
2528 assert(Mask && "Missing call preserved mask for calling convention");
2529 Ops.push_back(DAG.getRegisterMask(Mask));
2531 // Glue the call to the argument copies.
2532 Ops.push_back(Glue);
2535 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2536 Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
2537 Glue = Chain.getValue(1);
2539 // Copy the return value from %r2.
2540 return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
2543 SDValue SystemZTargetLowering::lowerThreadPointer(const SDLoc &DL,
2544 SelectionDAG &DAG) const {
2545 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2547 // The high part of the thread pointer is in access register 0.
2548 SDValue TPHi = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
2549 DAG.getConstant(0, DL, MVT::i32));
2550 TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
2552 // The low part of the thread pointer is in access register 1.
2553 SDValue TPLo = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
2554 DAG.getConstant(1, DL, MVT::i32));
2555 TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
2557 // Merge them into a single 64-bit address.
2558 SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
2559 DAG.getConstant(32, DL, PtrVT));
2560 return DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
2563 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
2564 SelectionDAG &DAG) const {
2565 if (DAG.getTarget().Options.EmulatedTLS)
2566 return LowerToTLSEmulatedModel(Node, DAG);
2568 const GlobalValue *GV = Node->getGlobal();
2569 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2570 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
2572 SDValue TP = lowerThreadPointer(DL, DAG);
2574 // Get the offset of GA from the thread pointer, based on the TLS model.
2577 case TLSModel::GeneralDynamic: {
2578 // Load the GOT offset of the tls_index (module ID / per-symbol offset).
2579 SystemZConstantPoolValue *CPV =
2580 SystemZConstantPoolValue::Create(GV, SystemZCP::TLSGD);
2582 Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2583 Offset = DAG.getLoad(
2584 PtrVT, DL, DAG.getEntryNode(), Offset,
2585 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2587 // Call __tls_get_offset to retrieve the offset.
2588 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
2592 case TLSModel::LocalDynamic: {
2593 // Load the GOT offset of the module ID.
2594 SystemZConstantPoolValue *CPV =
2595 SystemZConstantPoolValue::Create(GV, SystemZCP::TLSLDM);
2597 Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2598 Offset = DAG.getLoad(
2599 PtrVT, DL, DAG.getEntryNode(), Offset,
2600 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2602 // Call __tls_get_offset to retrieve the module base offset.
2603 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
2605 // Note: The SystemZLDCleanupPass will remove redundant computations
2606 // of the module base offset. Count total number of local-dynamic
2607 // accesses to trigger execution of that pass.
2608 SystemZMachineFunctionInfo* MFI =
2609 DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>();
2610 MFI->incNumLocalDynamicTLSAccesses();
2612 // Add the per-symbol offset.
2613 CPV = SystemZConstantPoolValue::Create(GV, SystemZCP::DTPOFF);
2615 SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, 8);
2616 DTPOffset = DAG.getLoad(
2617 PtrVT, DL, DAG.getEntryNode(), DTPOffset,
2618 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2620 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
2624 case TLSModel::InitialExec: {
2625 // Load the offset from the GOT.
2626 Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2627 SystemZII::MO_INDNTPOFF);
2628 Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
2630 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset,
2631 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2635 case TLSModel::LocalExec: {
2636 // Force the offset into the constant pool and load it from there.
2637 SystemZConstantPoolValue *CPV =
2638 SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF);
2640 Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2641 Offset = DAG.getLoad(
2642 PtrVT, DL, DAG.getEntryNode(), Offset,
2643 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2648 // Add the base and offset together.
2649 return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
2652 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
2653 SelectionDAG &DAG) const {
2655 const BlockAddress *BA = Node->getBlockAddress();
2656 int64_t Offset = Node->getOffset();
2657 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2659 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
2660 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2664 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
2665 SelectionDAG &DAG) const {
2667 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2668 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2670 // Use LARL to load the address of the table.
2671 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2674 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
2675 SelectionDAG &DAG) const {
2677 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2680 if (CP->isMachineConstantPoolEntry())
2681 Result = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2682 CP->getAlignment());
2684 Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2685 CP->getAlignment(), CP->getOffset());
2687 // Use LARL to load the address of the constant pool entry.
2688 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2691 SDValue SystemZTargetLowering::lowerFRAMEADDR(SDValue Op,
2692 SelectionDAG &DAG) const {
2693 MachineFunction &MF = DAG.getMachineFunction();
2694 MachineFrameInfo *MFI = MF.getFrameInfo();
2695 MFI->setFrameAddressIsTaken(true);
2698 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2699 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2701 // If the back chain frame index has not been allocated yet, do so.
2702 SystemZMachineFunctionInfo *FI = MF.getInfo<SystemZMachineFunctionInfo>();
2703 int BackChainIdx = FI->getFramePointerSaveIndex();
2704 if (!BackChainIdx) {
2705 // By definition, the frame address is the address of the back chain.
2706 BackChainIdx = MFI->CreateFixedObject(8, -SystemZMC::CallFrameSize, false);
2707 FI->setFramePointerSaveIndex(BackChainIdx);
2709 SDValue BackChain = DAG.getFrameIndex(BackChainIdx, PtrVT);
2711 // FIXME The frontend should detect this case.
2713 report_fatal_error("Unsupported stack frame traversal count");
2719 SDValue SystemZTargetLowering::lowerRETURNADDR(SDValue Op,
2720 SelectionDAG &DAG) const {
2721 MachineFunction &MF = DAG.getMachineFunction();
2722 MachineFrameInfo *MFI = MF.getFrameInfo();
2723 MFI->setReturnAddressIsTaken(true);
2725 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2729 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2730 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2732 // FIXME The frontend should detect this case.
2734 report_fatal_error("Unsupported stack frame traversal count");
2737 // Return R14D, which has the return address. Mark it an implicit live-in.
2738 unsigned LinkReg = MF.addLiveIn(SystemZ::R14D, &SystemZ::GR64BitRegClass);
2739 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, LinkReg, PtrVT);
2742 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
2743 SelectionDAG &DAG) const {
2745 SDValue In = Op.getOperand(0);
2746 EVT InVT = In.getValueType();
2747 EVT ResVT = Op.getValueType();
2749 // Convert loads directly. This is normally done by DAGCombiner,
2750 // but we need this case for bitcasts that are created during lowering
2751 // and which are then lowered themselves.
2752 if (auto *LoadN = dyn_cast<LoadSDNode>(In))
2753 return DAG.getLoad(ResVT, DL, LoadN->getChain(), LoadN->getBasePtr(),
2754 LoadN->getMemOperand());
2756 if (InVT == MVT::i32 && ResVT == MVT::f32) {
2758 if (Subtarget.hasHighWord()) {
2759 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
2761 In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
2762 MVT::i64, SDValue(U64, 0), In);
2764 In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
2765 In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
2766 DAG.getConstant(32, DL, MVT::i64));
2768 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
2769 return DAG.getTargetExtractSubreg(SystemZ::subreg_r32,
2770 DL, MVT::f32, Out64);
2772 if (InVT == MVT::f32 && ResVT == MVT::i32) {
2773 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
2774 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_r32, DL,
2775 MVT::f64, SDValue(U64, 0), In);
2776 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
2777 if (Subtarget.hasHighWord())
2778 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
2780 SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
2781 DAG.getConstant(32, DL, MVT::i64));
2782 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
2784 llvm_unreachable("Unexpected bitcast combination");
2787 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
2788 SelectionDAG &DAG) const {
2789 MachineFunction &MF = DAG.getMachineFunction();
2790 SystemZMachineFunctionInfo *FuncInfo =
2791 MF.getInfo<SystemZMachineFunctionInfo>();
2792 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2794 SDValue Chain = Op.getOperand(0);
2795 SDValue Addr = Op.getOperand(1);
2796 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2799 // The initial values of each field.
2800 const unsigned NumFields = 4;
2801 SDValue Fields[NumFields] = {
2802 DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
2803 DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
2804 DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
2805 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
2808 // Store each field into its respective slot.
2809 SDValue MemOps[NumFields];
2810 unsigned Offset = 0;
2811 for (unsigned I = 0; I < NumFields; ++I) {
2812 SDValue FieldAddr = Addr;
2814 FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
2815 DAG.getIntPtrConstant(Offset, DL));
2816 MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
2817 MachinePointerInfo(SV, Offset));
2820 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2823 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
2824 SelectionDAG &DAG) const {
2825 SDValue Chain = Op.getOperand(0);
2826 SDValue DstPtr = Op.getOperand(1);
2827 SDValue SrcPtr = Op.getOperand(2);
2828 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2829 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
2832 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32, DL),
2833 /*Align*/8, /*isVolatile*/false, /*AlwaysInline*/false,
2834 /*isTailCall*/false,
2835 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
2838 SDValue SystemZTargetLowering::
2839 lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
2840 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
2841 MachineFunction &MF = DAG.getMachineFunction();
2842 bool RealignOpt = !MF.getFunction()-> hasFnAttribute("no-realign-stack");
2843 bool StoreBackchain = MF.getFunction()->hasFnAttribute("backchain");
2845 SDValue Chain = Op.getOperand(0);
2846 SDValue Size = Op.getOperand(1);
2847 SDValue Align = Op.getOperand(2);
2850 // If user has set the no alignment function attribute, ignore
2851 // alloca alignments.
2852 uint64_t AlignVal = (RealignOpt ?
2853 dyn_cast<ConstantSDNode>(Align)->getZExtValue() : 0);
2855 uint64_t StackAlign = TFI->getStackAlignment();
2856 uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
2857 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
2859 unsigned SPReg = getStackPointerRegisterToSaveRestore();
2860 SDValue NeededSpace = Size;
2862 // Get a reference to the stack pointer.
2863 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
2865 // If we need a backchain, save it now.
2868 Backchain = DAG.getLoad(MVT::i64, DL, Chain, OldSP, MachinePointerInfo());
2870 // Add extra space for alignment if needed.
2871 if (ExtraAlignSpace)
2872 NeededSpace = DAG.getNode(ISD::ADD, DL, MVT::i64, NeededSpace,
2873 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
2875 // Get the new stack pointer value.
2876 SDValue NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, NeededSpace);
2878 // Copy the new stack pointer back.
2879 Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
2881 // The allocated data lives above the 160 bytes allocated for the standard
2882 // frame, plus any outgoing stack arguments. We don't know how much that
2883 // amounts to yet, so emit a special ADJDYNALLOC placeholder.
2884 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
2885 SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
2887 // Dynamically realign if needed.
2888 if (RequiredAlign > StackAlign) {
2890 DAG.getNode(ISD::ADD, DL, MVT::i64, Result,
2891 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
2893 DAG.getNode(ISD::AND, DL, MVT::i64, Result,
2894 DAG.getConstant(~(RequiredAlign - 1), DL, MVT::i64));
2898 Chain = DAG.getStore(Chain, DL, Backchain, NewSP, MachinePointerInfo());
2900 SDValue Ops[2] = { Result, Chain };
2901 return DAG.getMergeValues(Ops, DL);
2904 SDValue SystemZTargetLowering::lowerGET_DYNAMIC_AREA_OFFSET(
2905 SDValue Op, SelectionDAG &DAG) const {
2908 return DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
2911 SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
2912 SelectionDAG &DAG) const {
2913 EVT VT = Op.getValueType();
2917 // Just do a normal 64-bit multiplication and extract the results.
2918 // We define this so that it can be used for constant division.
2919 lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
2920 Op.getOperand(1), Ops[1], Ops[0]);
2922 // Do a full 128-bit multiplication based on UMUL_LOHI64:
2924 // (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
2926 // but using the fact that the upper halves are either all zeros
2929 // (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
2931 // and grouping the right terms together since they are quicker than the
2934 // (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
2935 SDValue C63 = DAG.getConstant(63, DL, MVT::i64);
2936 SDValue LL = Op.getOperand(0);
2937 SDValue RL = Op.getOperand(1);
2938 SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
2939 SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
2940 // UMUL_LOHI64 returns the low result in the odd register and the high
2941 // result in the even register. SMUL_LOHI is defined to return the
2942 // low half first, so the results are in reverse order.
2943 lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
2944 LL, RL, Ops[1], Ops[0]);
2945 SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
2946 SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
2947 SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
2948 Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
2950 return DAG.getMergeValues(Ops, DL);
2953 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
2954 SelectionDAG &DAG) const {
2955 EVT VT = Op.getValueType();
2959 // Just do a normal 64-bit multiplication and extract the results.
2960 // We define this so that it can be used for constant division.
2961 lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
2962 Op.getOperand(1), Ops[1], Ops[0]);
2964 // UMUL_LOHI64 returns the low result in the odd register and the high
2965 // result in the even register. UMUL_LOHI is defined to return the
2966 // low half first, so the results are in reverse order.
2967 lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
2968 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
2969 return DAG.getMergeValues(Ops, DL);
2972 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
2973 SelectionDAG &DAG) const {
2974 SDValue Op0 = Op.getOperand(0);
2975 SDValue Op1 = Op.getOperand(1);
2976 EVT VT = Op.getValueType();
2980 // We use DSGF for 32-bit division.
2982 Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
2983 Opcode = SystemZISD::SDIVREM32;
2984 } else if (DAG.ComputeNumSignBits(Op1) > 32) {
2985 Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
2986 Opcode = SystemZISD::SDIVREM32;
2988 Opcode = SystemZISD::SDIVREM64;
2990 // DSG(F) takes a 64-bit dividend, so the even register in the GR128
2991 // input is "don't care". The instruction returns the remainder in
2992 // the even register and the quotient in the odd register.
2994 lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, Opcode,
2995 Op0, Op1, Ops[1], Ops[0]);
2996 return DAG.getMergeValues(Ops, DL);
2999 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
3000 SelectionDAG &DAG) const {
3001 EVT VT = Op.getValueType();
3004 // DL(G) uses a double-width dividend, so we need to clear the even
3005 // register in the GR128 input. The instruction returns the remainder
3006 // in the even register and the quotient in the odd register.
3009 lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_32, SystemZISD::UDIVREM32,
3010 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3012 lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_64, SystemZISD::UDIVREM64,
3013 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3014 return DAG.getMergeValues(Ops, DL);
3017 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
3018 assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
3020 // Get the known-zero masks for each operand.
3021 SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
3022 APInt KnownZero[2], KnownOne[2];
3023 DAG.computeKnownBits(Ops[0], KnownZero[0], KnownOne[0]);
3024 DAG.computeKnownBits(Ops[1], KnownZero[1], KnownOne[1]);
3026 // See if the upper 32 bits of one operand and the lower 32 bits of the
3027 // other are known zero. They are the low and high operands respectively.
3028 uint64_t Masks[] = { KnownZero[0].getZExtValue(),
3029 KnownZero[1].getZExtValue() };
3031 if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
3033 else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
3038 SDValue LowOp = Ops[Low];
3039 SDValue HighOp = Ops[High];
3041 // If the high part is a constant, we're better off using IILH.
3042 if (HighOp.getOpcode() == ISD::Constant)
3045 // If the low part is a constant that is outside the range of LHI,
3046 // then we're better off using IILF.
3047 if (LowOp.getOpcode() == ISD::Constant) {
3048 int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
3049 if (!isInt<16>(Value))
3053 // Check whether the high part is an AND that doesn't change the
3054 // high 32 bits and just masks out low bits. We can skip it if so.
3055 if (HighOp.getOpcode() == ISD::AND &&
3056 HighOp.getOperand(1).getOpcode() == ISD::Constant) {
3057 SDValue HighOp0 = HighOp.getOperand(0);
3058 uint64_t Mask = cast<ConstantSDNode>(HighOp.getOperand(1))->getZExtValue();
3059 if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
3063 // Take advantage of the fact that all GR32 operations only change the
3064 // low 32 bits by truncating Low to an i32 and inserting it directly
3065 // using a subreg. The interesting cases are those where the truncation
3068 SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
3069 return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
3070 MVT::i64, HighOp, Low32);
3073 SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op,
3074 SelectionDAG &DAG) const {
3075 EVT VT = Op.getValueType();
3077 Op = Op.getOperand(0);
3079 // Handle vector types via VPOPCT.
3080 if (VT.isVector()) {
3081 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op);
3082 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op);
3083 switch (VT.getVectorElementType().getSizeInBits()) {
3087 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
3088 SDValue Shift = DAG.getConstant(8, DL, MVT::i32);
3089 SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift);
3090 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
3091 Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift);
3095 SDValue Tmp = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
3096 DAG.getConstant(0, DL, MVT::i32));
3097 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
3101 SDValue Tmp = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
3102 DAG.getConstant(0, DL, MVT::i32));
3103 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp);
3104 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
3108 llvm_unreachable("Unexpected type");
3113 // Get the known-zero mask for the operand.
3114 APInt KnownZero, KnownOne;
3115 DAG.computeKnownBits(Op, KnownZero, KnownOne);
3116 unsigned NumSignificantBits = (~KnownZero).getActiveBits();
3117 if (NumSignificantBits == 0)
3118 return DAG.getConstant(0, DL, VT);
3120 // Skip known-zero high parts of the operand.
3121 int64_t OrigBitSize = VT.getSizeInBits();
3122 int64_t BitSize = (int64_t)1 << Log2_32_Ceil(NumSignificantBits);
3123 BitSize = std::min(BitSize, OrigBitSize);
3125 // The POPCNT instruction counts the number of bits in each byte.
3126 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op);
3127 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op);
3128 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
3130 // Add up per-byte counts in a binary tree. All bits of Op at
3131 // position larger than BitSize remain zero throughout.
3132 for (int64_t I = BitSize / 2; I >= 8; I = I / 2) {
3133 SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT));
3134 if (BitSize != OrigBitSize)
3135 Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp,
3136 DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT));
3137 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
3140 // Extract overall result from high byte.
3142 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
3143 DAG.getConstant(BitSize - 8, DL, VT));
3148 SDValue SystemZTargetLowering::lowerATOMIC_FENCE(SDValue Op,
3149 SelectionDAG &DAG) const {
3151 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
3152 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
3153 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
3154 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
3156 // The only fence that needs an instruction is a sequentially-consistent
3157 // cross-thread fence.
3158 if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
3159 FenceScope == CrossThread) {
3160 return SDValue(DAG.getMachineNode(SystemZ::Serialize, DL, MVT::Other,
3165 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
3166 return DAG.getNode(SystemZISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
3169 // Op is an atomic load. Lower it into a normal volatile load.
3170 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
3171 SelectionDAG &DAG) const {
3172 auto *Node = cast<AtomicSDNode>(Op.getNode());
3173 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), Op.getValueType(),
3174 Node->getChain(), Node->getBasePtr(),
3175 Node->getMemoryVT(), Node->getMemOperand());
3178 // Op is an atomic store. Lower it into a normal volatile store followed
3179 // by a serialization.
3180 SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
3181 SelectionDAG &DAG) const {
3182 auto *Node = cast<AtomicSDNode>(Op.getNode());
3183 SDValue Chain = DAG.getTruncStore(Node->getChain(), SDLoc(Op), Node->getVal(),
3184 Node->getBasePtr(), Node->getMemoryVT(),
3185 Node->getMemOperand());
3186 return SDValue(DAG.getMachineNode(SystemZ::Serialize, SDLoc(Op), MVT::Other,
3190 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation. Lower the first
3191 // two into the fullword ATOMIC_LOADW_* operation given by Opcode.
3192 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op,
3194 unsigned Opcode) const {
3195 auto *Node = cast<AtomicSDNode>(Op.getNode());
3197 // 32-bit operations need no code outside the main loop.
3198 EVT NarrowVT = Node->getMemoryVT();
3199 EVT WideVT = MVT::i32;
3200 if (NarrowVT == WideVT)
3203 int64_t BitSize = NarrowVT.getSizeInBits();
3204 SDValue ChainIn = Node->getChain();
3205 SDValue Addr = Node->getBasePtr();
3206 SDValue Src2 = Node->getVal();
3207 MachineMemOperand *MMO = Node->getMemOperand();
3209 EVT PtrVT = Addr.getValueType();
3211 // Convert atomic subtracts of constants into additions.
3212 if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
3213 if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
3214 Opcode = SystemZISD::ATOMIC_LOADW_ADD;
3215 Src2 = DAG.getConstant(-Const->getSExtValue(), DL, Src2.getValueType());
3218 // Get the address of the containing word.
3219 SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
3220 DAG.getConstant(-4, DL, PtrVT));
3222 // Get the number of bits that the word must be rotated left in order
3223 // to bring the field to the top bits of a GR32.
3224 SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
3225 DAG.getConstant(3, DL, PtrVT));
3226 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
3228 // Get the complementing shift amount, for rotating a field in the top
3229 // bits back to its proper position.
3230 SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
3231 DAG.getConstant(0, DL, WideVT), BitShift);
3233 // Extend the source operand to 32 bits and prepare it for the inner loop.
3234 // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
3235 // operations require the source to be shifted in advance. (This shift
3236 // can be folded if the source is constant.) For AND and NAND, the lower
3237 // bits must be set, while for other opcodes they should be left clear.
3238 if (Opcode != SystemZISD::ATOMIC_SWAPW)
3239 Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
3240 DAG.getConstant(32 - BitSize, DL, WideVT));
3241 if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
3242 Opcode == SystemZISD::ATOMIC_LOADW_NAND)
3243 Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
3244 DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT));
3246 // Construct the ATOMIC_LOADW_* node.
3247 SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
3248 SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
3249 DAG.getConstant(BitSize, DL, WideVT) };
3250 SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
3253 // Rotate the result of the final CS so that the field is in the lower
3254 // bits of a GR32, then truncate it.
3255 SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
3256 DAG.getConstant(BitSize, DL, WideVT));
3257 SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
3259 SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
3260 return DAG.getMergeValues(RetOps, DL);
3263 // Op is an ATOMIC_LOAD_SUB operation. Lower 8- and 16-bit operations
3264 // into ATOMIC_LOADW_SUBs and decide whether to convert 32- and 64-bit
3265 // operations into additions.
3266 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
3267 SelectionDAG &DAG) const {
3268 auto *Node = cast<AtomicSDNode>(Op.getNode());
3269 EVT MemVT = Node->getMemoryVT();
3270 if (MemVT == MVT::i32 || MemVT == MVT::i64) {
3271 // A full-width operation.
3272 assert(Op.getValueType() == MemVT && "Mismatched VTs");
3273 SDValue Src2 = Node->getVal();
3277 if (auto *Op2 = dyn_cast<ConstantSDNode>(Src2)) {
3278 // Use an addition if the operand is constant and either LAA(G) is
3279 // available or the negative value is in the range of A(G)FHI.
3280 int64_t Value = (-Op2->getAPIntValue()).getSExtValue();
3281 if (isInt<32>(Value) || Subtarget.hasInterlockedAccess1())
3282 NegSrc2 = DAG.getConstant(Value, DL, MemVT);
3283 } else if (Subtarget.hasInterlockedAccess1())
3284 // Use LAA(G) if available.
3285 NegSrc2 = DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT),
3288 if (NegSrc2.getNode())
3289 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT,
3290 Node->getChain(), Node->getBasePtr(), NegSrc2,
3291 Node->getMemOperand(), Node->getOrdering(),
3292 Node->getSynchScope());
3294 // Use the node as-is.
3298 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
3301 // Node is an 8- or 16-bit ATOMIC_CMP_SWAP operation. Lower the first two
3302 // into a fullword ATOMIC_CMP_SWAPW operation.
3303 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
3304 SelectionDAG &DAG) const {
3305 auto *Node = cast<AtomicSDNode>(Op.getNode());
3307 // We have native support for 32-bit compare and swap.
3308 EVT NarrowVT = Node->getMemoryVT();
3309 EVT WideVT = MVT::i32;
3310 if (NarrowVT == WideVT)
3313 int64_t BitSize = NarrowVT.getSizeInBits();
3314 SDValue ChainIn = Node->getOperand(0);
3315 SDValue Addr = Node->getOperand(1);
3316 SDValue CmpVal = Node->getOperand(2);
3317 SDValue SwapVal = Node->getOperand(3);
3318 MachineMemOperand *MMO = Node->getMemOperand();
3320 EVT PtrVT = Addr.getValueType();
3322 // Get the address of the containing word.
3323 SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
3324 DAG.getConstant(-4, DL, PtrVT));
3326 // Get the number of bits that the word must be rotated left in order
3327 // to bring the field to the top bits of a GR32.
3328 SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
3329 DAG.getConstant(3, DL, PtrVT));
3330 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
3332 // Get the complementing shift amount, for rotating a field in the top
3333 // bits back to its proper position.
3334 SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
3335 DAG.getConstant(0, DL, WideVT), BitShift);
3337 // Construct the ATOMIC_CMP_SWAPW node.
3338 SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
3339 SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
3340 NegBitShift, DAG.getConstant(BitSize, DL, WideVT) };
3341 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
3342 VTList, Ops, NarrowVT, MMO);
3346 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
3347 SelectionDAG &DAG) const {
3348 MachineFunction &MF = DAG.getMachineFunction();
3349 MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
3350 return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
3351 SystemZ::R15D, Op.getValueType());
3354 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
3355 SelectionDAG &DAG) const {
3356 MachineFunction &MF = DAG.getMachineFunction();
3357 MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
3358 bool StoreBackchain = MF.getFunction()->hasFnAttribute("backchain");
3360 SDValue Chain = Op.getOperand(0);
3361 SDValue NewSP = Op.getOperand(1);
3365 if (StoreBackchain) {
3366 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, MVT::i64);
3367 Backchain = DAG.getLoad(MVT::i64, DL, Chain, OldSP, MachinePointerInfo());
3370 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R15D, NewSP);
3373 Chain = DAG.getStore(Chain, DL, Backchain, NewSP, MachinePointerInfo());
3378 SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
3379 SelectionDAG &DAG) const {
3380 bool IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3382 // Just preserve the chain.
3383 return Op.getOperand(0);
3386 bool IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
3387 unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
3388 auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
3391 DAG.getConstant(Code, DL, MVT::i32),
3394 return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, DL,
3395 Node->getVTList(), Ops,
3396 Node->getMemoryVT(), Node->getMemOperand());
3399 // Return an i32 that contains the value of CC immediately after After,
3400 // whose final operand must be MVT::Glue.
3401 static SDValue getCCResult(SelectionDAG &DAG, SDNode *After) {
3403 SDValue Glue = SDValue(After, After->getNumValues() - 1);
3404 SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
3405 return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM,
3406 DAG.getConstant(SystemZ::IPM_CC, DL, MVT::i32));
3410 SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
3411 SelectionDAG &DAG) const {
3412 unsigned Opcode, CCValid;
3413 if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) {
3414 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
3415 SDValue Glued = emitIntrinsicWithChainAndGlue(DAG, Op, Opcode);
3416 SDValue CC = getCCResult(DAG, Glued.getNode());
3417 DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC);
3425 SystemZTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
3426 SelectionDAG &DAG) const {
3427 unsigned Opcode, CCValid;
3428 if (isIntrinsicWithCC(Op, Opcode, CCValid)) {
3429 SDValue Glued = emitIntrinsicWithGlue(DAG, Op, Opcode);
3430 SDValue CC = getCCResult(DAG, Glued.getNode());
3431 if (Op->getNumValues() == 1)
3433 assert(Op->getNumValues() == 2 && "Expected a CC and non-CC result");
3434 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), Op->getVTList(), Glued,
3438 unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3440 case Intrinsic::thread_pointer:
3441 return lowerThreadPointer(SDLoc(Op), DAG);
3443 case Intrinsic::s390_vpdi:
3444 return DAG.getNode(SystemZISD::PERMUTE_DWORDS, SDLoc(Op), Op.getValueType(),
3445 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3447 case Intrinsic::s390_vperm:
3448 return DAG.getNode(SystemZISD::PERMUTE, SDLoc(Op), Op.getValueType(),
3449 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3451 case Intrinsic::s390_vuphb:
3452 case Intrinsic::s390_vuphh:
3453 case Intrinsic::s390_vuphf:
3454 return DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(Op), Op.getValueType(),
3457 case Intrinsic::s390_vuplhb:
3458 case Intrinsic::s390_vuplhh:
3459 case Intrinsic::s390_vuplhf:
3460 return DAG.getNode(SystemZISD::UNPACKL_HIGH, SDLoc(Op), Op.getValueType(),
3463 case Intrinsic::s390_vuplb:
3464 case Intrinsic::s390_vuplhw:
3465 case Intrinsic::s390_vuplf:
3466 return DAG.getNode(SystemZISD::UNPACK_LOW, SDLoc(Op), Op.getValueType(),
3469 case Intrinsic::s390_vupllb:
3470 case Intrinsic::s390_vupllh:
3471 case Intrinsic::s390_vupllf:
3472 return DAG.getNode(SystemZISD::UNPACKL_LOW, SDLoc(Op), Op.getValueType(),
3475 case Intrinsic::s390_vsumb:
3476 case Intrinsic::s390_vsumh:
3477 case Intrinsic::s390_vsumgh:
3478 case Intrinsic::s390_vsumgf:
3479 case Intrinsic::s390_vsumqf:
3480 case Intrinsic::s390_vsumqg:
3481 return DAG.getNode(SystemZISD::VSUM, SDLoc(Op), Op.getValueType(),
3482 Op.getOperand(1), Op.getOperand(2));
3489 // Says that SystemZISD operation Opcode can be used to perform the equivalent
3490 // of a VPERM with permute vector Bytes. If Opcode takes three operands,
3491 // Operand is the constant third operand, otherwise it is the number of
3492 // bytes in each element of the result.
3496 unsigned char Bytes[SystemZ::VectorBytes];
3500 static const Permute PermuteForms[] = {
3502 { SystemZISD::MERGE_HIGH, 8,
3503 { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } },
3505 { SystemZISD::MERGE_HIGH, 4,
3506 { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } },
3508 { SystemZISD::MERGE_HIGH, 2,
3509 { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } },
3511 { SystemZISD::MERGE_HIGH, 1,
3512 { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } },
3514 { SystemZISD::MERGE_LOW, 8,
3515 { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } },
3517 { SystemZISD::MERGE_LOW, 4,
3518 { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
3520 { SystemZISD::MERGE_LOW, 2,
3521 { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
3523 { SystemZISD::MERGE_LOW, 1,
3524 { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
3526 { SystemZISD::PACK, 4,
3527 { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } },
3529 { SystemZISD::PACK, 2,
3530 { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
3532 { SystemZISD::PACK, 1,
3533 { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
3534 // VPDI V1, V2, 4 (low half of V1, high half of V2)
3535 { SystemZISD::PERMUTE_DWORDS, 4,
3536 { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } },
3537 // VPDI V1, V2, 1 (high half of V1, low half of V2)
3538 { SystemZISD::PERMUTE_DWORDS, 1,
3539 { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } }
3542 // Called after matching a vector shuffle against a particular pattern.
3543 // Both the original shuffle and the pattern have two vector operands.
3544 // OpNos[0] is the operand of the original shuffle that should be used for
3545 // operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything.
3546 // OpNos[1] is the same for operand 1 of the pattern. Resolve these -1s and
3547 // set OpNo0 and OpNo1 to the shuffle operands that should actually be used
3548 // for operands 0 and 1 of the pattern.
3549 static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) {
3553 OpNo0 = OpNo1 = OpNos[1];
3554 } else if (OpNos[1] < 0) {
3555 OpNo0 = OpNo1 = OpNos[0];
3563 // Bytes is a VPERM-like permute vector, except that -1 is used for
3564 // undefined bytes. Return true if the VPERM can be implemented using P.
3565 // When returning true set OpNo0 to the VPERM operand that should be
3566 // used for operand 0 of P and likewise OpNo1 for operand 1 of P.
3568 // For example, if swapping the VPERM operands allows P to match, OpNo0
3569 // will be 1 and OpNo1 will be 0. If instead Bytes only refers to one
3570 // operand, but rewriting it to use two duplicated operands allows it to
3571 // match P, then OpNo0 and OpNo1 will be the same.
3572 static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P,
3573 unsigned &OpNo0, unsigned &OpNo1) {
3574 int OpNos[] = { -1, -1 };
3575 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
3578 // Make sure that the two permute vectors use the same suboperand
3579 // byte number. Only the operand numbers (the high bits) are
3580 // allowed to differ.
3581 if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1))
3583 int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes;
3584 int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes;
3585 // Make sure that the operand mappings are consistent with previous
3587 if (OpNos[ModelOpNo] == 1 - RealOpNo)
3589 OpNos[ModelOpNo] = RealOpNo;
3592 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
3595 // As above, but search for a matching permute.
3596 static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes,
3597 unsigned &OpNo0, unsigned &OpNo1) {
3598 for (auto &P : PermuteForms)
3599 if (matchPermute(Bytes, P, OpNo0, OpNo1))
3604 // Bytes is a VPERM-like permute vector, except that -1 is used for
3605 // undefined bytes. This permute is an operand of an outer permute.
3606 // See whether redistributing the -1 bytes gives a shuffle that can be
3607 // implemented using P. If so, set Transform to a VPERM-like permute vector
3608 // that, when applied to the result of P, gives the original permute in Bytes.
3609 static bool matchDoublePermute(const SmallVectorImpl<int> &Bytes,
3611 SmallVectorImpl<int> &Transform) {
3613 for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) {
3614 int Elt = Bytes[From];
3616 // Byte number From of the result is undefined.
3617 Transform[From] = -1;
3619 while (P.Bytes[To] != Elt) {
3621 if (To == SystemZ::VectorBytes)
3624 Transform[From] = To;
3630 // As above, but search for a matching permute.
3631 static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes,
3632 SmallVectorImpl<int> &Transform) {
3633 for (auto &P : PermuteForms)
3634 if (matchDoublePermute(Bytes, P, Transform))
3639 // Convert the mask of the given VECTOR_SHUFFLE into a byte-level mask,
3640 // as if it had type vNi8.
3641 static void getVPermMask(ShuffleVectorSDNode *VSN,
3642 SmallVectorImpl<int> &Bytes) {
3643 EVT VT = VSN->getValueType(0);
3644 unsigned NumElements = VT.getVectorNumElements();
3645 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3646 Bytes.resize(NumElements * BytesPerElement, -1);
3647 for (unsigned I = 0; I < NumElements; ++I) {
3648 int Index = VSN->getMaskElt(I);
3650 for (unsigned J = 0; J < BytesPerElement; ++J)
3651 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
3655 // Bytes is a VPERM-like permute vector, except that -1 is used for
3656 // undefined bytes. See whether bytes [Start, Start + BytesPerElement) of
3657 // the result come from a contiguous sequence of bytes from one input.
3658 // Set Base to the selector for the first byte if so.
3659 static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start,
3660 unsigned BytesPerElement, int &Base) {
3662 for (unsigned I = 0; I < BytesPerElement; ++I) {
3663 if (Bytes[Start + I] >= 0) {
3664 unsigned Elem = Bytes[Start + I];
3667 // Make sure the bytes would come from one input operand.
3668 if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size())
3670 } else if (unsigned(Base) != Elem - I)
3677 // Bytes is a VPERM-like permute vector, except that -1 is used for
3678 // undefined bytes. Return true if it can be performed using VSLDI.
3679 // When returning true, set StartIndex to the shift amount and OpNo0
3680 // and OpNo1 to the VPERM operands that should be used as the first
3681 // and second shift operand respectively.
3682 static bool isShlDoublePermute(const SmallVectorImpl<int> &Bytes,
3683 unsigned &StartIndex, unsigned &OpNo0,
3685 int OpNos[] = { -1, -1 };
3687 for (unsigned I = 0; I < 16; ++I) {
3688 int Index = Bytes[I];
3690 int ExpectedShift = (Index - I) % SystemZ::VectorBytes;
3691 int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes;
3692 int RealOpNo = unsigned(Index) / SystemZ::VectorBytes;
3694 Shift = ExpectedShift;
3695 else if (Shift != ExpectedShift)
3697 // Make sure that the operand mappings are consistent with previous
3699 if (OpNos[ModelOpNo] == 1 - RealOpNo)
3701 OpNos[ModelOpNo] = RealOpNo;
3705 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
3708 // Create a node that performs P on operands Op0 and Op1, casting the
3709 // operands to the appropriate type. The type of the result is determined by P.
3710 static SDValue getPermuteNode(SelectionDAG &DAG, const SDLoc &DL,
3711 const Permute &P, SDValue Op0, SDValue Op1) {
3712 // VPDI (PERMUTE_DWORDS) always operates on v2i64s. The input
3713 // elements of a PACK are twice as wide as the outputs.
3714 unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 :
3715 P.Opcode == SystemZISD::PACK ? P.Operand * 2 :
3717 // Cast both operands to the appropriate type.
3718 MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8),
3719 SystemZ::VectorBytes / InBytes);
3720 Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0);
3721 Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1);
3723 if (P.Opcode == SystemZISD::PERMUTE_DWORDS) {
3724 SDValue Op2 = DAG.getConstant(P.Operand, DL, MVT::i32);
3725 Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2);
3726 } else if (P.Opcode == SystemZISD::PACK) {
3727 MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8),
3728 SystemZ::VectorBytes / P.Operand);
3729 Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1);
3731 Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1);
3736 // Bytes is a VPERM-like permute vector, except that -1 is used for
3737 // undefined bytes. Implement it on operands Ops[0] and Ops[1] using
3739 static SDValue getGeneralPermuteNode(SelectionDAG &DAG, const SDLoc &DL,
3741 const SmallVectorImpl<int> &Bytes) {
3742 for (unsigned I = 0; I < 2; ++I)
3743 Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]);
3745 // First see whether VSLDI can be used.
3746 unsigned StartIndex, OpNo0, OpNo1;
3747 if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1))
3748 return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0],
3749 Ops[OpNo1], DAG.getConstant(StartIndex, DL, MVT::i32));
3751 // Fall back on VPERM. Construct an SDNode for the permute vector.
3752 SDValue IndexNodes[SystemZ::VectorBytes];
3753 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
3755 IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32);
3757 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
3758 SDValue Op2 = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
3759 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0], Ops[1], Op2);
3763 // Describes a general N-operand vector shuffle.
3764 struct GeneralShuffle {
3765 GeneralShuffle(EVT vt) : VT(vt) {}
3767 void add(SDValue, unsigned);
3768 SDValue getNode(SelectionDAG &, const SDLoc &);
3770 // The operands of the shuffle.
3771 SmallVector<SDValue, SystemZ::VectorBytes> Ops;
3773 // Index I is -1 if byte I of the result is undefined. Otherwise the
3774 // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand
3775 // Bytes[I] / SystemZ::VectorBytes.
3776 SmallVector<int, SystemZ::VectorBytes> Bytes;
3778 // The type of the shuffle result.
3783 // Add an extra undefined element to the shuffle.
3784 void GeneralShuffle::addUndef() {
3785 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3786 for (unsigned I = 0; I < BytesPerElement; ++I)
3787 Bytes.push_back(-1);
3790 // Add an extra element to the shuffle, taking it from element Elem of Op.
3791 // A null Op indicates a vector input whose value will be calculated later;
3792 // there is at most one such input per shuffle and it always has the same
3793 // type as the result.
3794 void GeneralShuffle::add(SDValue Op, unsigned Elem) {
3795 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3797 // The source vector can have wider elements than the result,
3798 // either through an explicit TRUNCATE or because of type legalization.
3799 // We want the least significant part.
3800 EVT FromVT = Op.getNode() ? Op.getValueType() : VT;
3801 unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize();
3802 assert(FromBytesPerElement >= BytesPerElement &&
3803 "Invalid EXTRACT_VECTOR_ELT");
3804 unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes +
3805 (FromBytesPerElement - BytesPerElement));
3807 // Look through things like shuffles and bitcasts.
3808 while (Op.getNode()) {
3809 if (Op.getOpcode() == ISD::BITCAST)
3810 Op = Op.getOperand(0);
3811 else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) {
3812 // See whether the bytes we need come from a contiguous part of one
3814 SmallVector<int, SystemZ::VectorBytes> OpBytes;
3815 getVPermMask(cast<ShuffleVectorSDNode>(Op), OpBytes);
3817 if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte))
3823 Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes);
3824 Byte = unsigned(NewByte) % SystemZ::VectorBytes;
3825 } else if (Op.isUndef()) {
3832 // Make sure that the source of the extraction is in Ops.
3834 for (; OpNo < Ops.size(); ++OpNo)
3835 if (Ops[OpNo] == Op)
3837 if (OpNo == Ops.size())
3840 // Add the element to Bytes.
3841 unsigned Base = OpNo * SystemZ::VectorBytes + Byte;
3842 for (unsigned I = 0; I < BytesPerElement; ++I)
3843 Bytes.push_back(Base + I);
3846 // Return SDNodes for the completed shuffle.
3847 SDValue GeneralShuffle::getNode(SelectionDAG &DAG, const SDLoc &DL) {
3848 assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector");
3850 if (Ops.size() == 0)
3851 return DAG.getUNDEF(VT);
3853 // Make sure that there are at least two shuffle operands.
3854 if (Ops.size() == 1)
3855 Ops.push_back(DAG.getUNDEF(MVT::v16i8));
3857 // Create a tree of shuffles, deferring root node until after the loop.
3858 // Try to redistribute the undefined elements of non-root nodes so that
3859 // the non-root shuffles match something like a pack or merge, then adjust
3860 // the parent node's permute vector to compensate for the new order.
3861 // Among other things, this copes with vectors like <2 x i16> that were
3862 // padded with undefined elements during type legalization.
3864 // In the best case this redistribution will lead to the whole tree
3865 // using packs and merges. It should rarely be a loss in other cases.
3866 unsigned Stride = 1;
3867 for (; Stride * 2 < Ops.size(); Stride *= 2) {
3868 for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) {
3869 SDValue SubOps[] = { Ops[I], Ops[I + Stride] };
3871 // Create a mask for just these two operands.
3872 SmallVector<int, SystemZ::VectorBytes> NewBytes(SystemZ::VectorBytes);
3873 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
3874 unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes;
3875 unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes;
3878 else if (OpNo == I + Stride)
3879 NewBytes[J] = SystemZ::VectorBytes + Byte;
3883 // See if it would be better to reorganize NewMask to avoid using VPERM.
3884 SmallVector<int, SystemZ::VectorBytes> NewBytesMap(SystemZ::VectorBytes);
3885 if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) {
3886 Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]);
3887 // Applying NewBytesMap to Ops[I] gets back to NewBytes.
3888 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
3889 if (NewBytes[J] >= 0) {
3890 assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
3891 "Invalid double permute");
3892 Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J];
3894 assert(NewBytesMap[J] < 0 && "Invalid double permute");
3897 // Just use NewBytes on the operands.
3898 Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes);
3899 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J)
3900 if (NewBytes[J] >= 0)
3901 Bytes[J] = I * SystemZ::VectorBytes + J;
3906 // Now we just have 2 inputs. Put the second operand in Ops[1].
3908 Ops[1] = Ops[Stride];
3909 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
3910 if (Bytes[I] >= int(SystemZ::VectorBytes))
3911 Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes;
3914 // Look for an instruction that can do the permute without resorting
3916 unsigned OpNo0, OpNo1;
3918 if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1))
3919 Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]);
3921 Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes);
3922 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
3925 // Return true if the given BUILD_VECTOR is a scalar-to-vector conversion.
3926 static bool isScalarToVector(SDValue Op) {
3927 for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I)
3928 if (!Op.getOperand(I).isUndef())
3933 // Return a vector of type VT that contains Value in the first element.
3934 // The other elements don't matter.
3935 static SDValue buildScalarToVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
3937 // If we have a constant, replicate it to all elements and let the
3938 // BUILD_VECTOR lowering take care of it.
3939 if (Value.getOpcode() == ISD::Constant ||
3940 Value.getOpcode() == ISD::ConstantFP) {
3941 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Value);
3942 return DAG.getBuildVector(VT, DL, Ops);
3944 if (Value.isUndef())
3945 return DAG.getUNDEF(VT);
3946 return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
3949 // Return a vector of type VT in which Op0 is in element 0 and Op1 is in
3950 // element 1. Used for cases in which replication is cheap.
3951 static SDValue buildMergeScalars(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
3952 SDValue Op0, SDValue Op1) {
3953 if (Op0.isUndef()) {
3955 return DAG.getUNDEF(VT);
3956 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1);
3959 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0);
3960 return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT,
3961 buildScalarToVector(DAG, DL, VT, Op0),
3962 buildScalarToVector(DAG, DL, VT, Op1));
3965 // Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64
3967 static SDValue joinDwords(SelectionDAG &DAG, const SDLoc &DL, SDValue Op0,
3969 if (Op0.isUndef() && Op1.isUndef())
3970 return DAG.getUNDEF(MVT::v2i64);
3971 // If one of the two inputs is undefined then replicate the other one,
3972 // in order to avoid using another register unnecessarily.
3974 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
3975 else if (Op1.isUndef())
3976 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3978 Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3979 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
3981 return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1);
3984 // Try to represent constant BUILD_VECTOR node BVN using a
3985 // SystemZISD::BYTE_MASK-style mask. Store the mask value in Mask
3987 static bool tryBuildVectorByteMask(BuildVectorSDNode *BVN, uint64_t &Mask) {
3988 EVT ElemVT = BVN->getValueType(0).getVectorElementType();
3989 unsigned BytesPerElement = ElemVT.getStoreSize();
3990 for (unsigned I = 0, E = BVN->getNumOperands(); I != E; ++I) {
3991 SDValue Op = BVN->getOperand(I);
3992 if (!Op.isUndef()) {
3994 if (Op.getOpcode() == ISD::Constant)
3995 Value = dyn_cast<ConstantSDNode>(Op)->getZExtValue();
3996 else if (Op.getOpcode() == ISD::ConstantFP)
3997 Value = (dyn_cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt()
4001 for (unsigned J = 0; J < BytesPerElement; ++J) {
4002 uint64_t Byte = (Value >> (J * 8)) & 0xff;
4004 Mask |= 1ULL << ((E - I - 1) * BytesPerElement + J);
4013 // Try to load a vector constant in which BitsPerElement-bit value Value
4014 // is replicated to fill the vector. VT is the type of the resulting
4015 // constant, which may have elements of a different size from BitsPerElement.
4016 // Return the SDValue of the constant on success, otherwise return
4018 static SDValue tryBuildVectorReplicate(SelectionDAG &DAG,
4019 const SystemZInstrInfo *TII,
4020 const SDLoc &DL, EVT VT, uint64_t Value,
4021 unsigned BitsPerElement) {
4022 // Signed 16-bit values can be replicated using VREPI.
4023 int64_t SignedValue = SignExtend64(Value, BitsPerElement);
4024 if (isInt<16>(SignedValue)) {
4025 MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement),
4026 SystemZ::VectorBits / BitsPerElement);
4027 SDValue Op = DAG.getNode(SystemZISD::REPLICATE, DL, VecVT,
4028 DAG.getConstant(SignedValue, DL, MVT::i32));
4029 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4031 // See whether rotating the constant left some N places gives a value that
4032 // is one less than a power of 2 (i.e. all zeros followed by all ones).
4033 // If so we can use VGM.
4034 unsigned Start, End;
4035 if (TII->isRxSBGMask(Value, BitsPerElement, Start, End)) {
4036 // isRxSBGMask returns the bit numbers for a full 64-bit value,
4037 // with 0 denoting 1 << 63 and 63 denoting 1. Convert them to
4038 // bit numbers for an BitsPerElement value, so that 0 denotes
4039 // 1 << (BitsPerElement-1).
4040 Start -= 64 - BitsPerElement;
4041 End -= 64 - BitsPerElement;
4042 MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement),
4043 SystemZ::VectorBits / BitsPerElement);
4044 SDValue Op = DAG.getNode(SystemZISD::ROTATE_MASK, DL, VecVT,
4045 DAG.getConstant(Start, DL, MVT::i32),
4046 DAG.getConstant(End, DL, MVT::i32));
4047 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4052 // If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually
4053 // better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for
4054 // the non-EXTRACT_VECTOR_ELT elements. See if the given BUILD_VECTOR
4055 // would benefit from this representation and return it if so.
4056 static SDValue tryBuildVectorShuffle(SelectionDAG &DAG,
4057 BuildVectorSDNode *BVN) {
4058 EVT VT = BVN->getValueType(0);
4059 unsigned NumElements = VT.getVectorNumElements();
4061 // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation
4062 // on byte vectors. If there are non-EXTRACT_VECTOR_ELT elements that still
4063 // need a BUILD_VECTOR, add an additional placeholder operand for that
4064 // BUILD_VECTOR and store its operands in ResidueOps.
4065 GeneralShuffle GS(VT);
4066 SmallVector<SDValue, SystemZ::VectorBytes> ResidueOps;
4067 bool FoundOne = false;
4068 for (unsigned I = 0; I < NumElements; ++I) {
4069 SDValue Op = BVN->getOperand(I);
4070 if (Op.getOpcode() == ISD::TRUNCATE)
4071 Op = Op.getOperand(0);
4072 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4073 Op.getOperand(1).getOpcode() == ISD::Constant) {
4074 unsigned Elem = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4075 GS.add(Op.getOperand(0), Elem);
4077 } else if (Op.isUndef()) {
4080 GS.add(SDValue(), ResidueOps.size());
4081 ResidueOps.push_back(BVN->getOperand(I));
4085 // Nothing to do if there are no EXTRACT_VECTOR_ELTs.
4089 // Create the BUILD_VECTOR for the remaining elements, if any.
4090 if (!ResidueOps.empty()) {
4091 while (ResidueOps.size() < NumElements)
4092 ResidueOps.push_back(DAG.getUNDEF(ResidueOps[0].getValueType()));
4093 for (auto &Op : GS.Ops) {
4094 if (!Op.getNode()) {
4095 Op = DAG.getBuildVector(VT, SDLoc(BVN), ResidueOps);
4100 return GS.getNode(DAG, SDLoc(BVN));
4103 // Combine GPR scalar values Elems into a vector of type VT.
4104 static SDValue buildVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
4105 SmallVectorImpl<SDValue> &Elems) {
4106 // See whether there is a single replicated value.
4108 unsigned int NumElements = Elems.size();
4109 unsigned int Count = 0;
4110 for (auto Elem : Elems) {
4111 if (!Elem.isUndef()) {
4112 if (!Single.getNode())
4114 else if (Elem != Single) {
4121 // There are three cases here:
4123 // - if the only defined element is a loaded one, the best sequence
4124 // is a replicating load.
4126 // - otherwise, if the only defined element is an i64 value, we will
4127 // end up with the same VLVGP sequence regardless of whether we short-cut
4128 // for replication or fall through to the later code.
4130 // - otherwise, if the only defined element is an i32 or smaller value,
4131 // we would need 2 instructions to replicate it: VLVGP followed by VREPx.
4132 // This is only a win if the single defined element is used more than once.
4133 // In other cases we're better off using a single VLVGx.
4134 if (Single.getNode() && (Count > 1 || Single.getOpcode() == ISD::LOAD))
4135 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single);
4137 // The best way of building a v2i64 from two i64s is to use VLVGP.
4138 if (VT == MVT::v2i64)
4139 return joinDwords(DAG, DL, Elems[0], Elems[1]);
4141 // Use a 64-bit merge high to combine two doubles.
4142 if (VT == MVT::v2f64)
4143 return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
4145 // Build v4f32 values directly from the FPRs:
4147 // <Axxx> <Bxxx> <Cxxxx> <Dxxx>
4152 if (VT == MVT::v4f32) {
4153 SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
4154 SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[2], Elems[3]);
4155 // Avoid unnecessary undefs by reusing the other operand.
4158 else if (Op23.isUndef())
4160 // Merging identical replications is a no-op.
4161 if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23)
4163 Op01 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op01);
4164 Op23 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op23);
4165 SDValue Op = DAG.getNode(SystemZISD::MERGE_HIGH,
4166 DL, MVT::v2i64, Op01, Op23);
4167 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4170 // Collect the constant terms.
4171 SmallVector<SDValue, SystemZ::VectorBytes> Constants(NumElements, SDValue());
4172 SmallVector<bool, SystemZ::VectorBytes> Done(NumElements, false);
4174 unsigned NumConstants = 0;
4175 for (unsigned I = 0; I < NumElements; ++I) {
4176 SDValue Elem = Elems[I];
4177 if (Elem.getOpcode() == ISD::Constant ||
4178 Elem.getOpcode() == ISD::ConstantFP) {
4180 Constants[I] = Elem;
4184 // If there was at least one constant, fill in the other elements of
4185 // Constants with undefs to get a full vector constant and use that
4186 // as the starting point.
4188 if (NumConstants > 0) {
4189 for (unsigned I = 0; I < NumElements; ++I)
4190 if (!Constants[I].getNode())
4191 Constants[I] = DAG.getUNDEF(Elems[I].getValueType());
4192 Result = DAG.getBuildVector(VT, DL, Constants);
4194 // Otherwise try to use VLVGP to start the sequence in order to
4195 // avoid a false dependency on any previous contents of the vector
4196 // register. This only makes sense if one of the associated elements
4198 unsigned I1 = NumElements / 2 - 1;
4199 unsigned I2 = NumElements - 1;
4200 bool Def1 = !Elems[I1].isUndef();
4201 bool Def2 = !Elems[I2].isUndef();
4203 SDValue Elem1 = Elems[Def1 ? I1 : I2];
4204 SDValue Elem2 = Elems[Def2 ? I2 : I1];
4205 Result = DAG.getNode(ISD::BITCAST, DL, VT,
4206 joinDwords(DAG, DL, Elem1, Elem2));
4210 Result = DAG.getUNDEF(VT);
4213 // Use VLVGx to insert the other elements.
4214 for (unsigned I = 0; I < NumElements; ++I)
4215 if (!Done[I] && !Elems[I].isUndef())
4216 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I],
4217 DAG.getConstant(I, DL, MVT::i32));
4221 SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op,
4222 SelectionDAG &DAG) const {
4223 const SystemZInstrInfo *TII =
4224 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4225 auto *BVN = cast<BuildVectorSDNode>(Op.getNode());
4227 EVT VT = Op.getValueType();
4229 if (BVN->isConstant()) {
4230 // Try using VECTOR GENERATE BYTE MASK. This is the architecturally-
4231 // preferred way of creating all-zero and all-one vectors so give it
4232 // priority over other methods below.
4234 if (tryBuildVectorByteMask(BVN, Mask)) {
4235 SDValue Op = DAG.getNode(SystemZISD::BYTE_MASK, DL, MVT::v16i8,
4236 DAG.getConstant(Mask, DL, MVT::i32));
4237 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4240 // Try using some form of replication.
4241 APInt SplatBits, SplatUndef;
4242 unsigned SplatBitSize;
4244 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
4246 SplatBitSize <= 64) {
4247 // First try assuming that any undefined bits above the highest set bit
4248 // and below the lowest set bit are 1s. This increases the likelihood of
4249 // being able to use a sign-extended element value in VECTOR REPLICATE
4250 // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
4251 uint64_t SplatBitsZ = SplatBits.getZExtValue();
4252 uint64_t SplatUndefZ = SplatUndef.getZExtValue();
4253 uint64_t Lower = (SplatUndefZ
4254 & ((uint64_t(1) << findFirstSet(SplatBitsZ)) - 1));
4255 uint64_t Upper = (SplatUndefZ
4256 & ~((uint64_t(1) << findLastSet(SplatBitsZ)) - 1));
4257 uint64_t Value = SplatBitsZ | Upper | Lower;
4258 SDValue Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value,
4263 // Now try assuming that any undefined bits between the first and
4264 // last defined set bits are set. This increases the chances of
4265 // using a non-wraparound mask.
4266 uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
4267 Value = SplatBitsZ | Middle;
4268 Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value, SplatBitSize);
4273 // Fall back to loading it from memory.
4277 // See if we should use shuffles to construct the vector from other vectors.
4278 if (SDValue Res = tryBuildVectorShuffle(DAG, BVN))
4281 // Detect SCALAR_TO_VECTOR conversions.
4282 if (isOperationLegal(ISD::SCALAR_TO_VECTOR, VT) && isScalarToVector(Op))
4283 return buildScalarToVector(DAG, DL, VT, Op.getOperand(0));
4285 // Otherwise use buildVector to build the vector up from GPRs.
4286 unsigned NumElements = Op.getNumOperands();
4287 SmallVector<SDValue, SystemZ::VectorBytes> Ops(NumElements);
4288 for (unsigned I = 0; I < NumElements; ++I)
4289 Ops[I] = Op.getOperand(I);
4290 return buildVector(DAG, DL, VT, Ops);
4293 SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
4294 SelectionDAG &DAG) const {
4295 auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode());
4297 EVT VT = Op.getValueType();
4298 unsigned NumElements = VT.getVectorNumElements();
4300 if (VSN->isSplat()) {
4301 SDValue Op0 = Op.getOperand(0);
4302 unsigned Index = VSN->getSplatIndex();
4303 assert(Index < VT.getVectorNumElements() &&
4304 "Splat index should be defined and in first operand");
4305 // See whether the value we're splatting is directly available as a scalar.
4306 if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
4307 Op0.getOpcode() == ISD::BUILD_VECTOR)
4308 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index));
4309 // Otherwise keep it as a vector-to-vector operation.
4310 return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0),
4311 DAG.getConstant(Index, DL, MVT::i32));
4314 GeneralShuffle GS(VT);
4315 for (unsigned I = 0; I < NumElements; ++I) {
4316 int Elt = VSN->getMaskElt(I);
4320 GS.add(Op.getOperand(unsigned(Elt) / NumElements),
4321 unsigned(Elt) % NumElements);
4323 return GS.getNode(DAG, SDLoc(VSN));
4326 SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
4327 SelectionDAG &DAG) const {
4329 // Just insert the scalar into element 0 of an undefined vector.
4330 return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL,
4331 Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
4332 Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32));
4335 SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4336 SelectionDAG &DAG) const {
4337 // Handle insertions of floating-point values.
4339 SDValue Op0 = Op.getOperand(0);
4340 SDValue Op1 = Op.getOperand(1);
4341 SDValue Op2 = Op.getOperand(2);
4342 EVT VT = Op.getValueType();
4344 // Insertions into constant indices of a v2f64 can be done using VPDI.
4345 // However, if the inserted value is a bitcast or a constant then it's
4346 // better to use GPRs, as below.
4347 if (VT == MVT::v2f64 &&
4348 Op1.getOpcode() != ISD::BITCAST &&
4349 Op1.getOpcode() != ISD::ConstantFP &&
4350 Op2.getOpcode() == ISD::Constant) {
4351 uint64_t Index = dyn_cast<ConstantSDNode>(Op2)->getZExtValue();
4352 unsigned Mask = VT.getVectorNumElements() - 1;
4357 // Otherwise bitcast to the equivalent integer form and insert via a GPR.
4358 MVT IntVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
4359 MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements());
4360 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT,
4361 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0),
4362 DAG.getNode(ISD::BITCAST, DL, IntVT, Op1), Op2);
4363 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
4367 SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4368 SelectionDAG &DAG) const {
4369 // Handle extractions of floating-point values.
4371 SDValue Op0 = Op.getOperand(0);
4372 SDValue Op1 = Op.getOperand(1);
4373 EVT VT = Op.getValueType();
4374 EVT VecVT = Op0.getValueType();
4376 // Extractions of constant indices can be done directly.
4377 if (auto *CIndexN = dyn_cast<ConstantSDNode>(Op1)) {
4378 uint64_t Index = CIndexN->getZExtValue();
4379 unsigned Mask = VecVT.getVectorNumElements() - 1;
4384 // Otherwise bitcast to the equivalent integer form and extract via a GPR.
4385 MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
4386 MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements());
4387 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntVT,
4388 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1);
4389 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
4393 SystemZTargetLowering::lowerExtendVectorInreg(SDValue Op, SelectionDAG &DAG,
4394 unsigned UnpackHigh) const {
4395 SDValue PackedOp = Op.getOperand(0);
4396 EVT OutVT = Op.getValueType();
4397 EVT InVT = PackedOp.getValueType();
4398 unsigned ToBits = OutVT.getVectorElementType().getSizeInBits();
4399 unsigned FromBits = InVT.getVectorElementType().getSizeInBits();
4402 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(FromBits),
4403 SystemZ::VectorBits / FromBits);
4404 PackedOp = DAG.getNode(UnpackHigh, SDLoc(PackedOp), OutVT, PackedOp);
4405 } while (FromBits != ToBits);
4409 SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG,
4410 unsigned ByScalar) const {
4411 // Look for cases where a vector shift can use the *_BY_SCALAR form.
4412 SDValue Op0 = Op.getOperand(0);
4413 SDValue Op1 = Op.getOperand(1);
4415 EVT VT = Op.getValueType();
4416 unsigned ElemBitSize = VT.getVectorElementType().getSizeInBits();
4418 // See whether the shift vector is a splat represented as BUILD_VECTOR.
4419 if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) {
4420 APInt SplatBits, SplatUndef;
4421 unsigned SplatBitSize;
4423 // Check for constant splats. Use ElemBitSize as the minimum element
4424 // width and reject splats that need wider elements.
4425 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
4426 ElemBitSize, true) &&
4427 SplatBitSize == ElemBitSize) {
4428 SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff,
4430 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4432 // Check for variable splats.
4433 BitVector UndefElements;
4434 SDValue Splat = BVN->getSplatValue(&UndefElements);
4436 // Since i32 is the smallest legal type, we either need a no-op
4438 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat);
4439 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4443 // See whether the shift vector is a splat represented as SHUFFLE_VECTOR,
4444 // and the shift amount is directly available in a GPR.
4445 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) {
4446 if (VSN->isSplat()) {
4447 SDValue VSNOp0 = VSN->getOperand(0);
4448 unsigned Index = VSN->getSplatIndex();
4449 assert(Index < VT.getVectorNumElements() &&
4450 "Splat index should be defined and in first operand");
4451 if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
4452 VSNOp0.getOpcode() == ISD::BUILD_VECTOR) {
4453 // Since i32 is the smallest legal type, we either need a no-op
4455 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
4456 VSNOp0.getOperand(Index));
4457 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4462 // Otherwise just treat the current form as legal.
4466 SDValue SystemZTargetLowering::LowerOperation(SDValue Op,
4467 SelectionDAG &DAG) const {
4468 switch (Op.getOpcode()) {
4469 case ISD::FRAMEADDR:
4470 return lowerFRAMEADDR(Op, DAG);
4471 case ISD::RETURNADDR:
4472 return lowerRETURNADDR(Op, DAG);
4474 return lowerBR_CC(Op, DAG);
4475 case ISD::SELECT_CC:
4476 return lowerSELECT_CC(Op, DAG);
4478 return lowerSETCC(Op, DAG);
4479 case ISD::GlobalAddress:
4480 return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
4481 case ISD::GlobalTLSAddress:
4482 return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
4483 case ISD::BlockAddress:
4484 return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
4485 case ISD::JumpTable:
4486 return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
4487 case ISD::ConstantPool:
4488 return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
4490 return lowerBITCAST(Op, DAG);
4492 return lowerVASTART(Op, DAG);
4494 return lowerVACOPY(Op, DAG);
4495 case ISD::DYNAMIC_STACKALLOC:
4496 return lowerDYNAMIC_STACKALLOC(Op, DAG);
4497 case ISD::GET_DYNAMIC_AREA_OFFSET:
4498 return lowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
4499 case ISD::SMUL_LOHI:
4500 return lowerSMUL_LOHI(Op, DAG);
4501 case ISD::UMUL_LOHI:
4502 return lowerUMUL_LOHI(Op, DAG);
4504 return lowerSDIVREM(Op, DAG);
4506 return lowerUDIVREM(Op, DAG);
4508 return lowerOR(Op, DAG);
4510 return lowerCTPOP(Op, DAG);
4511 case ISD::ATOMIC_FENCE:
4512 return lowerATOMIC_FENCE(Op, DAG);
4513 case ISD::ATOMIC_SWAP:
4514 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_SWAPW);
4515 case ISD::ATOMIC_STORE:
4516 return lowerATOMIC_STORE(Op, DAG);
4517 case ISD::ATOMIC_LOAD:
4518 return lowerATOMIC_LOAD(Op, DAG);
4519 case ISD::ATOMIC_LOAD_ADD:
4520 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
4521 case ISD::ATOMIC_LOAD_SUB:
4522 return lowerATOMIC_LOAD_SUB(Op, DAG);
4523 case ISD::ATOMIC_LOAD_AND:
4524 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
4525 case ISD::ATOMIC_LOAD_OR:
4526 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
4527 case ISD::ATOMIC_LOAD_XOR:
4528 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
4529 case ISD::ATOMIC_LOAD_NAND:
4530 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
4531 case ISD::ATOMIC_LOAD_MIN:
4532 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
4533 case ISD::ATOMIC_LOAD_MAX:
4534 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
4535 case ISD::ATOMIC_LOAD_UMIN:
4536 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
4537 case ISD::ATOMIC_LOAD_UMAX:
4538 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
4539 case ISD::ATOMIC_CMP_SWAP:
4540 return lowerATOMIC_CMP_SWAP(Op, DAG);
4541 case ISD::STACKSAVE:
4542 return lowerSTACKSAVE(Op, DAG);
4543 case ISD::STACKRESTORE:
4544 return lowerSTACKRESTORE(Op, DAG);
4546 return lowerPREFETCH(Op, DAG);
4547 case ISD::INTRINSIC_W_CHAIN:
4548 return lowerINTRINSIC_W_CHAIN(Op, DAG);
4549 case ISD::INTRINSIC_WO_CHAIN:
4550 return lowerINTRINSIC_WO_CHAIN(Op, DAG);
4551 case ISD::BUILD_VECTOR:
4552 return lowerBUILD_VECTOR(Op, DAG);
4553 case ISD::VECTOR_SHUFFLE:
4554 return lowerVECTOR_SHUFFLE(Op, DAG);
4555 case ISD::SCALAR_TO_VECTOR:
4556 return lowerSCALAR_TO_VECTOR(Op, DAG);
4557 case ISD::INSERT_VECTOR_ELT:
4558 return lowerINSERT_VECTOR_ELT(Op, DAG);
4559 case ISD::EXTRACT_VECTOR_ELT:
4560 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4561 case ISD::SIGN_EXTEND_VECTOR_INREG:
4562 return lowerExtendVectorInreg(Op, DAG, SystemZISD::UNPACK_HIGH);
4563 case ISD::ZERO_EXTEND_VECTOR_INREG:
4564 return lowerExtendVectorInreg(Op, DAG, SystemZISD::UNPACKL_HIGH);
4566 return lowerShift(Op, DAG, SystemZISD::VSHL_BY_SCALAR);
4568 return lowerShift(Op, DAG, SystemZISD::VSRL_BY_SCALAR);
4570 return lowerShift(Op, DAG, SystemZISD::VSRA_BY_SCALAR);
4572 llvm_unreachable("Unexpected node to lower");
4576 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
4577 #define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME
4578 switch ((SystemZISD::NodeType)Opcode) {
4579 case SystemZISD::FIRST_NUMBER: break;
4585 OPCODE(PCREL_WRAPPER);
4586 OPCODE(PCREL_OFFSET);
4592 OPCODE(SELECT_CCMASK);
4593 OPCODE(ADJDYNALLOC);
4594 OPCODE(EXTRACT_ACCESS);
4596 OPCODE(UMUL_LOHI64);
4613 OPCODE(SEARCH_STRING);
4618 OPCODE(TBEGIN_NOFLOAT);
4621 OPCODE(ROTATE_MASK);
4623 OPCODE(JOIN_DWORDS);
4628 OPCODE(PERMUTE_DWORDS);
4633 OPCODE(UNPACK_HIGH);
4634 OPCODE(UNPACKL_HIGH);
4636 OPCODE(UNPACKL_LOW);
4637 OPCODE(VSHL_BY_SCALAR);
4638 OPCODE(VSRL_BY_SCALAR);
4639 OPCODE(VSRA_BY_SCALAR);
4667 OPCODE(ATOMIC_SWAPW);
4668 OPCODE(ATOMIC_LOADW_ADD);
4669 OPCODE(ATOMIC_LOADW_SUB);
4670 OPCODE(ATOMIC_LOADW_AND);
4671 OPCODE(ATOMIC_LOADW_OR);
4672 OPCODE(ATOMIC_LOADW_XOR);
4673 OPCODE(ATOMIC_LOADW_NAND);
4674 OPCODE(ATOMIC_LOADW_MIN);
4675 OPCODE(ATOMIC_LOADW_MAX);
4676 OPCODE(ATOMIC_LOADW_UMIN);
4677 OPCODE(ATOMIC_LOADW_UMAX);
4678 OPCODE(ATOMIC_CMP_SWAPW);
4687 // Return true if VT is a vector whose elements are a whole number of bytes
4689 static bool canTreatAsByteVector(EVT VT) {
4690 return VT.isVector() && VT.getVectorElementType().getSizeInBits() % 8 == 0;
4693 // Try to simplify an EXTRACT_VECTOR_ELT from a vector of type VecVT
4694 // producing a result of type ResVT. Op is a possibly bitcast version
4695 // of the input vector and Index is the index (based on type VecVT) that
4696 // should be extracted. Return the new extraction if a simplification
4697 // was possible or if Force is true.
4698 SDValue SystemZTargetLowering::combineExtract(const SDLoc &DL, EVT ResVT,
4699 EVT VecVT, SDValue Op,
4701 DAGCombinerInfo &DCI,
4703 SelectionDAG &DAG = DCI.DAG;
4705 // The number of bytes being extracted.
4706 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
4709 unsigned Opcode = Op.getOpcode();
4710 if (Opcode == ISD::BITCAST)
4711 // Look through bitcasts.
4712 Op = Op.getOperand(0);
4713 else if (Opcode == ISD::VECTOR_SHUFFLE &&
4714 canTreatAsByteVector(Op.getValueType())) {
4715 // Get a VPERM-like permute mask and see whether the bytes covered
4716 // by the extracted element are a contiguous sequence from one
4718 SmallVector<int, SystemZ::VectorBytes> Bytes;
4719 getVPermMask(cast<ShuffleVectorSDNode>(Op), Bytes);
4721 if (!getShuffleInput(Bytes, Index * BytesPerElement,
4722 BytesPerElement, First))
4725 return DAG.getUNDEF(ResVT);
4726 // Make sure the contiguous sequence starts at a multiple of the
4727 // original element size.
4728 unsigned Byte = unsigned(First) % Bytes.size();
4729 if (Byte % BytesPerElement != 0)
4731 // We can get the extracted value directly from an input.
4732 Index = Byte / BytesPerElement;
4733 Op = Op.getOperand(unsigned(First) / Bytes.size());
4735 } else if (Opcode == ISD::BUILD_VECTOR &&
4736 canTreatAsByteVector(Op.getValueType())) {
4737 // We can only optimize this case if the BUILD_VECTOR elements are
4738 // at least as wide as the extracted value.
4739 EVT OpVT = Op.getValueType();
4740 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
4741 if (OpBytesPerElement < BytesPerElement)
4743 // Make sure that the least-significant bit of the extracted value
4744 // is the least significant bit of an input.
4745 unsigned End = (Index + 1) * BytesPerElement;
4746 if (End % OpBytesPerElement != 0)
4748 // We're extracting the low part of one operand of the BUILD_VECTOR.
4749 Op = Op.getOperand(End / OpBytesPerElement - 1);
4750 if (!Op.getValueType().isInteger()) {
4751 EVT VT = MVT::getIntegerVT(Op.getValueType().getSizeInBits());
4752 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
4753 DCI.AddToWorklist(Op.getNode());
4755 EVT VT = MVT::getIntegerVT(ResVT.getSizeInBits());
4756 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
4758 DCI.AddToWorklist(Op.getNode());
4759 Op = DAG.getNode(ISD::BITCAST, DL, ResVT, Op);
4762 } else if ((Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
4763 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
4764 Opcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
4765 canTreatAsByteVector(Op.getValueType()) &&
4766 canTreatAsByteVector(Op.getOperand(0).getValueType())) {
4767 // Make sure that only the unextended bits are significant.
4768 EVT ExtVT = Op.getValueType();
4769 EVT OpVT = Op.getOperand(0).getValueType();
4770 unsigned ExtBytesPerElement = ExtVT.getVectorElementType().getStoreSize();
4771 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
4772 unsigned Byte = Index * BytesPerElement;
4773 unsigned SubByte = Byte % ExtBytesPerElement;
4774 unsigned MinSubByte = ExtBytesPerElement - OpBytesPerElement;
4775 if (SubByte < MinSubByte ||
4776 SubByte + BytesPerElement > ExtBytesPerElement)
4778 // Get the byte offset of the unextended element
4779 Byte = Byte / ExtBytesPerElement * OpBytesPerElement;
4780 // ...then add the byte offset relative to that element.
4781 Byte += SubByte - MinSubByte;
4782 if (Byte % BytesPerElement != 0)
4784 Op = Op.getOperand(0);
4785 Index = Byte / BytesPerElement;
4791 if (Op.getValueType() != VecVT) {
4792 Op = DAG.getNode(ISD::BITCAST, DL, VecVT, Op);
4793 DCI.AddToWorklist(Op.getNode());
4795 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Op,
4796 DAG.getConstant(Index, DL, MVT::i32));
4801 // Optimize vector operations in scalar value Op on the basis that Op
4802 // is truncated to TruncVT.
4803 SDValue SystemZTargetLowering::combineTruncateExtract(
4804 const SDLoc &DL, EVT TruncVT, SDValue Op, DAGCombinerInfo &DCI) const {
4805 // If we have (trunc (extract_vector_elt X, Y)), try to turn it into
4806 // (extract_vector_elt (bitcast X), Y'), where (bitcast X) has elements
4808 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4809 TruncVT.getSizeInBits() % 8 == 0) {
4810 SDValue Vec = Op.getOperand(0);
4811 EVT VecVT = Vec.getValueType();
4812 if (canTreatAsByteVector(VecVT)) {
4813 if (auto *IndexN = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
4814 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
4815 unsigned TruncBytes = TruncVT.getStoreSize();
4816 if (BytesPerElement % TruncBytes == 0) {
4817 // Calculate the value of Y' in the above description. We are
4818 // splitting the original elements into Scale equal-sized pieces
4819 // and for truncation purposes want the last (least-significant)
4820 // of these pieces for IndexN. This is easiest to do by calculating
4821 // the start index of the following element and then subtracting 1.
4822 unsigned Scale = BytesPerElement / TruncBytes;
4823 unsigned NewIndex = (IndexN->getZExtValue() + 1) * Scale - 1;
4825 // Defer the creation of the bitcast from X to combineExtract,
4826 // which might be able to optimize the extraction.
4827 VecVT = MVT::getVectorVT(MVT::getIntegerVT(TruncBytes * 8),
4828 VecVT.getStoreSize() / TruncBytes);
4829 EVT ResVT = (TruncBytes < 4 ? MVT::i32 : TruncVT);
4830 return combineExtract(DL, ResVT, VecVT, Vec, NewIndex, DCI, true);
4838 SDValue SystemZTargetLowering::combineSIGN_EXTEND(
4839 SDNode *N, DAGCombinerInfo &DCI) const {
4840 // Convert (sext (ashr (shl X, C1), C2)) to
4841 // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
4842 // cheap as narrower ones.
4843 SelectionDAG &DAG = DCI.DAG;
4844 SDValue N0 = N->getOperand(0);
4845 EVT VT = N->getValueType(0);
4846 if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
4847 auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4848 SDValue Inner = N0.getOperand(0);
4849 if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
4850 if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
4851 unsigned Extra = (VT.getSizeInBits() -
4852 N0.getValueType().getSizeInBits());
4853 unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
4854 unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
4855 EVT ShiftVT = N0.getOperand(1).getValueType();
4856 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
4857 Inner.getOperand(0));
4858 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
4859 DAG.getConstant(NewShlAmt, SDLoc(Inner),
4861 return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
4862 DAG.getConstant(NewSraAmt, SDLoc(N0), ShiftVT));
4869 SDValue SystemZTargetLowering::combineMERGE(
4870 SDNode *N, DAGCombinerInfo &DCI) const {
4871 SelectionDAG &DAG = DCI.DAG;
4872 unsigned Opcode = N->getOpcode();
4873 SDValue Op0 = N->getOperand(0);
4874 SDValue Op1 = N->getOperand(1);
4875 if (Op0.getOpcode() == ISD::BITCAST)
4876 Op0 = Op0.getOperand(0);
4877 if (Op0.getOpcode() == SystemZISD::BYTE_MASK &&
4878 cast<ConstantSDNode>(Op0.getOperand(0))->getZExtValue() == 0) {
4879 // (z_merge_* 0, 0) -> 0. This is mostly useful for using VLLEZF
4881 if (Op1 == N->getOperand(0))
4883 // (z_merge_? 0, X) -> (z_unpackl_? 0, X).
4884 EVT VT = Op1.getValueType();
4885 unsigned ElemBytes = VT.getVectorElementType().getStoreSize();
4886 if (ElemBytes <= 4) {
4887 Opcode = (Opcode == SystemZISD::MERGE_HIGH ?
4888 SystemZISD::UNPACKL_HIGH : SystemZISD::UNPACKL_LOW);
4889 EVT InVT = VT.changeVectorElementTypeToInteger();
4890 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(ElemBytes * 16),
4891 SystemZ::VectorBytes / ElemBytes / 2);
4893 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), InVT, Op1);
4894 DCI.AddToWorklist(Op1.getNode());
4896 SDValue Op = DAG.getNode(Opcode, SDLoc(N), OutVT, Op1);
4897 DCI.AddToWorklist(Op.getNode());
4898 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
4904 SDValue SystemZTargetLowering::combineSTORE(
4905 SDNode *N, DAGCombinerInfo &DCI) const {
4906 SelectionDAG &DAG = DCI.DAG;
4907 auto *SN = cast<StoreSDNode>(N);
4908 auto &Op1 = N->getOperand(1);
4909 EVT MemVT = SN->getMemoryVT();
4910 // If we have (truncstoreiN (extract_vector_elt X, Y), Z) then it is better
4911 // for the extraction to be done on a vMiN value, so that we can use VSTE.
4912 // If X has wider elements then convert it to:
4913 // (truncstoreiN (extract_vector_elt (bitcast X), Y2), Z).
4914 if (MemVT.isInteger()) {
4916 combineTruncateExtract(SDLoc(N), MemVT, SN->getValue(), DCI)) {
4917 DCI.AddToWorklist(Value.getNode());
4919 // Rewrite the store with the new form of stored value.
4920 return DAG.getTruncStore(SN->getChain(), SDLoc(SN), Value,
4921 SN->getBasePtr(), SN->getMemoryVT(),
4922 SN->getMemOperand());
4925 // Combine STORE (BSWAP) into STRVH/STRV/STRVG
4926 // See comment in combineBSWAP about volatile accesses.
4927 if (!SN->isVolatile() &&
4928 Op1.getOpcode() == ISD::BSWAP &&
4929 Op1.getNode()->hasOneUse() &&
4930 (Op1.getValueType() == MVT::i16 ||
4931 Op1.getValueType() == MVT::i32 ||
4932 Op1.getValueType() == MVT::i64)) {
4934 SDValue BSwapOp = Op1.getOperand(0);
4936 if (BSwapOp.getValueType() == MVT::i16)
4937 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), MVT::i32, BSwapOp);
4940 N->getOperand(0), BSwapOp, N->getOperand(2),
4941 DAG.getValueType(Op1.getValueType())
4945 DAG.getMemIntrinsicNode(SystemZISD::STRV, SDLoc(N), DAG.getVTList(MVT::Other),
4946 Ops, MemVT, SN->getMemOperand());
4951 SDValue SystemZTargetLowering::combineEXTRACT_VECTOR_ELT(
4952 SDNode *N, DAGCombinerInfo &DCI) const {
4953 // Try to simplify a vector extraction.
4954 if (auto *IndexN = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
4955 SDValue Op0 = N->getOperand(0);
4956 EVT VecVT = Op0.getValueType();
4957 return combineExtract(SDLoc(N), N->getValueType(0), VecVT, Op0,
4958 IndexN->getZExtValue(), DCI, false);
4963 SDValue SystemZTargetLowering::combineJOIN_DWORDS(
4964 SDNode *N, DAGCombinerInfo &DCI) const {
4965 SelectionDAG &DAG = DCI.DAG;
4966 // (join_dwords X, X) == (replicate X)
4967 if (N->getOperand(0) == N->getOperand(1))
4968 return DAG.getNode(SystemZISD::REPLICATE, SDLoc(N), N->getValueType(0),
4973 SDValue SystemZTargetLowering::combineFP_ROUND(
4974 SDNode *N, DAGCombinerInfo &DCI) const {
4975 // (fround (extract_vector_elt X 0))
4976 // (fround (extract_vector_elt X 1)) ->
4977 // (extract_vector_elt (VROUND X) 0)
4978 // (extract_vector_elt (VROUND X) 1)
4980 // This is a special case since the target doesn't really support v2f32s.
4981 SelectionDAG &DAG = DCI.DAG;
4982 SDValue Op0 = N->getOperand(0);
4983 if (N->getValueType(0) == MVT::f32 &&
4985 Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4986 Op0.getOperand(0).getValueType() == MVT::v2f64 &&
4987 Op0.getOperand(1).getOpcode() == ISD::Constant &&
4988 cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue() == 0) {
4989 SDValue Vec = Op0.getOperand(0);
4990 for (auto *U : Vec->uses()) {
4991 if (U != Op0.getNode() &&
4993 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4994 U->getOperand(0) == Vec &&
4995 U->getOperand(1).getOpcode() == ISD::Constant &&
4996 cast<ConstantSDNode>(U->getOperand(1))->getZExtValue() == 1) {
4997 SDValue OtherRound = SDValue(*U->use_begin(), 0);
4998 if (OtherRound.getOpcode() == ISD::FP_ROUND &&
4999 OtherRound.getOperand(0) == SDValue(U, 0) &&
5000 OtherRound.getValueType() == MVT::f32) {
5001 SDValue VRound = DAG.getNode(SystemZISD::VROUND, SDLoc(N),
5003 DCI.AddToWorklist(VRound.getNode());
5005 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f32,
5006 VRound, DAG.getConstant(2, SDLoc(U), MVT::i32));
5007 DCI.AddToWorklist(Extract1.getNode());
5008 DAG.ReplaceAllUsesOfValueWith(OtherRound, Extract1);
5010 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f32,
5011 VRound, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
5020 SDValue SystemZTargetLowering::combineBSWAP(
5021 SDNode *N, DAGCombinerInfo &DCI) const {
5022 SelectionDAG &DAG = DCI.DAG;
5023 // Combine BSWAP (LOAD) into LRVH/LRV/LRVG
5024 // These loads are allowed to access memory multiple times, and so we must check
5025 // that the loads are not volatile before performing the combine.
5026 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
5027 N->getOperand(0).hasOneUse() &&
5028 (N->getValueType(0) == MVT::i16 || N->getValueType(0) == MVT::i32 ||
5029 N->getValueType(0) == MVT::i64) &&
5030 !cast<LoadSDNode>(N->getOperand(0))->isVolatile()) {
5031 SDValue Load = N->getOperand(0);
5032 LoadSDNode *LD = cast<LoadSDNode>(Load);
5034 // Create the byte-swapping load.
5036 LD->getChain(), // Chain
5037 LD->getBasePtr(), // Ptr
5038 DAG.getValueType(N->getValueType(0)) // VT
5041 DAG.getMemIntrinsicNode(SystemZISD::LRV, SDLoc(N),
5042 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
5043 MVT::i64 : MVT::i32, MVT::Other),
5044 Ops, LD->getMemoryVT(), LD->getMemOperand());
5046 // If this is an i16 load, insert the truncate.
5047 SDValue ResVal = BSLoad;
5048 if (N->getValueType(0) == MVT::i16)
5049 ResVal = DAG.getNode(ISD::TRUNCATE, SDLoc(N), MVT::i16, BSLoad);
5051 // First, combine the bswap away. This makes the value produced by the
5053 DCI.CombineTo(N, ResVal);
5055 // Next, combine the load away, we give it a bogus result value but a real
5056 // chain result. The result value is dead because the bswap is dead.
5057 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
5059 // Return N so it doesn't get rechecked!
5060 return SDValue(N, 0);
5065 SDValue SystemZTargetLowering::combineSHIFTROT(
5066 SDNode *N, DAGCombinerInfo &DCI) const {
5068 SelectionDAG &DAG = DCI.DAG;
5070 // Shift/rotate instructions only use the last 6 bits of the second operand
5071 // register. If the second operand is the result of an AND with an immediate
5072 // value that has its last 6 bits set, we can safely remove the AND operation.
5073 SDValue N1 = N->getOperand(1);
5074 if (N1.getOpcode() == ISD::AND) {
5075 auto *AndMask = dyn_cast<ConstantSDNode>(N1.getOperand(1));
5077 // The AND mask is constant
5079 auto AmtVal = AndMask->getZExtValue();
5081 // Bottom 6 bits are set
5082 if ((AmtVal & 0x3f) == 0x3f) {
5083 SDValue AndOp = N1->getOperand(0);
5085 // This is the only use, so remove the node
5086 if (N1.hasOneUse()) {
5087 // Combine the AND away
5088 DCI.CombineTo(N1.getNode(), AndOp);
5090 // Return N so it isn't rechecked
5091 return SDValue(N, 0);
5093 // The node will be reused, so create a new node for this one use
5095 SDValue Replace = DAG.getNode(N->getOpcode(), SDLoc(N),
5096 N->getValueType(0), N->getOperand(0),
5098 DCI.AddToWorklist(Replace.getNode());
5109 SDValue SystemZTargetLowering::PerformDAGCombine(SDNode *N,
5110 DAGCombinerInfo &DCI) const {
5111 switch(N->getOpcode()) {
5113 case ISD::SIGN_EXTEND: return combineSIGN_EXTEND(N, DCI);
5114 case SystemZISD::MERGE_HIGH:
5115 case SystemZISD::MERGE_LOW: return combineMERGE(N, DCI);
5116 case ISD::STORE: return combineSTORE(N, DCI);
5117 case ISD::EXTRACT_VECTOR_ELT: return combineEXTRACT_VECTOR_ELT(N, DCI);
5118 case SystemZISD::JOIN_DWORDS: return combineJOIN_DWORDS(N, DCI);
5119 case ISD::FP_ROUND: return combineFP_ROUND(N, DCI);
5120 case ISD::BSWAP: return combineBSWAP(N, DCI);
5124 case ISD::ROTL: return combineSHIFTROT(N, DCI);
5130 //===----------------------------------------------------------------------===//
5132 //===----------------------------------------------------------------------===//
5134 // Create a new basic block after MBB.
5135 static MachineBasicBlock *emitBlockAfter(MachineBasicBlock *MBB) {
5136 MachineFunction &MF = *MBB->getParent();
5137 MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(MBB->getBasicBlock());
5138 MF.insert(std::next(MachineFunction::iterator(MBB)), NewMBB);
5142 // Split MBB after MI and return the new block (the one that contains
5143 // instructions after MI).
5144 static MachineBasicBlock *splitBlockAfter(MachineBasicBlock::iterator MI,
5145 MachineBasicBlock *MBB) {
5146 MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
5147 NewMBB->splice(NewMBB->begin(), MBB,
5148 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
5149 NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
5153 // Split MBB before MI and return the new block (the one that contains MI).
5154 static MachineBasicBlock *splitBlockBefore(MachineBasicBlock::iterator MI,
5155 MachineBasicBlock *MBB) {
5156 MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
5157 NewMBB->splice(NewMBB->begin(), MBB, MI, MBB->end());
5158 NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
5162 // Force base value Base into a register before MI. Return the register.
5163 static unsigned forceReg(MachineInstr &MI, MachineOperand &Base,
5164 const SystemZInstrInfo *TII) {
5166 return Base.getReg();
5168 MachineBasicBlock *MBB = MI.getParent();
5169 MachineFunction &MF = *MBB->getParent();
5170 MachineRegisterInfo &MRI = MF.getRegInfo();
5172 unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
5173 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LA), Reg)
5180 // Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
5182 SystemZTargetLowering::emitSelect(MachineInstr &MI,
5183 MachineBasicBlock *MBB) const {
5184 const SystemZInstrInfo *TII =
5185 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5187 unsigned DestReg = MI.getOperand(0).getReg();
5188 unsigned TrueReg = MI.getOperand(1).getReg();
5189 unsigned FalseReg = MI.getOperand(2).getReg();
5190 unsigned CCValid = MI.getOperand(3).getImm();
5191 unsigned CCMask = MI.getOperand(4).getImm();
5192 DebugLoc DL = MI.getDebugLoc();
5194 MachineBasicBlock *StartMBB = MBB;
5195 MachineBasicBlock *JoinMBB = splitBlockBefore(MI, MBB);
5196 MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
5199 // BRC CCMask, JoinMBB
5200 // # fallthrough to FalseMBB
5202 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5203 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
5204 MBB->addSuccessor(JoinMBB);
5205 MBB->addSuccessor(FalseMBB);
5208 // # fallthrough to JoinMBB
5210 MBB->addSuccessor(JoinMBB);
5213 // %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
5216 BuildMI(*MBB, MI, DL, TII->get(SystemZ::PHI), DestReg)
5217 .addReg(TrueReg).addMBB(StartMBB)
5218 .addReg(FalseReg).addMBB(FalseMBB);
5220 MI.eraseFromParent();
5224 // Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
5225 // StoreOpcode is the store to use and Invert says whether the store should
5226 // happen when the condition is false rather than true. If a STORE ON
5227 // CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
5228 MachineBasicBlock *SystemZTargetLowering::emitCondStore(MachineInstr &MI,
5229 MachineBasicBlock *MBB,
5230 unsigned StoreOpcode,
5231 unsigned STOCOpcode,
5232 bool Invert) const {
5233 const SystemZInstrInfo *TII =
5234 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5236 unsigned SrcReg = MI.getOperand(0).getReg();
5237 MachineOperand Base = MI.getOperand(1);
5238 int64_t Disp = MI.getOperand(2).getImm();
5239 unsigned IndexReg = MI.getOperand(3).getReg();
5240 unsigned CCValid = MI.getOperand(4).getImm();
5241 unsigned CCMask = MI.getOperand(5).getImm();
5242 DebugLoc DL = MI.getDebugLoc();
5244 StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
5246 // Use STOCOpcode if possible. We could use different store patterns in
5247 // order to avoid matching the index register, but the performance trade-offs
5248 // might be more complicated in that case.
5249 if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) {
5252 BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
5253 .addReg(SrcReg).addOperand(Base).addImm(Disp)
5254 .addImm(CCValid).addImm(CCMask);
5255 MI.eraseFromParent();
5259 // Get the condition needed to branch around the store.
5263 MachineBasicBlock *StartMBB = MBB;
5264 MachineBasicBlock *JoinMBB = splitBlockBefore(MI, MBB);
5265 MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
5268 // BRC CCMask, JoinMBB
5269 // # fallthrough to FalseMBB
5271 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5272 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
5273 MBB->addSuccessor(JoinMBB);
5274 MBB->addSuccessor(FalseMBB);
5277 // store %SrcReg, %Disp(%Index,%Base)
5278 // # fallthrough to JoinMBB
5280 BuildMI(MBB, DL, TII->get(StoreOpcode))
5281 .addReg(SrcReg).addOperand(Base).addImm(Disp).addReg(IndexReg);
5282 MBB->addSuccessor(JoinMBB);
5284 MI.eraseFromParent();
5288 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_LOAD{,W}_*
5289 // or ATOMIC_SWAP{,W} instruction MI. BinOpcode is the instruction that
5290 // performs the binary operation elided by "*", or 0 for ATOMIC_SWAP{,W}.
5291 // BitSize is the width of the field in bits, or 0 if this is a partword
5292 // ATOMIC_LOADW_* or ATOMIC_SWAPW instruction, in which case the bitsize
5293 // is one of the operands. Invert says whether the field should be
5294 // inverted after performing BinOpcode (e.g. for NAND).
5295 MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadBinary(
5296 MachineInstr &MI, MachineBasicBlock *MBB, unsigned BinOpcode,
5297 unsigned BitSize, bool Invert) const {
5298 MachineFunction &MF = *MBB->getParent();
5299 const SystemZInstrInfo *TII =
5300 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5301 MachineRegisterInfo &MRI = MF.getRegInfo();
5302 bool IsSubWord = (BitSize < 32);
5304 // Extract the operands. Base can be a register or a frame index.
5305 // Src2 can be a register or immediate.
5306 unsigned Dest = MI.getOperand(0).getReg();
5307 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
5308 int64_t Disp = MI.getOperand(2).getImm();
5309 MachineOperand Src2 = earlyUseOperand(MI.getOperand(3));
5310 unsigned BitShift = (IsSubWord ? MI.getOperand(4).getReg() : 0);
5311 unsigned NegBitShift = (IsSubWord ? MI.getOperand(5).getReg() : 0);
5312 DebugLoc DL = MI.getDebugLoc();
5314 BitSize = MI.getOperand(6).getImm();
5316 // Subword operations use 32-bit registers.
5317 const TargetRegisterClass *RC = (BitSize <= 32 ?
5318 &SystemZ::GR32BitRegClass :
5319 &SystemZ::GR64BitRegClass);
5320 unsigned LOpcode = BitSize <= 32 ? SystemZ::L : SystemZ::LG;
5321 unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
5323 // Get the right opcodes for the displacement.
5324 LOpcode = TII->getOpcodeForOffset(LOpcode, Disp);
5325 CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
5326 assert(LOpcode && CSOpcode && "Displacement out of range");
5328 // Create virtual registers for temporary results.
5329 unsigned OrigVal = MRI.createVirtualRegister(RC);
5330 unsigned OldVal = MRI.createVirtualRegister(RC);
5331 unsigned NewVal = (BinOpcode || IsSubWord ?
5332 MRI.createVirtualRegister(RC) : Src2.getReg());
5333 unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
5334 unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
5336 // Insert a basic block for the main loop.
5337 MachineBasicBlock *StartMBB = MBB;
5338 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5339 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5343 // %OrigVal = L Disp(%Base)
5344 // # fall through to LoopMMB
5346 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
5347 .addOperand(Base).addImm(Disp).addReg(0);
5348 MBB->addSuccessor(LoopMBB);
5351 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
5352 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
5353 // %RotatedNewVal = OP %RotatedOldVal, %Src2
5354 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
5355 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
5357 // # fall through to DoneMMB
5359 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
5360 .addReg(OrigVal).addMBB(StartMBB)
5361 .addReg(Dest).addMBB(LoopMBB);
5363 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
5364 .addReg(OldVal).addReg(BitShift).addImm(0);
5366 // Perform the operation normally and then invert every bit of the field.
5367 unsigned Tmp = MRI.createVirtualRegister(RC);
5368 BuildMI(MBB, DL, TII->get(BinOpcode), Tmp)
5369 .addReg(RotatedOldVal).addOperand(Src2);
5371 // XILF with the upper BitSize bits set.
5372 BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
5373 .addReg(Tmp).addImm(-1U << (32 - BitSize));
5375 // Use LCGR and add -1 to the result, which is more compact than
5376 // an XILF, XILH pair.
5377 unsigned Tmp2 = MRI.createVirtualRegister(RC);
5378 BuildMI(MBB, DL, TII->get(SystemZ::LCGR), Tmp2).addReg(Tmp);
5379 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), RotatedNewVal)
5380 .addReg(Tmp2).addImm(-1);
5382 } else if (BinOpcode)
5383 // A simply binary operation.
5384 BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
5385 .addReg(RotatedOldVal).addOperand(Src2);
5387 // Use RISBG to rotate Src2 into position and use it to replace the
5388 // field in RotatedOldVal.
5389 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
5390 .addReg(RotatedOldVal).addReg(Src2.getReg())
5391 .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize);
5393 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
5394 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
5395 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
5396 .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
5397 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5398 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
5399 MBB->addSuccessor(LoopMBB);
5400 MBB->addSuccessor(DoneMBB);
5402 MI.eraseFromParent();
5406 // Implement EmitInstrWithCustomInserter for pseudo
5407 // ATOMIC_LOAD{,W}_{,U}{MIN,MAX} instruction MI. CompareOpcode is the
5408 // instruction that should be used to compare the current field with the
5409 // minimum or maximum value. KeepOldMask is the BRC condition-code mask
5410 // for when the current field should be kept. BitSize is the width of
5411 // the field in bits, or 0 if this is a partword ATOMIC_LOADW_* instruction.
5412 MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadMinMax(
5413 MachineInstr &MI, MachineBasicBlock *MBB, unsigned CompareOpcode,
5414 unsigned KeepOldMask, unsigned BitSize) const {
5415 MachineFunction &MF = *MBB->getParent();
5416 const SystemZInstrInfo *TII =
5417 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5418 MachineRegisterInfo &MRI = MF.getRegInfo();
5419 bool IsSubWord = (BitSize < 32);
5421 // Extract the operands. Base can be a register or a frame index.
5422 unsigned Dest = MI.getOperand(0).getReg();
5423 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
5424 int64_t Disp = MI.getOperand(2).getImm();
5425 unsigned Src2 = MI.getOperand(3).getReg();
5426 unsigned BitShift = (IsSubWord ? MI.getOperand(4).getReg() : 0);
5427 unsigned NegBitShift = (IsSubWord ? MI.getOperand(5).getReg() : 0);
5428 DebugLoc DL = MI.getDebugLoc();
5430 BitSize = MI.getOperand(6).getImm();
5432 // Subword operations use 32-bit registers.
5433 const TargetRegisterClass *RC = (BitSize <= 32 ?
5434 &SystemZ::GR32BitRegClass :
5435 &SystemZ::GR64BitRegClass);
5436 unsigned LOpcode = BitSize <= 32 ? SystemZ::L : SystemZ::LG;
5437 unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
5439 // Get the right opcodes for the displacement.
5440 LOpcode = TII->getOpcodeForOffset(LOpcode, Disp);
5441 CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
5442 assert(LOpcode && CSOpcode && "Displacement out of range");
5444 // Create virtual registers for temporary results.
5445 unsigned OrigVal = MRI.createVirtualRegister(RC);
5446 unsigned OldVal = MRI.createVirtualRegister(RC);
5447 unsigned NewVal = MRI.createVirtualRegister(RC);
5448 unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
5449 unsigned RotatedAltVal = (IsSubWord ? MRI.createVirtualRegister(RC) : Src2);
5450 unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
5452 // Insert 3 basic blocks for the loop.
5453 MachineBasicBlock *StartMBB = MBB;
5454 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5455 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5456 MachineBasicBlock *UseAltMBB = emitBlockAfter(LoopMBB);
5457 MachineBasicBlock *UpdateMBB = emitBlockAfter(UseAltMBB);
5461 // %OrigVal = L Disp(%Base)
5462 // # fall through to LoopMMB
5464 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
5465 .addOperand(Base).addImm(Disp).addReg(0);
5466 MBB->addSuccessor(LoopMBB);
5469 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
5470 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
5471 // CompareOpcode %RotatedOldVal, %Src2
5472 // BRC KeepOldMask, UpdateMBB
5474 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
5475 .addReg(OrigVal).addMBB(StartMBB)
5476 .addReg(Dest).addMBB(UpdateMBB);
5478 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
5479 .addReg(OldVal).addReg(BitShift).addImm(0);
5480 BuildMI(MBB, DL, TII->get(CompareOpcode))
5481 .addReg(RotatedOldVal).addReg(Src2);
5482 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5483 .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
5484 MBB->addSuccessor(UpdateMBB);
5485 MBB->addSuccessor(UseAltMBB);
5488 // %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
5489 // # fall through to UpdateMMB
5492 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
5493 .addReg(RotatedOldVal).addReg(Src2)
5494 .addImm(32).addImm(31 + BitSize).addImm(0);
5495 MBB->addSuccessor(UpdateMBB);
5498 // %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
5499 // [ %RotatedAltVal, UseAltMBB ]
5500 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
5501 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
5503 // # fall through to DoneMMB
5505 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
5506 .addReg(RotatedOldVal).addMBB(LoopMBB)
5507 .addReg(RotatedAltVal).addMBB(UseAltMBB);
5509 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
5510 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
5511 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
5512 .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
5513 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5514 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
5515 MBB->addSuccessor(LoopMBB);
5516 MBB->addSuccessor(DoneMBB);
5518 MI.eraseFromParent();
5522 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_CMP_SWAPW
5525 SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr &MI,
5526 MachineBasicBlock *MBB) const {
5528 MachineFunction &MF = *MBB->getParent();
5529 const SystemZInstrInfo *TII =
5530 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5531 MachineRegisterInfo &MRI = MF.getRegInfo();
5533 // Extract the operands. Base can be a register or a frame index.
5534 unsigned Dest = MI.getOperand(0).getReg();
5535 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
5536 int64_t Disp = MI.getOperand(2).getImm();
5537 unsigned OrigCmpVal = MI.getOperand(3).getReg();
5538 unsigned OrigSwapVal = MI.getOperand(4).getReg();
5539 unsigned BitShift = MI.getOperand(5).getReg();
5540 unsigned NegBitShift = MI.getOperand(6).getReg();
5541 int64_t BitSize = MI.getOperand(7).getImm();
5542 DebugLoc DL = MI.getDebugLoc();
5544 const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
5546 // Get the right opcodes for the displacement.
5547 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
5548 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
5549 assert(LOpcode && CSOpcode && "Displacement out of range");
5551 // Create virtual registers for temporary results.
5552 unsigned OrigOldVal = MRI.createVirtualRegister(RC);
5553 unsigned OldVal = MRI.createVirtualRegister(RC);
5554 unsigned CmpVal = MRI.createVirtualRegister(RC);
5555 unsigned SwapVal = MRI.createVirtualRegister(RC);
5556 unsigned StoreVal = MRI.createVirtualRegister(RC);
5557 unsigned RetryOldVal = MRI.createVirtualRegister(RC);
5558 unsigned RetryCmpVal = MRI.createVirtualRegister(RC);
5559 unsigned RetrySwapVal = MRI.createVirtualRegister(RC);
5561 // Insert 2 basic blocks for the loop.
5562 MachineBasicBlock *StartMBB = MBB;
5563 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5564 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5565 MachineBasicBlock *SetMBB = emitBlockAfter(LoopMBB);
5569 // %OrigOldVal = L Disp(%Base)
5570 // # fall through to LoopMMB
5572 BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
5573 .addOperand(Base).addImm(Disp).addReg(0);
5574 MBB->addSuccessor(LoopMBB);
5577 // %OldVal = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
5578 // %CmpVal = phi [ %OrigCmpVal, EntryBB ], [ %RetryCmpVal, SetMBB ]
5579 // %SwapVal = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
5580 // %Dest = RLL %OldVal, BitSize(%BitShift)
5581 // ^^ The low BitSize bits contain the field
5583 // %RetryCmpVal = RISBG32 %CmpVal, %Dest, 32, 63-BitSize, 0
5584 // ^^ Replace the upper 32-BitSize bits of the
5585 // comparison value with those that we loaded,
5586 // so that we can use a full word comparison.
5587 // CR %Dest, %RetryCmpVal
5589 // # Fall through to SetMBB
5591 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
5592 .addReg(OrigOldVal).addMBB(StartMBB)
5593 .addReg(RetryOldVal).addMBB(SetMBB);
5594 BuildMI(MBB, DL, TII->get(SystemZ::PHI), CmpVal)
5595 .addReg(OrigCmpVal).addMBB(StartMBB)
5596 .addReg(RetryCmpVal).addMBB(SetMBB);
5597 BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
5598 .addReg(OrigSwapVal).addMBB(StartMBB)
5599 .addReg(RetrySwapVal).addMBB(SetMBB);
5600 BuildMI(MBB, DL, TII->get(SystemZ::RLL), Dest)
5601 .addReg(OldVal).addReg(BitShift).addImm(BitSize);
5602 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetryCmpVal)
5603 .addReg(CmpVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
5604 BuildMI(MBB, DL, TII->get(SystemZ::CR))
5605 .addReg(Dest).addReg(RetryCmpVal);
5606 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5607 .addImm(SystemZ::CCMASK_ICMP)
5608 .addImm(SystemZ::CCMASK_CMP_NE).addMBB(DoneMBB);
5609 MBB->addSuccessor(DoneMBB);
5610 MBB->addSuccessor(SetMBB);
5613 // %RetrySwapVal = RISBG32 %SwapVal, %Dest, 32, 63-BitSize, 0
5614 // ^^ Replace the upper 32-BitSize bits of the new
5615 // value with those that we loaded.
5616 // %StoreVal = RLL %RetrySwapVal, -BitSize(%NegBitShift)
5617 // ^^ Rotate the new field to its proper position.
5618 // %RetryOldVal = CS %Dest, %StoreVal, Disp(%Base)
5620 // # fall through to ExitMMB
5622 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
5623 .addReg(SwapVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
5624 BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
5625 .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
5626 BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
5627 .addReg(OldVal).addReg(StoreVal).addOperand(Base).addImm(Disp);
5628 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5629 .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
5630 MBB->addSuccessor(LoopMBB);
5631 MBB->addSuccessor(DoneMBB);
5633 MI.eraseFromParent();
5637 // Emit an extension from a GR32 or GR64 to a GR128. ClearEven is true
5638 // if the high register of the GR128 value must be cleared or false if
5639 // it's "don't care". SubReg is subreg_l32 when extending a GR32
5640 // and subreg_l64 when extending a GR64.
5641 MachineBasicBlock *SystemZTargetLowering::emitExt128(MachineInstr &MI,
5642 MachineBasicBlock *MBB,
5644 unsigned SubReg) const {
5645 MachineFunction &MF = *MBB->getParent();
5646 const SystemZInstrInfo *TII =
5647 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5648 MachineRegisterInfo &MRI = MF.getRegInfo();
5649 DebugLoc DL = MI.getDebugLoc();
5651 unsigned Dest = MI.getOperand(0).getReg();
5652 unsigned Src = MI.getOperand(1).getReg();
5653 unsigned In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
5655 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128);
5657 unsigned NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
5658 unsigned Zero64 = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
5660 BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64)
5662 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128)
5663 .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_h64);
5666 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
5667 .addReg(In128).addReg(Src).addImm(SubReg);
5669 MI.eraseFromParent();
5673 MachineBasicBlock *SystemZTargetLowering::emitMemMemWrapper(
5674 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
5675 MachineFunction &MF = *MBB->getParent();
5676 const SystemZInstrInfo *TII =
5677 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5678 MachineRegisterInfo &MRI = MF.getRegInfo();
5679 DebugLoc DL = MI.getDebugLoc();
5681 MachineOperand DestBase = earlyUseOperand(MI.getOperand(0));
5682 uint64_t DestDisp = MI.getOperand(1).getImm();
5683 MachineOperand SrcBase = earlyUseOperand(MI.getOperand(2));
5684 uint64_t SrcDisp = MI.getOperand(3).getImm();
5685 uint64_t Length = MI.getOperand(4).getImm();
5687 // When generating more than one CLC, all but the last will need to
5688 // branch to the end when a difference is found.
5689 MachineBasicBlock *EndMBB = (Length > 256 && Opcode == SystemZ::CLC ?
5690 splitBlockAfter(MI, MBB) : nullptr);
5692 // Check for the loop form, in which operand 5 is the trip count.
5693 if (MI.getNumExplicitOperands() > 5) {
5694 bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
5696 uint64_t StartCountReg = MI.getOperand(5).getReg();
5697 uint64_t StartSrcReg = forceReg(MI, SrcBase, TII);
5698 uint64_t StartDestReg = (HaveSingleBase ? StartSrcReg :
5699 forceReg(MI, DestBase, TII));
5701 const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
5702 uint64_t ThisSrcReg = MRI.createVirtualRegister(RC);
5703 uint64_t ThisDestReg = (HaveSingleBase ? ThisSrcReg :
5704 MRI.createVirtualRegister(RC));
5705 uint64_t NextSrcReg = MRI.createVirtualRegister(RC);
5706 uint64_t NextDestReg = (HaveSingleBase ? NextSrcReg :
5707 MRI.createVirtualRegister(RC));
5709 RC = &SystemZ::GR64BitRegClass;
5710 uint64_t ThisCountReg = MRI.createVirtualRegister(RC);
5711 uint64_t NextCountReg = MRI.createVirtualRegister(RC);
5713 MachineBasicBlock *StartMBB = MBB;
5714 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5715 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5716 MachineBasicBlock *NextMBB = (EndMBB ? emitBlockAfter(LoopMBB) : LoopMBB);
5719 // # fall through to LoopMMB
5720 MBB->addSuccessor(LoopMBB);
5723 // %ThisDestReg = phi [ %StartDestReg, StartMBB ],
5724 // [ %NextDestReg, NextMBB ]
5725 // %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
5726 // [ %NextSrcReg, NextMBB ]
5727 // %ThisCountReg = phi [ %StartCountReg, StartMBB ],
5728 // [ %NextCountReg, NextMBB ]
5729 // ( PFD 2, 768+DestDisp(%ThisDestReg) )
5730 // Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
5733 // The prefetch is used only for MVC. The JLH is used only for CLC.
5736 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
5737 .addReg(StartDestReg).addMBB(StartMBB)
5738 .addReg(NextDestReg).addMBB(NextMBB);
5739 if (!HaveSingleBase)
5740 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
5741 .addReg(StartSrcReg).addMBB(StartMBB)
5742 .addReg(NextSrcReg).addMBB(NextMBB);
5743 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
5744 .addReg(StartCountReg).addMBB(StartMBB)
5745 .addReg(NextCountReg).addMBB(NextMBB);
5746 if (Opcode == SystemZ::MVC)
5747 BuildMI(MBB, DL, TII->get(SystemZ::PFD))
5748 .addImm(SystemZ::PFD_WRITE)
5749 .addReg(ThisDestReg).addImm(DestDisp + 768).addReg(0);
5750 BuildMI(MBB, DL, TII->get(Opcode))
5751 .addReg(ThisDestReg).addImm(DestDisp).addImm(256)
5752 .addReg(ThisSrcReg).addImm(SrcDisp);
5754 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5755 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5757 MBB->addSuccessor(EndMBB);
5758 MBB->addSuccessor(NextMBB);
5762 // %NextDestReg = LA 256(%ThisDestReg)
5763 // %NextSrcReg = LA 256(%ThisSrcReg)
5764 // %NextCountReg = AGHI %ThisCountReg, -1
5765 // CGHI %NextCountReg, 0
5767 // # fall through to DoneMMB
5769 // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
5772 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
5773 .addReg(ThisDestReg).addImm(256).addReg(0);
5774 if (!HaveSingleBase)
5775 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
5776 .addReg(ThisSrcReg).addImm(256).addReg(0);
5777 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
5778 .addReg(ThisCountReg).addImm(-1);
5779 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
5780 .addReg(NextCountReg).addImm(0);
5781 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5782 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5784 MBB->addSuccessor(LoopMBB);
5785 MBB->addSuccessor(DoneMBB);
5787 DestBase = MachineOperand::CreateReg(NextDestReg, false);
5788 SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
5792 // Handle any remaining bytes with straight-line code.
5793 while (Length > 0) {
5794 uint64_t ThisLength = std::min(Length, uint64_t(256));
5795 // The previous iteration might have created out-of-range displacements.
5796 // Apply them using LAY if so.
5797 if (!isUInt<12>(DestDisp)) {
5798 unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
5799 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LAY), Reg)
5800 .addOperand(DestBase)
5803 DestBase = MachineOperand::CreateReg(Reg, false);
5806 if (!isUInt<12>(SrcDisp)) {
5807 unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
5808 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LAY), Reg)
5809 .addOperand(SrcBase)
5812 SrcBase = MachineOperand::CreateReg(Reg, false);
5815 BuildMI(*MBB, MI, DL, TII->get(Opcode))
5816 .addOperand(DestBase).addImm(DestDisp).addImm(ThisLength)
5817 .addOperand(SrcBase).addImm(SrcDisp);
5818 DestDisp += ThisLength;
5819 SrcDisp += ThisLength;
5820 Length -= ThisLength;
5821 // If there's another CLC to go, branch to the end if a difference
5823 if (EndMBB && Length > 0) {
5824 MachineBasicBlock *NextMBB = splitBlockBefore(MI, MBB);
5825 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5826 .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
5828 MBB->addSuccessor(EndMBB);
5829 MBB->addSuccessor(NextMBB);
5834 MBB->addSuccessor(EndMBB);
5836 MBB->addLiveIn(SystemZ::CC);
5839 MI.eraseFromParent();
5843 // Decompose string pseudo-instruction MI into a loop that continually performs
5844 // Opcode until CC != 3.
5845 MachineBasicBlock *SystemZTargetLowering::emitStringWrapper(
5846 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
5847 MachineFunction &MF = *MBB->getParent();
5848 const SystemZInstrInfo *TII =
5849 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5850 MachineRegisterInfo &MRI = MF.getRegInfo();
5851 DebugLoc DL = MI.getDebugLoc();
5853 uint64_t End1Reg = MI.getOperand(0).getReg();
5854 uint64_t Start1Reg = MI.getOperand(1).getReg();
5855 uint64_t Start2Reg = MI.getOperand(2).getReg();
5856 uint64_t CharReg = MI.getOperand(3).getReg();
5858 const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
5859 uint64_t This1Reg = MRI.createVirtualRegister(RC);
5860 uint64_t This2Reg = MRI.createVirtualRegister(RC);
5861 uint64_t End2Reg = MRI.createVirtualRegister(RC);
5863 MachineBasicBlock *StartMBB = MBB;
5864 MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
5865 MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
5868 // # fall through to LoopMMB
5869 MBB->addSuccessor(LoopMBB);
5872 // %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
5873 // %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
5875 // %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
5877 // # fall through to DoneMMB
5879 // The load of R0L can be hoisted by post-RA LICM.
5882 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
5883 .addReg(Start1Reg).addMBB(StartMBB)
5884 .addReg(End1Reg).addMBB(LoopMBB);
5885 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
5886 .addReg(Start2Reg).addMBB(StartMBB)
5887 .addReg(End2Reg).addMBB(LoopMBB);
5888 BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
5889 BuildMI(MBB, DL, TII->get(Opcode))
5890 .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
5891 .addReg(This1Reg).addReg(This2Reg);
5892 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
5893 .addImm(SystemZ::CCMASK_ANY).addImm(SystemZ::CCMASK_3).addMBB(LoopMBB);
5894 MBB->addSuccessor(LoopMBB);
5895 MBB->addSuccessor(DoneMBB);
5897 DoneMBB->addLiveIn(SystemZ::CC);
5899 MI.eraseFromParent();
5903 // Update TBEGIN instruction with final opcode and register clobbers.
5904 MachineBasicBlock *SystemZTargetLowering::emitTransactionBegin(
5905 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode,
5906 bool NoFloat) const {
5907 MachineFunction &MF = *MBB->getParent();
5908 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
5909 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
5912 MI.setDesc(TII->get(Opcode));
5914 // We cannot handle a TBEGIN that clobbers the stack or frame pointer.
5915 // Make sure to add the corresponding GRSM bits if they are missing.
5916 uint64_t Control = MI.getOperand(2).getImm();
5917 static const unsigned GPRControlBit[16] = {
5918 0x8000, 0x8000, 0x4000, 0x4000, 0x2000, 0x2000, 0x1000, 0x1000,
5919 0x0800, 0x0800, 0x0400, 0x0400, 0x0200, 0x0200, 0x0100, 0x0100
5921 Control |= GPRControlBit[15];
5923 Control |= GPRControlBit[11];
5924 MI.getOperand(2).setImm(Control);
5926 // Add GPR clobbers.
5927 for (int I = 0; I < 16; I++) {
5928 if ((Control & GPRControlBit[I]) == 0) {
5929 unsigned Reg = SystemZMC::GR64Regs[I];
5930 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
5934 // Add FPR/VR clobbers.
5935 if (!NoFloat && (Control & 4) != 0) {
5936 if (Subtarget.hasVector()) {
5937 for (int I = 0; I < 32; I++) {
5938 unsigned Reg = SystemZMC::VR128Regs[I];
5939 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
5942 for (int I = 0; I < 16; I++) {
5943 unsigned Reg = SystemZMC::FP64Regs[I];
5944 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
5952 MachineBasicBlock *SystemZTargetLowering::emitLoadAndTestCmp0(
5953 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
5954 MachineFunction &MF = *MBB->getParent();
5955 MachineRegisterInfo *MRI = &MF.getRegInfo();
5956 const SystemZInstrInfo *TII =
5957 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
5958 DebugLoc DL = MI.getDebugLoc();
5960 unsigned SrcReg = MI.getOperand(0).getReg();
5962 // Create new virtual register of the same class as source.
5963 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
5964 unsigned DstReg = MRI->createVirtualRegister(RC);
5966 // Replace pseudo with a normal load-and-test that models the def as
5968 BuildMI(*MBB, MI, DL, TII->get(Opcode), DstReg)
5970 MI.eraseFromParent();
5975 MachineBasicBlock *SystemZTargetLowering::EmitInstrWithCustomInserter(
5976 MachineInstr &MI, MachineBasicBlock *MBB) const {
5977 switch (MI.getOpcode()) {
5978 case SystemZ::Select32Mux:
5979 case SystemZ::Select32:
5980 case SystemZ::SelectF32:
5981 case SystemZ::Select64:
5982 case SystemZ::SelectF64:
5983 case SystemZ::SelectF128:
5984 return emitSelect(MI, MBB);
5986 case SystemZ::CondStore8Mux:
5987 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
5988 case SystemZ::CondStore8MuxInv:
5989 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
5990 case SystemZ::CondStore16Mux:
5991 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
5992 case SystemZ::CondStore16MuxInv:
5993 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
5994 case SystemZ::CondStore8:
5995 return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
5996 case SystemZ::CondStore8Inv:
5997 return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
5998 case SystemZ::CondStore16:
5999 return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
6000 case SystemZ::CondStore16Inv:
6001 return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
6002 case SystemZ::CondStore32:
6003 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
6004 case SystemZ::CondStore32Inv:
6005 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
6006 case SystemZ::CondStore64:
6007 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
6008 case SystemZ::CondStore64Inv:
6009 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
6010 case SystemZ::CondStoreF32:
6011 return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
6012 case SystemZ::CondStoreF32Inv:
6013 return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
6014 case SystemZ::CondStoreF64:
6015 return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
6016 case SystemZ::CondStoreF64Inv:
6017 return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
6019 case SystemZ::AEXT128_64:
6020 return emitExt128(MI, MBB, false, SystemZ::subreg_l64);
6021 case SystemZ::ZEXT128_32:
6022 return emitExt128(MI, MBB, true, SystemZ::subreg_l32);
6023 case SystemZ::ZEXT128_64:
6024 return emitExt128(MI, MBB, true, SystemZ::subreg_l64);
6026 case SystemZ::ATOMIC_SWAPW:
6027 return emitAtomicLoadBinary(MI, MBB, 0, 0);
6028 case SystemZ::ATOMIC_SWAP_32:
6029 return emitAtomicLoadBinary(MI, MBB, 0, 32);
6030 case SystemZ::ATOMIC_SWAP_64:
6031 return emitAtomicLoadBinary(MI, MBB, 0, 64);
6033 case SystemZ::ATOMIC_LOADW_AR:
6034 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 0);
6035 case SystemZ::ATOMIC_LOADW_AFI:
6036 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 0);
6037 case SystemZ::ATOMIC_LOAD_AR:
6038 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 32);
6039 case SystemZ::ATOMIC_LOAD_AHI:
6040 return emitAtomicLoadBinary(MI, MBB, SystemZ::AHI, 32);
6041 case SystemZ::ATOMIC_LOAD_AFI:
6042 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 32);
6043 case SystemZ::ATOMIC_LOAD_AGR:
6044 return emitAtomicLoadBinary(MI, MBB, SystemZ::AGR, 64);
6045 case SystemZ::ATOMIC_LOAD_AGHI:
6046 return emitAtomicLoadBinary(MI, MBB, SystemZ::AGHI, 64);
6047 case SystemZ::ATOMIC_LOAD_AGFI:
6048 return emitAtomicLoadBinary(MI, MBB, SystemZ::AGFI, 64);
6050 case SystemZ::ATOMIC_LOADW_SR:
6051 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 0);
6052 case SystemZ::ATOMIC_LOAD_SR:
6053 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 32);
6054 case SystemZ::ATOMIC_LOAD_SGR:
6055 return emitAtomicLoadBinary(MI, MBB, SystemZ::SGR, 64);
6057 case SystemZ::ATOMIC_LOADW_NR:
6058 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0);
6059 case SystemZ::ATOMIC_LOADW_NILH:
6060 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0);
6061 case SystemZ::ATOMIC_LOAD_NR:
6062 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32);
6063 case SystemZ::ATOMIC_LOAD_NILL:
6064 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32);
6065 case SystemZ::ATOMIC_LOAD_NILH:
6066 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32);
6067 case SystemZ::ATOMIC_LOAD_NILF:
6068 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32);
6069 case SystemZ::ATOMIC_LOAD_NGR:
6070 return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64);
6071 case SystemZ::ATOMIC_LOAD_NILL64:
6072 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64);
6073 case SystemZ::ATOMIC_LOAD_NILH64:
6074 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64);
6075 case SystemZ::ATOMIC_LOAD_NIHL64:
6076 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64);
6077 case SystemZ::ATOMIC_LOAD_NIHH64:
6078 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64);
6079 case SystemZ::ATOMIC_LOAD_NILF64:
6080 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64);
6081 case SystemZ::ATOMIC_LOAD_NIHF64:
6082 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64);
6084 case SystemZ::ATOMIC_LOADW_OR:
6085 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 0);
6086 case SystemZ::ATOMIC_LOADW_OILH:
6087 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 0);
6088 case SystemZ::ATOMIC_LOAD_OR:
6089 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 32);
6090 case SystemZ::ATOMIC_LOAD_OILL:
6091 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL, 32);
6092 case SystemZ::ATOMIC_LOAD_OILH:
6093 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 32);
6094 case SystemZ::ATOMIC_LOAD_OILF:
6095 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF, 32);
6096 case SystemZ::ATOMIC_LOAD_OGR:
6097 return emitAtomicLoadBinary(MI, MBB, SystemZ::OGR, 64);
6098 case SystemZ::ATOMIC_LOAD_OILL64:
6099 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL64, 64);
6100 case SystemZ::ATOMIC_LOAD_OILH64:
6101 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH64, 64);
6102 case SystemZ::ATOMIC_LOAD_OIHL64:
6103 return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHL64, 64);
6104 case SystemZ::ATOMIC_LOAD_OIHH64:
6105 return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHH64, 64);
6106 case SystemZ::ATOMIC_LOAD_OILF64:
6107 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF64, 64);
6108 case SystemZ::ATOMIC_LOAD_OIHF64:
6109 return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHF64, 64);
6111 case SystemZ::ATOMIC_LOADW_XR:
6112 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 0);
6113 case SystemZ::ATOMIC_LOADW_XILF:
6114 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 0);
6115 case SystemZ::ATOMIC_LOAD_XR:
6116 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 32);
6117 case SystemZ::ATOMIC_LOAD_XILF:
6118 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 32);
6119 case SystemZ::ATOMIC_LOAD_XGR:
6120 return emitAtomicLoadBinary(MI, MBB, SystemZ::XGR, 64);
6121 case SystemZ::ATOMIC_LOAD_XILF64:
6122 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF64, 64);
6123 case SystemZ::ATOMIC_LOAD_XIHF64:
6124 return emitAtomicLoadBinary(MI, MBB, SystemZ::XIHF64, 64);
6126 case SystemZ::ATOMIC_LOADW_NRi:
6127 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0, true);
6128 case SystemZ::ATOMIC_LOADW_NILHi:
6129 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0, true);
6130 case SystemZ::ATOMIC_LOAD_NRi:
6131 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32, true);
6132 case SystemZ::ATOMIC_LOAD_NILLi:
6133 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32, true);
6134 case SystemZ::ATOMIC_LOAD_NILHi:
6135 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32, true);
6136 case SystemZ::ATOMIC_LOAD_NILFi:
6137 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32, true);
6138 case SystemZ::ATOMIC_LOAD_NGRi:
6139 return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64, true);
6140 case SystemZ::ATOMIC_LOAD_NILL64i:
6141 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64, true);
6142 case SystemZ::ATOMIC_LOAD_NILH64i:
6143 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64, true);
6144 case SystemZ::ATOMIC_LOAD_NIHL64i:
6145 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64, true);
6146 case SystemZ::ATOMIC_LOAD_NIHH64i:
6147 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64, true);
6148 case SystemZ::ATOMIC_LOAD_NILF64i:
6149 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64, true);
6150 case SystemZ::ATOMIC_LOAD_NIHF64i:
6151 return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64, true);
6153 case SystemZ::ATOMIC_LOADW_MIN:
6154 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
6155 SystemZ::CCMASK_CMP_LE, 0);
6156 case SystemZ::ATOMIC_LOAD_MIN_32:
6157 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
6158 SystemZ::CCMASK_CMP_LE, 32);
6159 case SystemZ::ATOMIC_LOAD_MIN_64:
6160 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
6161 SystemZ::CCMASK_CMP_LE, 64);
6163 case SystemZ::ATOMIC_LOADW_MAX:
6164 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
6165 SystemZ::CCMASK_CMP_GE, 0);
6166 case SystemZ::ATOMIC_LOAD_MAX_32:
6167 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
6168 SystemZ::CCMASK_CMP_GE, 32);
6169 case SystemZ::ATOMIC_LOAD_MAX_64:
6170 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
6171 SystemZ::CCMASK_CMP_GE, 64);
6173 case SystemZ::ATOMIC_LOADW_UMIN:
6174 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
6175 SystemZ::CCMASK_CMP_LE, 0);
6176 case SystemZ::ATOMIC_LOAD_UMIN_32:
6177 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
6178 SystemZ::CCMASK_CMP_LE, 32);
6179 case SystemZ::ATOMIC_LOAD_UMIN_64:
6180 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
6181 SystemZ::CCMASK_CMP_LE, 64);
6183 case SystemZ::ATOMIC_LOADW_UMAX:
6184 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
6185 SystemZ::CCMASK_CMP_GE, 0);
6186 case SystemZ::ATOMIC_LOAD_UMAX_32:
6187 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
6188 SystemZ::CCMASK_CMP_GE, 32);
6189 case SystemZ::ATOMIC_LOAD_UMAX_64:
6190 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
6191 SystemZ::CCMASK_CMP_GE, 64);
6193 case SystemZ::ATOMIC_CMP_SWAPW:
6194 return emitAtomicCmpSwapW(MI, MBB);
6195 case SystemZ::MVCSequence:
6196 case SystemZ::MVCLoop:
6197 return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
6198 case SystemZ::NCSequence:
6199 case SystemZ::NCLoop:
6200 return emitMemMemWrapper(MI, MBB, SystemZ::NC);
6201 case SystemZ::OCSequence:
6202 case SystemZ::OCLoop:
6203 return emitMemMemWrapper(MI, MBB, SystemZ::OC);
6204 case SystemZ::XCSequence:
6205 case SystemZ::XCLoop:
6206 return emitMemMemWrapper(MI, MBB, SystemZ::XC);
6207 case SystemZ::CLCSequence:
6208 case SystemZ::CLCLoop:
6209 return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
6210 case SystemZ::CLSTLoop:
6211 return emitStringWrapper(MI, MBB, SystemZ::CLST);
6212 case SystemZ::MVSTLoop:
6213 return emitStringWrapper(MI, MBB, SystemZ::MVST);
6214 case SystemZ::SRSTLoop:
6215 return emitStringWrapper(MI, MBB, SystemZ::SRST);
6216 case SystemZ::TBEGIN:
6217 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, false);
6218 case SystemZ::TBEGIN_nofloat:
6219 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, true);
6220 case SystemZ::TBEGINC:
6221 return emitTransactionBegin(MI, MBB, SystemZ::TBEGINC, true);
6222 case SystemZ::LTEBRCompare_VecPseudo:
6223 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTEBR);
6224 case SystemZ::LTDBRCompare_VecPseudo:
6225 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTDBR);
6226 case SystemZ::LTXBRCompare_VecPseudo:
6227 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTXBR);
6230 llvm_unreachable("Unexpected instr type to insert");