LLVM 24.0.0git
SystemZISelLowering.cpp
Go to the documentation of this file.
1//===-- SystemZISelLowering.cpp - SystemZ DAG lowering implementation -----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the SystemZTargetLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "SystemZISelLowering.h"
14#include "SystemZCallingConv.h"
17#include "llvm/ADT/SmallSet.h"
22#include "llvm/IR/GlobalAlias.h"
24#include "llvm/IR/Intrinsics.h"
25#include "llvm/IR/IntrinsicsS390.h"
26#include "llvm/IR/Module.h"
32#include <cctype>
33#include <optional>
34
35using namespace llvm;
36
37#define DEBUG_TYPE "systemz-lower"
38
39// Temporarily let this be disabled by default until all known problems
40// related to argument extensions are fixed.
42 "argext-abi-check", cl::init(false),
43 cl::desc("Verify that narrow int args are properly extended per the "
44 "SystemZ ABI."));
45
46namespace {
47// Represents information about a comparison.
48struct Comparison {
49 Comparison(SDValue Op0In, SDValue Op1In, SDValue ChainIn)
50 : Op0(Op0In), Op1(Op1In), Chain(ChainIn),
51 Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
52
53 // The operands to the comparison.
54 SDValue Op0, Op1;
55
56 // Chain if this is a strict floating-point comparison.
57 SDValue Chain;
58
59 // The opcode that should be used to compare Op0 and Op1.
60 unsigned Opcode;
61
62 // A SystemZICMP value. Only used for integer comparisons.
63 unsigned ICmpType;
64
65 // The mask of CC values that Opcode can produce.
66 unsigned CCValid;
67
68 // The mask of CC values for which the original condition is true.
69 unsigned CCMask;
70};
71} // end anonymous namespace
72
73// Classify VT as either 32 or 64 bit.
74static bool is32Bit(EVT VT) {
75 switch (VT.getSimpleVT().SimpleTy) {
76 case MVT::i32:
77 return true;
78 case MVT::i64:
79 return false;
80 default:
81 llvm_unreachable("Unsupported type");
82 }
83}
84
85// Return a version of MachineOperand that can be safely used before the
86// final use.
88 if (Op.isReg())
89 Op.setIsKill(false);
90 return Op;
91}
92
94 const SystemZSubtarget &STI)
95 : TargetLowering(TM, STI), Subtarget(STI) {
96 MVT PtrVT = MVT::i64;
97
98 auto *Regs = STI.getSpecialRegisters();
99
100 // Set up the register classes.
101 if (Subtarget.hasHighWord())
102 addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
103 else
104 addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
105 addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass);
106 if (!useSoftFloat()) {
107 if (Subtarget.hasVector()) {
108 addRegisterClass(MVT::f16, &SystemZ::VR16BitRegClass);
109 addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass);
110 addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass);
111 } else {
112 addRegisterClass(MVT::f16, &SystemZ::FP16BitRegClass);
113 addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass);
114 addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass);
115 }
116 if (Subtarget.hasVectorEnhancements1())
117 addRegisterClass(MVT::f128, &SystemZ::VR128BitRegClass);
118 else
119 addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
120
121 if (Subtarget.hasVector()) {
122 addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass);
123 addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass);
124 addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass);
125 addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass);
126 addRegisterClass(MVT::v8f16, &SystemZ::VR128BitRegClass);
127 addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass);
128 addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass);
129 }
130
131 if (Subtarget.hasVector())
132 addRegisterClass(MVT::i128, &SystemZ::VR128BitRegClass);
133 }
134
135 // Compute derived properties from the register classes
136 computeRegisterProperties(Subtarget.getRegisterInfo());
137
138 // Set up special registers.
139 setStackPointerRegisterToSaveRestore(Regs->getStackPointerRegister());
140
141 // TODO: It may be better to default to latency-oriented scheduling, however
142 // LLVM's current latency-oriented scheduler can't handle physreg definitions
143 // such as SystemZ has with CC, so set this to the register-pressure
144 // scheduler, because it can.
146
149
151
152 // Instructions are strings of 2-byte aligned 2-byte values.
154 // For performance reasons we prefer 16-byte alignment.
156
157 // Handle operations that are handled in a similar way for all types.
158 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
159 I <= MVT::LAST_FP_VALUETYPE;
160 ++I) {
162 if (isTypeLegal(VT)) {
163 // Lower SET_CC into an IPM-based sequence.
167
168 // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
170
171 // Lower SELECT_CC and BR_CC into separate comparisons and branches.
174 }
175 }
176
177 // Expand jump table branches as address arithmetic followed by an
178 // indirect jump.
180
181 // Expand BRCOND into a BR_CC (see above).
183
184 // Handle integer types except i128.
185 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
186 I <= MVT::LAST_INTEGER_VALUETYPE;
187 ++I) {
189 if (isTypeLegal(VT) && VT != MVT::i128) {
191
192 // Expand individual DIV and REMs into DIVREMs.
199
200 // Support addition/subtraction with overflow.
203
204 // Support addition/subtraction with carry.
207
208 // Support carry in as value rather than glue.
211
212 // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
213 // available, or if the operand is constant.
215
216 // Use POPCNT on z196 and above.
217 if (Subtarget.hasPopulationCount())
219 else
221
222 // No special instructions for these.
225
226 // Use *MUL_LOHI where possible instead of MULH*.
231
232 // The fp<=>i32/i64 conversions are all Legal except for f16 and for
233 // unsigned on z10 (only z196 and above have native support for
234 // unsigned conversions).
241 // Handle unsigned 32-bit input types as signed 64-bit types on z10.
242 auto OpAction =
243 (!Subtarget.hasFPExtension() && VT == MVT::i32) ? Promote : Custom;
244 setOperationAction(Op, VT, OpAction);
245 }
246 }
247 }
248
249 // Handle i128 if legal.
250 if (isTypeLegal(MVT::i128)) {
251 // No special instructions for these.
258
259 // We may be able to use VSLDB/VSLD/VSRD for these.
262
263 // No special instructions for these before z17.
264 if (!Subtarget.hasVectorEnhancements3()) {
274 } else {
275 // Even if we do have a legal 128-bit multiply, we do not
276 // want 64-bit multiply-high operations to use it.
279 }
280
281 // Support addition/subtraction with carry.
286
287 // Use VPOPCT and add up partial results.
289
290 // Additional instructions available with z17.
291 if (Subtarget.hasVectorEnhancements3()) {
292 setOperationAction(ISD::ABS, MVT::i128, Legal);
293
295 MVT::i128, Legal);
296 }
297 }
298
299 // These need custom handling in order to handle the f16 conversions.
308
309 // Type legalization will convert 8- and 16-bit atomic operations into
310 // forms that operate on i32s (but still keeping the original memory VT).
311 // Lower them into full i32 operations.
323
324 // Whether or not i128 is not a legal type, we need to custom lower
325 // the atomic operations in order to exploit SystemZ instructions.
330
331 // Mark sign/zero extending atomic loads as legal, which will make
332 // DAGCombiner fold extensions into atomic loads if possible.
334 {MVT::i8, MVT::i16, MVT::i32}, Legal);
336 {MVT::i8, MVT::i16}, Legal);
338 MVT::i8, Legal);
339
340 // We can use the CC result of compare-and-swap to implement
341 // the "success" result of ATOMIC_CMP_SWAP_WITH_SUCCESS.
345
347
348 // Traps are legal, as we will convert them to "j .+2".
349 setOperationAction(ISD::TRAP, MVT::Other, Legal);
350
351 // We have native support for a 64-bit CTLZ, via FLOGR.
355
356 // On z17 we have native support for a 64-bit CTTZ.
357 if (Subtarget.hasMiscellaneousExtensions4()) {
361 }
362
363 // On z15 we have native support for a 64-bit CTPOP.
364 if (Subtarget.hasMiscellaneousExtensions3()) {
367 }
368
369 // Give LowerOperation the chance to replace 64-bit ORs with subregs.
371
372 // Expand 128 bit shifts without using a libcall.
376
377 // Also expand 256 bit shifts if i128 is a legal type.
378 if (isTypeLegal(MVT::i128)) {
382 }
383
384 // Handle bitcast from fp128 to i128.
385 if (!isTypeLegal(MVT::i128))
387
388 // We have native instructions for i8, i16 and i32 extensions, but not i1.
390 for (MVT VT : MVT::integer_valuetypes()) {
394 }
395
396 // Handle the various types of symbolic address.
402
403 // We need to handle dynamic allocations specially because of the
404 // 160-byte area at the bottom of the stack.
407
410
411 // Handle prefetches with PFD or PFDRL.
413
414 // Handle readcyclecounter with STCKF.
416
418 // Assume by default that all vector operations need to be expanded.
419 for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
420 if (getOperationAction(Opcode, VT) == Legal)
421 setOperationAction(Opcode, VT, Expand);
422
423 // Likewise all truncating stores and extending loads.
424 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
425 setTruncStoreAction(VT, InnerVT, Expand);
428 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
429 }
430
431 if (isTypeLegal(VT)) {
432 // These operations are legal for anything that can be stored in a
433 // vector register, even if there is no native support for the format
434 // as such. In particular, we can do these for v4f32 even though there
435 // are no specific instructions for that format.
441
442 // Likewise, except that we need to replace the nodes with something
443 // more specific.
446 }
447 }
448
449 // Handle integer vector types.
451 if (isTypeLegal(VT)) {
452 // These operations have direct equivalents.
457 if (VT != MVT::v2i64 || Subtarget.hasVectorEnhancements3()) {
461 }
462 if (Subtarget.hasVectorEnhancements3() &&
463 VT != MVT::v16i8 && VT != MVT::v8i16) {
468 }
473 if (Subtarget.hasVectorEnhancements1())
475 else
479
480 // Convert a GPR scalar to a vector by inserting it into element 0.
482
483 // Use a series of unpacks for extensions.
486
487 // Detect shifts/rotates by a scalar amount and convert them into
488 // V*_BY_SCALAR.
493
494 // Add ISD::VECREDUCE_ADD as custom in order to implement
495 // it with VZERO+VSUM
497
498 // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
499 // and inverting the result as necessary.
501
503 Legal);
504 }
505 }
506
507 if (Subtarget.hasVector()) {
508 // There should be no need to check for float types other than v2f64
509 // since <2 x f32> isn't a legal type.
518
527 }
528
529 if (Subtarget.hasVectorEnhancements2()) {
538
547 }
548
549 // Handle floating-point types.
550 if (!useSoftFloat()) {
551 // Promote all f16 operations to float, with some exceptions below.
552 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
553 setOperationAction(Opc, MVT::f16, Promote);
555 for (MVT VT : {MVT::f32, MVT::f64, MVT::f128}) {
556 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
557 setTruncStoreAction(VT, MVT::f16, Expand);
558 }
560 setOperationAction(Op, MVT::f16, Subtarget.hasVector() ? Legal : Custom);
564
565 for (auto Op : {ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN})
566 setOperationAction(Op, MVT::f16, Legal);
567 }
568
569 for (unsigned I = MVT::FIRST_FP_VALUETYPE;
570 I <= MVT::LAST_FP_VALUETYPE;
571 ++I) {
573 if (isTypeLegal(VT) && VT != MVT::f16) {
574 // We can use FI for FRINT.
576
577 // We can use the extended form of FI for other rounding operations.
578 if (Subtarget.hasFPExtension()) {
585 }
586
587 // No special instructions for these.
593
594 // Special treatment.
596
597 // Handle constrained floating-point operations.
606 if (Subtarget.hasFPExtension()) {
613 }
614
615 // Extension from f16 needs libcall.
618 }
619 }
620
621 // Handle floating-point vector types.
622 if (Subtarget.hasVector()) {
623 // Scalar-to-vector conversion is just a subreg.
627
628 // Some insertions and extractions can be done directly but others
629 // need to go via integers.
636
637 // These operations have direct equivalents.
638 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
639 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
640 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
641 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
642 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
643 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
644 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
645 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
646 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
649 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
653
654 // Handle constrained floating-point operations.
668
673 if (Subtarget.hasVectorEnhancements1()) {
676 }
677 }
678
679 // The vector enhancements facility 1 has instructions for these.
680 if (Subtarget.hasVectorEnhancements1()) {
681 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
682 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
683 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
684 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
685 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
686 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
687 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
688 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
689 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
692 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
696
697 for (MVT Type : {MVT::f64, MVT::v2f64, MVT::f32, MVT::v4f32, MVT::f128}) {
706 }
707
708 // Handle constrained floating-point operations.
722 for (auto VT : { MVT::f32, MVT::f64, MVT::f128,
723 MVT::v4f32, MVT::v2f64 }) {
730 }
731 }
732
733 // We only have fused f128 multiply-addition on vector registers.
734 if (!Subtarget.hasVectorEnhancements1()) {
737 }
738
739 // We don't have a copysign instruction on vector registers.
740 if (Subtarget.hasVectorEnhancements1())
742
743 // Needed so that we don't try to implement f128 constant loads using
744 // a load-and-extend of a f80 constant (in cases where the constant
745 // would fit in an f80).
746 for (MVT VT : MVT::fp_valuetypes())
747 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
748
749 // We don't have extending load instruction on vector registers.
750 if (Subtarget.hasVectorEnhancements1()) {
751 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
752 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
753 }
754
755 // Floating-point truncation and stores need to be done separately.
756 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
757 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
758 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
759
760 // We have 64-bit FPR<->GPR moves, but need special handling for
761 // 32-bit forms.
762 if (!Subtarget.hasVector()) {
765 }
766
767 // VASTART and VACOPY need to deal with the SystemZ-specific varargs
768 // structure, but VAEND is a no-op.
772
773 if (Subtarget.isTargetzOS()) {
774 // Handle address space casts between mixed sized pointers.
777 }
778
780
781 // Codes for which we want to perform some z-specific combinations.
785 ISD::LOAD,
798 ISD::SRL,
799 ISD::SRA,
800 ISD::MUL,
801 ISD::SDIV,
802 ISD::UDIV,
803 ISD::SREM,
804 ISD::UREM,
807
808 // Handle intrinsics.
811
812 // We're not using SJLJ for exception handling, but they're implemented
813 // solely to support use of __builtin_setjmp / __builtin_longjmp.
816
817 // We want to use MVC in preference to even a single load/store pair.
818 MaxStoresPerMemcpy = Subtarget.hasVector() ? 2 : 0;
820
821 // Same with memmove.
822 MaxStoresPerMemmove = Subtarget.hasVector() ? 2 : 0;
824
825 // The main memset sequence is a byte store followed by an MVC.
826 // Two STC or MV..I stores win over that, but the kind of fused stores
827 // generated by target-independent code don't when the byte value is
828 // variable. E.g. "STC <reg>;MHI <reg>,257;STH <reg>" is not better
829 // than "STC;MVC". Handle the choice in target-specific code instead.
830 MaxStoresPerMemset = Subtarget.hasVector() ? 2 : 0;
832
833 // Default to having -disable-strictnode-mutation on
834 IsStrictFPEnabled = true;
835}
836
838 return Subtarget.hasSoftFloat();
839}
840
843 // Widen subvectors to the full width rather than promoting integer
844 // elements. This is better because:
845 //
846 // (a) it means that we can handle the ABI for passing and returning
847 // sub-128 vectors without having to handle them as legal types.
848 //
849 // (b) we don't have instructions to extend on load and truncate on store,
850 // so promoting the integers is less efficient.
851 //
852 // (c) there are no multiplication instructions for the widest integer
853 // type (v2i64).
854
855 // Expand (narrow) f16 vectors during type legalization to avoid
856 // operations for all elements as with expansion after widening.
857 if (VT.getScalarType() == MVT::f16)
860 if (VT.getScalarSizeInBits() % 8 == 0)
861 return TypeWidenVector;
863}
864
866 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
867 unsigned &NumIntermediates, MVT &RegisterVT) const {
868 // Pass fp16 vectors in VR(s).
869 if (Subtarget.hasVector() && VT.isVectorOf(MVT::f16)) {
870 IntermediateVT = RegisterVT = MVT::v8f16;
871 return NumIntermediates =
873 }
875 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
876}
877
880 EVT VT) const {
881 // 128-bit single-element vector types are passed like other vectors,
882 // not like their element type.
883 if (Subtarget.hasVector() && VT.isVector() && VT.getSizeInBits() == 128 &&
884 VT.getVectorNumElements() == 1)
885 return MVT::v16i8;
886 // Pass fp16 vectors in VR(s).
887 if (Subtarget.hasVector() && VT.isVectorOf(MVT::f16))
888 return MVT::v8f16;
889 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
890}
891
893 LLVMContext &Context, CallingConv::ID CC, EVT VT) const {
894 // Pass fp16 vectors in VR(s).
895 if (Subtarget.hasVector() && VT.isVectorOf(MVT::f16))
897 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
898}
899
901 LLVMContext &, EVT VT) const {
902 if (!VT.isVector())
903 return MVT::i32;
905}
906
908 const MachineFunction &MF, EVT VT) const {
909 if (useSoftFloat())
910 return false;
911
912 VT = VT.getScalarType();
913
914 if (!VT.isSimple())
915 return false;
916
917 switch (VT.getSimpleVT().SimpleTy) {
918 case MVT::f32:
919 case MVT::f64:
920 return true;
921 case MVT::f128:
922 return Subtarget.hasVectorEnhancements1();
923 default:
924 break;
925 }
926
927 return false;
928}
929
930// Return true if the constant can be generated with a vector instruction,
931// such as VGM, VGMB or VREPI.
933 const SystemZSubtarget &Subtarget) {
934 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
935 if (!Subtarget.hasVector() ||
936 (isFP128 && !Subtarget.hasVectorEnhancements1()))
937 return false;
938
939 // Try using VECTOR GENERATE BYTE MASK. This is the architecturally-
940 // preferred way of creating all-zero and all-one vectors so give it
941 // priority over other methods below.
942 unsigned Mask = 0;
943 unsigned I = 0;
944 for (; I < SystemZ::VectorBytes; ++I) {
945 uint64_t Byte = IntBits.lshr(I * 8).trunc(8).getZExtValue();
946 if (Byte == 0xff)
947 Mask |= 1ULL << I;
948 else if (Byte != 0)
949 break;
950 }
951 if (I == SystemZ::VectorBytes) {
952 Opcode = SystemZISD::BYTE_MASK;
953 OpVals.push_back(Mask);
955 return true;
956 }
957
958 if (SplatBitSize > 64)
959 return false;
960
961 auto TryValue = [&](uint64_t Value) -> bool {
962 // Try VECTOR REPLICATE IMMEDIATE
963 int64_t SignedValue = SignExtend64(Value, SplatBitSize);
964 if (isInt<16>(SignedValue)) {
965 OpVals.push_back(((unsigned) SignedValue));
966 Opcode = SystemZISD::REPLICATE;
968 SystemZ::VectorBits / SplatBitSize);
969 return true;
970 }
971 // Try VECTOR GENERATE MASK
972 unsigned Start, End;
973 if (TII->isRxSBGMask(Value, SplatBitSize, Start, End)) {
974 // isRxSBGMask returns the bit numbers for a full 64-bit value, with 0
975 // denoting 1 << 63 and 63 denoting 1. Convert them to bit numbers for
976 // an SplatBitSize value, so that 0 denotes 1 << (SplatBitSize-1).
977 OpVals.push_back(Start - (64 - SplatBitSize));
978 OpVals.push_back(End - (64 - SplatBitSize));
979 Opcode = SystemZISD::ROTATE_MASK;
981 SystemZ::VectorBits / SplatBitSize);
982 return true;
983 }
984 return false;
985 };
986
987 // First try assuming that any undefined bits above the highest set bit
988 // and below the lowest set bit are 1s. This increases the likelihood of
989 // being able to use a sign-extended element value in VECTOR REPLICATE
990 // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
991 uint64_t SplatBitsZ = SplatBits.getZExtValue();
992 uint64_t SplatUndefZ = SplatUndef.getZExtValue();
993 unsigned LowerBits = llvm::countr_zero(SplatBitsZ);
994 unsigned UpperBits = llvm::countl_zero(SplatBitsZ);
995 uint64_t Lower = SplatUndefZ & maskTrailingOnes<uint64_t>(LowerBits);
996 uint64_t Upper = SplatUndefZ & maskLeadingOnes<uint64_t>(UpperBits);
997 if (TryValue(SplatBitsZ | Upper | Lower))
998 return true;
999
1000 // Now try assuming that any undefined bits between the first and
1001 // last defined set bits are set. This increases the chances of
1002 // using a non-wraparound mask.
1003 uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
1004 return TryValue(SplatBitsZ | Middle);
1005}
1006
1008 if (IntImm.isSingleWord()) {
1009 IntBits = APInt(128, IntImm.getZExtValue());
1010 IntBits <<= (SystemZ::VectorBits - IntImm.getBitWidth());
1011 } else
1012 IntBits = IntImm;
1013 assert(IntBits.getBitWidth() == 128 && "Unsupported APInt.");
1014
1015 // Find the smallest splat.
1016 SplatBits = IntImm;
1017 unsigned Width = SplatBits.getBitWidth();
1018 while (Width > 8) {
1019 unsigned HalfSize = Width / 2;
1020 APInt HighValue = SplatBits.lshr(HalfSize).trunc(HalfSize);
1021 APInt LowValue = SplatBits.trunc(HalfSize);
1022
1023 // If the two halves do not match, stop here.
1024 if (HighValue != LowValue || 8 > HalfSize)
1025 break;
1026
1027 SplatBits = HighValue;
1028 Width = HalfSize;
1029 }
1030 SplatUndef = 0;
1031 SplatBitSize = Width;
1032}
1033
1035 assert(BVN->isConstant() && "Expected a constant BUILD_VECTOR");
1036 bool HasAnyUndefs;
1037
1038 // Get IntBits by finding the 128 bit splat.
1039 BVN->isConstantSplat(IntBits, SplatUndef, SplatBitSize, HasAnyUndefs, 128,
1040 true);
1041
1042 // Get SplatBits by finding the 8 bit or greater splat.
1043 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 8,
1044 true);
1045}
1046
1048 bool ForCodeSize) const {
1049 // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
1050 if (Imm.isZero() || Imm.isNegZero())
1051 return true;
1052
1054}
1055
1058 MachineBasicBlock *MBB) const {
1059 DebugLoc DL = MI.getDebugLoc();
1060 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1061 const SystemZRegisterInfo *TRI = Subtarget.getRegisterInfo();
1062
1063 MachineFunction *MF = MBB->getParent();
1064 MachineRegisterInfo &MRI = MF->getRegInfo();
1065
1066 const BasicBlock *BB = MBB->getBasicBlock();
1067 MachineFunction::iterator I = ++MBB->getIterator();
1068
1069 Register DstReg = MI.getOperand(0).getReg();
1070 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
1071 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
1072 (void)TRI;
1073 Register MainDstReg = MRI.createVirtualRegister(RC);
1074 Register RestoreDstReg = MRI.createVirtualRegister(RC);
1075
1076 MVT PVT = getPointerTy(MF->getDataLayout());
1077 assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
1078 // For v = setjmp(buf), we generate.
1079 // Algorithm:
1080 //
1081 // ---------
1082 // | thisMBB |
1083 // ---------
1084 // |
1085 // ------------------------
1086 // | |
1087 // ---------- ---------------
1088 // | mainMBB | | restoreMBB |
1089 // | v = 0 | | v = 1 |
1090 // ---------- ---------------
1091 // | |
1092 // -------------------------
1093 // |
1094 // -----------------------------
1095 // | sinkMBB |
1096 // | phi(v_mainMBB,v_restoreMBB) |
1097 // -----------------------------
1098 // thisMBB:
1099 // buf[FPOffset] = Frame Pointer if hasFP.
1100 // buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB.
1101 // buf[BCOffset] = Backchain value if building with -mbackchain.
1102 // buf[SPOffset] = Stack Pointer.
1103 // buf[LPOffset] = We never write this slot with R13, gcc stores R13 always.
1104 // SjLjSetup restoreMBB
1105 // mainMBB:
1106 // v_main = 0
1107 // sinkMBB:
1108 // v = phi(v_main, v_restore)
1109 // restoreMBB:
1110 // v_restore = 1
1111
1112 MachineBasicBlock *ThisMBB = MBB;
1113 MachineBasicBlock *MainMBB = MF->CreateMachineBasicBlock(BB);
1114 MachineBasicBlock *SinkMBB = MF->CreateMachineBasicBlock(BB);
1115 MachineBasicBlock *RestoreMBB = MF->CreateMachineBasicBlock(BB);
1116
1117 MF->insert(I, MainMBB);
1118 MF->insert(I, SinkMBB);
1119 MF->push_back(RestoreMBB);
1120 RestoreMBB->setMachineBlockAddressTaken();
1121
1123
1124 // Transfer the remainder of BB and its successor edges to sinkMBB.
1125 SinkMBB->splice(SinkMBB->begin(), MBB,
1126 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
1128
1129 // thisMBB:
1130 const int64_t FPOffset = 0; // Slot 1.
1131 const int64_t LabelOffset = 1 * PVT.getStoreSize(); // Slot 2.
1132 const int64_t BCOffset = 2 * PVT.getStoreSize(); // Slot 3.
1133 const int64_t SPOffset = 3 * PVT.getStoreSize(); // Slot 4.
1134
1135 // Buf address.
1136 Register BufReg = MI.getOperand(1).getReg();
1137
1138 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
1139 Register LabelReg = MRI.createVirtualRegister(PtrRC);
1140
1141 // Prepare IP for longjmp.
1142 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::LARL), LabelReg)
1143 .addMBB(RestoreMBB);
1144 // Store IP for return from jmp, slot 2, offset = 1.
1145 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1146 .addReg(LabelReg)
1147 .addReg(BufReg)
1148 .addImm(LabelOffset)
1149 .addReg(0);
1150
1151 auto *SpecialRegs = Subtarget.getSpecialRegisters();
1152 bool HasFP = Subtarget.getFrameLowering()->hasFP(*MF);
1153 if (HasFP) {
1154 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1155 .addReg(SpecialRegs->getFramePointerRegister())
1156 .addReg(BufReg)
1157 .addImm(FPOffset)
1158 .addReg(0);
1159 }
1160
1161 // Store SP.
1162 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1163 .addReg(SpecialRegs->getStackPointerRegister())
1164 .addReg(BufReg)
1165 .addImm(SPOffset)
1166 .addReg(0);
1167
1168 // Slot 3(Offset = 2) Backchain value (if building with -mbackchain).
1169 bool BackChain = MF->getSubtarget<SystemZSubtarget>().hasBackChain();
1170 if (BackChain) {
1171 Register BCReg = MRI.createVirtualRegister(PtrRC);
1172 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
1173 MIB = BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::LG), BCReg)
1174 .addReg(SpecialRegs->getStackPointerRegister())
1175 .addImm(TFL->getBackchainOffset(*MF))
1176 .addReg(0);
1177
1178 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1179 .addReg(BCReg)
1180 .addReg(BufReg)
1181 .addImm(BCOffset)
1182 .addReg(0);
1183 }
1184
1185 // Setup.
1186 MIB = BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::EH_SjLj_Setup))
1187 .addMBB(RestoreMBB);
1188
1189 const SystemZRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1190 MIB.addRegMask(RegInfo->getNoPreservedMask());
1191
1192 ThisMBB->addSuccessor(MainMBB);
1193 ThisMBB->addSuccessor(RestoreMBB);
1194
1195 // mainMBB:
1196 BuildMI(MainMBB, DL, TII->get(SystemZ::LHI), MainDstReg).addImm(0);
1197 MainMBB->addSuccessor(SinkMBB);
1198
1199 // sinkMBB:
1200 BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII->get(SystemZ::PHI), DstReg)
1201 .addReg(MainDstReg)
1202 .addMBB(MainMBB)
1203 .addReg(RestoreDstReg)
1204 .addMBB(RestoreMBB);
1205
1206 // restoreMBB.
1207 BuildMI(RestoreMBB, DL, TII->get(SystemZ::LHI), RestoreDstReg).addImm(1);
1208 BuildMI(RestoreMBB, DL, TII->get(SystemZ::J)).addMBB(SinkMBB);
1209 RestoreMBB->addSuccessor(SinkMBB);
1210
1211 MI.eraseFromParent();
1212
1213 return SinkMBB;
1214}
1215
1218 MachineBasicBlock *MBB) const {
1219
1220 DebugLoc DL = MI.getDebugLoc();
1221 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1222
1223 MachineFunction *MF = MBB->getParent();
1224 MachineRegisterInfo &MRI = MF->getRegInfo();
1225
1226 MVT PVT = getPointerTy(MF->getDataLayout());
1227 assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
1228 Register BufReg = MI.getOperand(0).getReg();
1229 const TargetRegisterClass *RC = MRI.getRegClass(BufReg);
1230 auto *SpecialRegs = Subtarget.getSpecialRegisters();
1231
1232 Register Tmp = MRI.createVirtualRegister(RC);
1233 Register BCReg = MRI.createVirtualRegister(RC);
1234
1236
1237 const int64_t FPOffset = 0;
1238 const int64_t LabelOffset = 1 * PVT.getStoreSize();
1239 const int64_t BCOffset = 2 * PVT.getStoreSize();
1240 const int64_t SPOffset = 3 * PVT.getStoreSize();
1241 const int64_t LPOffset = 4 * PVT.getStoreSize();
1242
1243 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG), Tmp)
1244 .addReg(BufReg)
1245 .addImm(LabelOffset)
1246 .addReg(0);
1247
1248 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG),
1249 SpecialRegs->getFramePointerRegister())
1250 .addReg(BufReg)
1251 .addImm(FPOffset)
1252 .addReg(0);
1253
1254 // We are restoring R13 even though we never stored in setjmp from llvm,
1255 // as gcc always stores R13 in builtin_setjmp. We could have mixed code
1256 // gcc setjmp and llvm longjmp.
1257 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG), SystemZ::R13D)
1258 .addReg(BufReg)
1259 .addImm(LPOffset)
1260 .addReg(0);
1261
1262 bool BackChain = MF->getSubtarget<SystemZSubtarget>().hasBackChain();
1263 if (BackChain) {
1264 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG), BCReg)
1265 .addReg(BufReg)
1266 .addImm(BCOffset)
1267 .addReg(0);
1268 }
1269
1270 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG),
1271 SpecialRegs->getStackPointerRegister())
1272 .addReg(BufReg)
1273 .addImm(SPOffset)
1274 .addReg(0);
1275
1276 if (BackChain) {
1277 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
1278 BuildMI(*MBB, MI, DL, TII->get(SystemZ::STG))
1279 .addReg(BCReg)
1280 .addReg(SpecialRegs->getStackPointerRegister())
1281 .addImm(TFL->getBackchainOffset(*MF))
1282 .addReg(0);
1283 }
1284
1285 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::BR)).addReg(Tmp);
1286
1287 MI.eraseFromParent();
1288 return MBB;
1289}
1290
1291/// Returns true if stack probing through inline assembly is requested.
1293 // If the function specifically requests inline stack probes, emit them.
1294 if (MF.getFunction().hasFnAttribute("probe-stack"))
1295 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
1296 "inline-asm";
1297 return false;
1298}
1299
1304
1309
1312 const AtomicRMWInst *RMW) const {
1313 // Don't expand subword operations as they require special treatment.
1314 if (RMW->getType()->isIntegerTy(8) || RMW->getType()->isIntegerTy(16))
1316
1317 // Don't expand if there is a target instruction available.
1318 if (Subtarget.hasInterlockedAccess1() &&
1319 (RMW->getType()->isIntegerTy(32) || RMW->getType()->isIntegerTy(64)) &&
1326
1328}
1329
1331 // We can use CGFI or CLGFI.
1332 return isInt<32>(Imm) || isUInt<32>(Imm);
1333}
1334
1336 // We can use ALGFI or SLGFI.
1337 return isUInt<32>(Imm) || isUInt<32>(-Imm);
1338}
1339
1341 EVT VT, unsigned, Align, MachineMemOperand::Flags, unsigned *Fast) const {
1342 // Unaligned accesses should never be slower than the expanded version.
1343 // We check specifically for aligned accesses in the few cases where
1344 // they are required.
1345 if (Fast)
1346 *Fast = 1;
1347 return true;
1348}
1349
1351 EVT VT = Y.getValueType();
1352
1353 // We can use NC(G)RK for types in GPRs ...
1354 if (VT == MVT::i32 || VT == MVT::i64)
1355 return Subtarget.hasMiscellaneousExtensions3();
1356
1357 // ... or VNC for types in VRs.
1358 if (VT.isVector() || VT == MVT::i128)
1359 return Subtarget.hasVector();
1360
1361 return false;
1362}
1363
1364// Information about the addressing mode for a memory access.
1366 // True if a long displacement is supported.
1368
1369 // True if use of index register is supported.
1371
1372 AddressingMode(bool LongDispl, bool IdxReg) :
1373 LongDisplacement(LongDispl), IndexReg(IdxReg) {}
1374};
1375
1376// Return the desired addressing mode for a Load which has only one use (in
1377// the same block) which is a Store.
1379 Type *Ty) {
1380 // With vector support a Load->Store combination may be combined to either
1381 // an MVC or vector operations and it seems to work best to allow the
1382 // vector addressing mode.
1383 if (HasVector)
1384 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
1385
1386 // Otherwise only the MVC case is special.
1387 bool MVC = Ty->isIntegerTy(8);
1388 return AddressingMode(!MVC/*LongDispl*/, !MVC/*IdxReg*/);
1389}
1390
1391// Return the addressing mode which seems most desirable given an LLVM
1392// Instruction pointer.
1393static AddressingMode
1396 switch (II->getIntrinsicID()) {
1397 default: break;
1398 case Intrinsic::memset:
1399 case Intrinsic::memmove:
1400 case Intrinsic::memcpy:
1401 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
1402 }
1403 }
1404
1405 if (isa<LoadInst>(I) && I->hasOneUse()) {
1406 auto *SingleUser = cast<Instruction>(*I->user_begin());
1407 if (SingleUser->getParent() == I->getParent()) {
1408 if (isa<ICmpInst>(SingleUser)) {
1409 if (auto *C = dyn_cast<ConstantInt>(SingleUser->getOperand(1)))
1410 if (C->getBitWidth() <= 64 &&
1411 (isInt<16>(C->getSExtValue()) || isUInt<16>(C->getZExtValue())))
1412 // Comparison of memory with 16 bit signed / unsigned immediate
1413 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
1414 } else if (isa<StoreInst>(SingleUser))
1415 // Load->Store
1416 return getLoadStoreAddrMode(HasVector, I->getType());
1417 }
1418 } else if (auto *StoreI = dyn_cast<StoreInst>(I)) {
1419 if (auto *LoadI = dyn_cast<LoadInst>(StoreI->getValueOperand()))
1420 if (LoadI->hasOneUse() && LoadI->getParent() == I->getParent())
1421 // Load->Store
1422 return getLoadStoreAddrMode(HasVector, LoadI->getType());
1423 }
1424
1425 if (HasVector && (isa<LoadInst>(I) || isa<StoreInst>(I))) {
1426
1427 // * Use LDE instead of LE/LEY for z13 to avoid partial register
1428 // dependencies (LDE only supports small offsets).
1429 // * Utilize the vector registers to hold floating point
1430 // values (vector load / store instructions only support small
1431 // offsets).
1432
1433 Type *MemAccessTy = (isa<LoadInst>(I) ? I->getType() :
1434 I->getOperand(0)->getType());
1435 bool IsFPAccess = MemAccessTy->isFloatingPointTy();
1436 bool IsVectorAccess = MemAccessTy->isVectorTy();
1437
1438 // A store of an extracted vector element will be combined into a VSTE type
1439 // instruction.
1440 if (!IsVectorAccess && isa<StoreInst>(I)) {
1441 Value *DataOp = I->getOperand(0);
1442 if (isa<ExtractElementInst>(DataOp))
1443 IsVectorAccess = true;
1444 }
1445
1446 // A load which gets inserted into a vector element will be combined into a
1447 // VLE type instruction.
1448 if (!IsVectorAccess && isa<LoadInst>(I) && I->hasOneUse()) {
1449 User *LoadUser = *I->user_begin();
1450 if (isa<InsertElementInst>(LoadUser))
1451 IsVectorAccess = true;
1452 }
1453
1454 if (IsFPAccess || IsVectorAccess)
1455 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
1456 }
1457
1458 return AddressingMode(true/*LongDispl*/, true/*IdxReg*/);
1459}
1460
1462 const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I) const {
1463 // Punt on globals for now, although they can be used in limited
1464 // RELATIVE LONG cases.
1465 if (AM.BaseGV)
1466 return false;
1467
1468 // Require a 20-bit signed offset.
1469 if (!isInt<20>(AM.BaseOffs))
1470 return false;
1471
1472 bool RequireD12 =
1473 Subtarget.hasVector() && (Ty->isVectorTy() || Ty->isIntegerTy(128));
1474 AddressingMode SupportedAM(!RequireD12, true);
1475 if (I != nullptr)
1476 SupportedAM = supportedAddressingMode(I, Subtarget.hasVector());
1477
1478 if (!SupportedAM.LongDisplacement && !isUInt<12>(AM.BaseOffs))
1479 return false;
1480
1481 if (!SupportedAM.IndexReg)
1482 // No indexing allowed.
1483 return AM.Scale == 0;
1484 else
1485 // Indexing is OK but no scale factor can be applied.
1486 return AM.Scale == 0 || AM.Scale == 1;
1487}
1488
1490 LLVMContext &Context, std::vector<EVT> &MemOps, unsigned Limit,
1491 const MemOp &Op, unsigned DstAS, unsigned SrcAS,
1492 const AttributeList &FuncAttributes, EVT *LargestVT) const {
1493
1494 assert(Limit != ~0U &&
1495 "Expected EmitTargetCodeForMemXXX() to handle AlwaysInline cases.");
1496
1497 if (Op.isZeroMemset())
1498 return false; // Memset zero: Use XC.
1499
1500 const int MVCFastLen = 16;
1501 // Use MVC up to 16 bytes for memcpy. Small memset uses STC/MVI for first
1502 // byte.
1503 if (Op.isMemcpy() && Op.size() <= MVCFastLen)
1504 return false;
1505 if (Op.isMemset() && Op.size() - 1 <= MVCFastLen)
1506 return false;
1507
1508 // Avoid unaligned VL/VST:s.
1509 if ((Op.size() >= 16 && !Op.isAligned(Align(8))) ||
1510 (Op.size() >= 25 && Op.size() <= 31))
1511 return false;
1512
1514 Context, MemOps, Limit, Op, DstAS, SrcAS, FuncAttributes, LargestVT);
1515}
1516
1518 LLVMContext &Context, const MemOp &Op,
1519 const AttributeList &FuncAttributes) const {
1520 return Subtarget.hasVector() ? MVT::v2i64 : MVT::Other;
1521}
1522
1523bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
1524 if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
1525 return false;
1526 unsigned FromBits = FromType->getPrimitiveSizeInBits().getFixedValue();
1527 unsigned ToBits = ToType->getPrimitiveSizeInBits().getFixedValue();
1528 return FromBits > ToBits;
1529}
1530
1532 if (!FromVT.isInteger() || !ToVT.isInteger())
1533 return false;
1534 unsigned FromBits = FromVT.getFixedSizeInBits();
1535 unsigned ToBits = ToVT.getFixedSizeInBits();
1536 return FromBits > ToBits;
1537}
1538
1539//===----------------------------------------------------------------------===//
1540// Inline asm support
1541//===----------------------------------------------------------------------===//
1542
1545 if (Constraint.size() == 1) {
1546 switch (Constraint[0]) {
1547 case 'a': // Address register
1548 case 'd': // Data register (equivalent to 'r')
1549 case 'f': // Floating-point register
1550 case 'h': // High-part register
1551 case 'r': // General-purpose register
1552 case 'v': // Vector register
1553 return C_RegisterClass;
1554
1555 case 'Q': // Memory with base and unsigned 12-bit displacement
1556 case 'R': // Likewise, plus an index
1557 case 'S': // Memory with base and signed 20-bit displacement
1558 case 'T': // Likewise, plus an index
1559 case 'm': // Equivalent to 'T'.
1560 return C_Memory;
1561
1562 case 'I': // Unsigned 8-bit constant
1563 case 'J': // Unsigned 12-bit constant
1564 case 'K': // Signed 16-bit constant
1565 case 'L': // Signed 20-bit displacement (on all targets we support)
1566 case 'M': // 0x7fffffff
1567 return C_Immediate;
1568
1569 default:
1570 break;
1571 }
1572 } else if (Constraint.size() == 2 && Constraint[0] == 'Z') {
1573 switch (Constraint[1]) {
1574 case 'Q': // Address with base and unsigned 12-bit displacement
1575 case 'R': // Likewise, plus an index
1576 case 'S': // Address with base and signed 20-bit displacement
1577 case 'T': // Likewise, plus an index
1578 return C_Address;
1579
1580 default:
1581 break;
1582 }
1583 } else if (Constraint.size() == 5 && Constraint.starts_with("{")) {
1584 if (StringRef("{@cc}").compare(Constraint) == 0)
1585 return C_Other;
1586 }
1587 return TargetLowering::getConstraintType(Constraint);
1588}
1589
1592 AsmOperandInfo &Info, const char *Constraint) const {
1594 Value *CallOperandVal = Info.CallOperandVal;
1595 // If we don't have a value, we can't do a match,
1596 // but allow it at the lowest weight.
1597 if (!CallOperandVal)
1598 return CW_Default;
1599 Type *type = CallOperandVal->getType();
1600 // Look at the constraint type.
1601 switch (*Constraint) {
1602 default:
1603 Weight = TargetLowering::getSingleConstraintMatchWeight(Info, Constraint);
1604 break;
1605
1606 case 'a': // Address register
1607 case 'd': // Data register (equivalent to 'r')
1608 case 'h': // High-part register
1609 case 'r': // General-purpose register
1610 Weight =
1611 CallOperandVal->getType()->isIntegerTy() ? CW_Register : CW_Default;
1612 break;
1613
1614 case 'f': // Floating-point register
1615 if (!useSoftFloat())
1616 Weight = type->isFloatingPointTy() ? CW_Register : CW_Default;
1617 break;
1618
1619 case 'v': // Vector register
1620 if (Subtarget.hasVector())
1621 Weight = (type->isVectorTy() || type->isFloatingPointTy()) ? CW_Register
1622 : CW_Default;
1623 break;
1624
1625 case 'I': // Unsigned 8-bit constant
1626 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1627 if (isUInt<8>(C->getZExtValue()))
1628 Weight = CW_Constant;
1629 break;
1630
1631 case 'J': // Unsigned 12-bit constant
1632 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1633 if (isUInt<12>(C->getZExtValue()))
1634 Weight = CW_Constant;
1635 break;
1636
1637 case 'K': // Signed 16-bit constant
1638 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1639 if (isInt<16>(C->getSExtValue()))
1640 Weight = CW_Constant;
1641 break;
1642
1643 case 'L': // Signed 20-bit displacement (on all targets we support)
1644 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1645 if (isInt<20>(C->getSExtValue()))
1646 Weight = CW_Constant;
1647 break;
1648
1649 case 'M': // 0x7fffffff
1650 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1651 if (C->getZExtValue() == 0x7fffffff)
1652 Weight = CW_Constant;
1653 break;
1654 }
1655 return Weight;
1656}
1657
1658// Parse a "{tNNN}" register constraint for which the register type "t"
1659// has already been verified. MC is the class associated with "t" and
1660// Map maps 0-based register numbers to LLVM register numbers.
1661static std::pair<unsigned, const TargetRegisterClass *>
1663 const unsigned *Map, unsigned Size) {
1664 assert(*(Constraint.end()-1) == '}' && "Missing '}'");
1665 if (isdigit(Constraint[2])) {
1666 unsigned Index;
1667 bool Failed =
1668 Constraint.slice(2, Constraint.size() - 1).getAsInteger(10, Index);
1669 if (!Failed && Index < Size && Map[Index])
1670 return std::make_pair(Map[Index], RC);
1671 }
1672 return std::make_pair(0U, nullptr);
1673}
1674
1675std::pair<unsigned, const TargetRegisterClass *>
1677 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
1678 if (Constraint.size() == 1) {
1679 // GCC Constraint Letters
1680 switch (Constraint[0]) {
1681 default: break;
1682 case 'd': // Data register (equivalent to 'r')
1683 case 'r': // General-purpose register
1684 if (VT.getSizeInBits() == 64)
1685 return std::make_pair(0U, &SystemZ::GR64BitRegClass);
1686 else if (VT.getSizeInBits() == 128)
1687 return std::make_pair(0U, &SystemZ::GR128BitRegClass);
1688 return std::make_pair(0U, &SystemZ::GR32BitRegClass);
1689
1690 case 'a': // Address register
1691 if (VT == MVT::i64)
1692 return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
1693 else if (VT == MVT::i128)
1694 return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
1695 return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
1696
1697 case 'h': // High-part register (an LLVM extension)
1698 return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
1699
1700 case 'f': // Floating-point register
1701 if (!useSoftFloat()) {
1702 if (VT.getSizeInBits() == 16)
1703 return std::make_pair(0U, &SystemZ::FP16BitRegClass);
1704 else if (VT.getSizeInBits() == 64)
1705 return std::make_pair(0U, &SystemZ::FP64BitRegClass);
1706 else if (VT.getSizeInBits() == 128)
1707 return std::make_pair(0U, &SystemZ::FP128BitRegClass);
1708 return std::make_pair(0U, &SystemZ::FP32BitRegClass);
1709 }
1710 break;
1711
1712 case 'v': // Vector register
1713 if (Subtarget.hasVector()) {
1714 if (VT.getSizeInBits() == 16)
1715 return std::make_pair(0U, &SystemZ::VR16BitRegClass);
1716 if (VT.getSizeInBits() == 32)
1717 return std::make_pair(0U, &SystemZ::VR32BitRegClass);
1718 if (VT.getSizeInBits() == 64)
1719 return std::make_pair(0U, &SystemZ::VR64BitRegClass);
1720 return std::make_pair(0U, &SystemZ::VR128BitRegClass);
1721 }
1722 break;
1723 }
1724 }
1725 if (Constraint.starts_with("{")) {
1726
1727 // A clobber constraint (e.g. ~{f0}) will have MVT::Other which is illegal
1728 // to check the size on.
1729 auto getVTSizeInBits = [&VT]() {
1730 return VT == MVT::Other ? 0 : VT.getSizeInBits();
1731 };
1732
1733 // We need to override the default register parsing for GPRs and FPRs
1734 // because the interpretation depends on VT. The internal names of
1735 // the registers are also different from the external names
1736 // (F0D and F0S instead of F0, etc.).
1737 if (Constraint[1] == 'r') {
1738 if (getVTSizeInBits() == 32)
1739 return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
1741 if (getVTSizeInBits() == 128)
1742 return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
1744 return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
1746 }
1747 if (Constraint[1] == 'f') {
1748 if (useSoftFloat())
1749 return std::make_pair(
1750 0u, static_cast<const TargetRegisterClass *>(nullptr));
1751 if (getVTSizeInBits() == 16)
1752 return parseRegisterNumber(Constraint, &SystemZ::FP16BitRegClass,
1754 if (getVTSizeInBits() == 32)
1755 return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
1757 if (getVTSizeInBits() == 128)
1758 return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
1760 return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
1762 }
1763 if (Constraint[1] == 'v') {
1764 if (!Subtarget.hasVector())
1765 return std::make_pair(
1766 0u, static_cast<const TargetRegisterClass *>(nullptr));
1767 if (getVTSizeInBits() == 16)
1768 return parseRegisterNumber(Constraint, &SystemZ::VR16BitRegClass,
1770 if (getVTSizeInBits() == 32)
1771 return parseRegisterNumber(Constraint, &SystemZ::VR32BitRegClass,
1773 if (getVTSizeInBits() == 64)
1774 return parseRegisterNumber(Constraint, &SystemZ::VR64BitRegClass,
1776 return parseRegisterNumber(Constraint, &SystemZ::VR128BitRegClass,
1778 }
1779 if (Constraint[1] == '@') {
1780 if (StringRef("{@cc}").compare(Constraint) == 0)
1781 return std::make_pair(SystemZ::CC, &SystemZ::CCRRegClass);
1782 }
1783 }
1784 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1785}
1786
1787// FIXME? Maybe this could be a TableGen attribute on some registers and
1788// this table could be generated automatically from RegInfo.
1791 const MachineFunction &MF) const {
1792 Register Reg =
1794 .Case("r4", Subtarget.isTargetXPLINK64() ? SystemZ::R4D
1795 : SystemZ::NoRegister)
1796 .Case("r15",
1797 Subtarget.isTargetELF() ? SystemZ::R15D : SystemZ::NoRegister)
1798 .Default(Register());
1799
1800 return Reg;
1801}
1802
1804 ExceptionHandling EH, const Constant *PersonalityFn) const {
1805 return Subtarget.isTargetXPLINK64() ? SystemZ::R1D : SystemZ::R6D;
1806}
1807
1809 ExceptionHandling EH, const Constant *PersonalityFn) const {
1810 return Subtarget.isTargetXPLINK64() ? SystemZ::R2D : SystemZ::R7D;
1811}
1812
1813// Convert condition code in CCReg to an i32 value.
1815 SDLoc DL(CCReg);
1816 SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, CCReg);
1817 return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM,
1818 DAG.getConstant(SystemZ::IPM_CC, DL, MVT::i32));
1819}
1820
1821// Lower @cc targets via setcc.
1823 SDValue &Chain, SDValue &Glue, const SDLoc &DL,
1824 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
1825 if (StringRef("{@cc}").compare(OpInfo.ConstraintCode) != 0)
1826 return SDValue();
1827
1828 // Check that return type is valid.
1829 if (OpInfo.ConstraintVT.isVector() || !OpInfo.ConstraintVT.isInteger() ||
1830 OpInfo.ConstraintVT.getSizeInBits() < 8)
1831 report_fatal_error("Glue output operand is of invalid type");
1832
1833 if (Glue.getNode()) {
1834 Glue = DAG.getCopyFromReg(Chain, DL, SystemZ::CC, MVT::i32, Glue);
1835 Chain = Glue.getValue(1);
1836 } else
1837 Glue = DAG.getCopyFromReg(Chain, DL, SystemZ::CC, MVT::i32);
1838 return getCCResult(DAG, Glue);
1839}
1840
1842 SDValue Op, StringRef Constraint, std::vector<SDValue> &Ops,
1843 SelectionDAG &DAG) const {
1844 // Only support length 1 constraints for now.
1845 if (Constraint.size() == 1) {
1846 switch (Constraint[0]) {
1847 case 'I': // Unsigned 8-bit constant
1848 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1849 if (isUInt<8>(C->getZExtValue()))
1850 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1851 Op.getValueType()));
1852 return;
1853
1854 case 'J': // Unsigned 12-bit constant
1855 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1856 if (isUInt<12>(C->getZExtValue()))
1857 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1858 Op.getValueType()));
1859 return;
1860
1861 case 'K': // Signed 16-bit constant
1862 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1863 if (isInt<16>(C->getSExtValue()))
1864 Ops.push_back(DAG.getSignedTargetConstant(
1865 C->getSExtValue(), SDLoc(Op), Op.getValueType()));
1866 return;
1867
1868 case 'L': // Signed 20-bit displacement (on all targets we support)
1869 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1870 if (isInt<20>(C->getSExtValue()))
1871 Ops.push_back(DAG.getSignedTargetConstant(
1872 C->getSExtValue(), SDLoc(Op), Op.getValueType()));
1873 return;
1874
1875 case 'M': // 0x7fffffff
1876 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1877 if (C->getZExtValue() == 0x7fffffff)
1878 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1879 Op.getValueType()));
1880 return;
1881 }
1882 }
1884}
1885
1886//===----------------------------------------------------------------------===//
1887// Calling conventions
1888//===----------------------------------------------------------------------===//
1889
1890#define GET_CALLING_CONV_IMPL
1891#include "SystemZGenCallingConv.inc"
1892
1894 CallingConv::ID) const {
1895 static const MCPhysReg ScratchRegs[] = { SystemZ::R0D, SystemZ::R1D,
1896 SystemZ::R14D, 0 };
1897 return ScratchRegs;
1898}
1899
1901 Type *ToType) const {
1902 return isTruncateFree(FromType, ToType);
1903}
1904
1906 return CI->isTailCall();
1907}
1908
1909// Value is a value that has been passed to us in the location described by VA
1910// (and so has type VA.getLocVT()). Convert Value to VA.getValVT(), chaining
1911// any loads onto Chain.
1913 CCValAssign &VA, SDValue Chain,
1914 SDValue Value) {
1915 // If the argument has been promoted from a smaller type, insert an
1916 // assertion to capture this.
1917 if (VA.getLocInfo() == CCValAssign::SExt)
1919 DAG.getValueType(VA.getValVT()));
1920 else if (VA.getLocInfo() == CCValAssign::ZExt)
1922 DAG.getValueType(VA.getValVT()));
1923
1924 if (VA.isExtInLoc())
1925 Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
1926 else if (VA.getLocInfo() == CCValAssign::BCvt) {
1927 // If this is a short vector argument loaded from the stack,
1928 // extend from i64 to full vector size and then bitcast.
1929 assert(VA.getLocVT() == MVT::i64);
1930 assert(VA.getValVT().isVector());
1931 Value = DAG.getBuildVector(MVT::v2i64, DL, {Value, DAG.getUNDEF(MVT::i64)});
1932 Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
1933 } else
1934 assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
1935 return Value;
1936}
1937
1938// Value is a value of type VA.getValVT() that we need to copy into
1939// the location described by VA. Return a copy of Value converted to
1940// VA.getValVT(). The caller is responsible for handling indirect values.
1942 CCValAssign &VA, SDValue Value) {
1943 switch (VA.getLocInfo()) {
1944 case CCValAssign::SExt:
1945 return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
1946 case CCValAssign::ZExt:
1947 return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
1948 case CCValAssign::AExt:
1949 return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
1950 case CCValAssign::BCvt: {
1951 assert(VA.getLocVT() == MVT::i64 || VA.getLocVT() == MVT::i128);
1952 assert(VA.getValVT().isVector() || VA.getValVT() == MVT::f32 ||
1953 VA.getValVT() == MVT::f64 || VA.getValVT() == MVT::f128);
1954 // For an f32 vararg we need to first promote it to an f64 and then
1955 // bitcast it to an i64.
1956 if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i64)
1957 Value = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f64, Value);
1958 MVT BitCastToType = VA.getValVT().isVector() && VA.getLocVT() == MVT::i64
1959 ? MVT::v2i64
1960 : VA.getLocVT();
1961 Value = DAG.getNode(ISD::BITCAST, DL, BitCastToType, Value);
1962 // For ELF, this is a short vector argument to be stored to the stack,
1963 // bitcast to v2i64 and then extract first element.
1964 if (BitCastToType == MVT::v2i64)
1965 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
1966 DAG.getConstant(0, DL, MVT::i32));
1967 return Value;
1968 }
1969 case CCValAssign::Full:
1970 return Value;
1971 default:
1972 llvm_unreachable("Unhandled getLocInfo()");
1973 }
1974}
1975
1977 SDLoc DL(In);
1978 SDValue Lo, Hi;
1979 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128)) {
1980 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, In);
1981 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
1982 DAG.getNode(ISD::SRL, DL, MVT::i128, In,
1983 DAG.getConstant(64, DL, MVT::i32)));
1984 } else {
1985 std::tie(Lo, Hi) = DAG.SplitScalar(In, DL, MVT::i64, MVT::i64);
1986 }
1987
1988 // FIXME: If v2i64 were a legal type, we could use it instead of
1989 // Untyped here. This might enable improved folding.
1990 SDNode *Pair = DAG.getMachineNode(SystemZ::PAIR128, DL,
1991 MVT::Untyped, Hi, Lo);
1992 return SDValue(Pair, 0);
1993}
1994
1996 SDLoc DL(In);
1997 SDValue Hi = DAG.getTargetExtractSubreg(SystemZ::subreg_h64,
1998 DL, MVT::i64, In);
1999 SDValue Lo = DAG.getTargetExtractSubreg(SystemZ::subreg_l64,
2000 DL, MVT::i64, In);
2001
2002 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128)) {
2003 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, Lo);
2004 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, Hi);
2005 Hi = DAG.getNode(ISD::SHL, DL, MVT::i128, Hi,
2006 DAG.getConstant(64, DL, MVT::i32));
2007 return DAG.getNode(ISD::OR, DL, MVT::i128, Lo, Hi);
2008 } else {
2009 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128, Lo, Hi);
2010 }
2011}
2012
2014 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
2015 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
2016 EVT ValueVT = Val.getValueType();
2017 if (ValueVT.getSizeInBits() == 128 && NumParts == 1 && PartVT == MVT::Untyped) {
2018 // Inline assembly operand.
2019 Parts[0] = lowerI128ToGR128(DAG, DAG.getBitcast(MVT::i128, Val));
2020 return true;
2021 }
2022
2023 return false;
2024}
2025
2027 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
2028 MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const {
2029 if (ValueVT.getSizeInBits() == 128 && NumParts == 1 && PartVT == MVT::Untyped) {
2030 // Inline assembly operand.
2031 SDValue Res = lowerGR128ToI128(DAG, Parts[0]);
2032 return DAG.getBitcast(ValueVT, Res);
2033 }
2034
2035 return SDValue();
2036}
2037
2038// The first part of a split stack argument is at index I in Args (and
2039// ArgLocs). Return the type of a part and the number of them by reference.
2040template <class ArgTy>
2042 SmallVector<CCValAssign, 16> &ArgLocs, unsigned I,
2043 MVT &PartVT, unsigned &NumParts) {
2044 if (!Args[I].Flags.isSplit())
2045 return false;
2046 assert(I < ArgLocs.size() && ArgLocs.size() == Args.size() &&
2047 "ArgLocs havoc.");
2048 PartVT = ArgLocs[I].getValVT();
2049 NumParts = 1;
2050 for (unsigned PartIdx = I + 1;; ++PartIdx) {
2051 assert(PartIdx != ArgLocs.size() && "SplitEnd not found.");
2052 assert(ArgLocs[PartIdx].getValVT() == PartVT && "Unsupported split.");
2053 ++NumParts;
2054 if (Args[PartIdx].Flags.isSplitEnd())
2055 break;
2056 }
2057 return true;
2058}
2059
2061 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
2062 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2063 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2065 MachineFrameInfo &MFI = MF.getFrameInfo();
2066 MachineRegisterInfo &MRI = MF.getRegInfo();
2067 SystemZMachineFunctionInfo *FuncInfo =
2069 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>();
2070 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2071
2072 // Assign locations to all of the incoming arguments.
2074 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2075 CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
2076 FuncInfo->setSizeOfFnParams(CCInfo.getStackSize());
2077
2078 unsigned NumFixedGPRs = 0;
2079 unsigned NumFixedFPRs = 0;
2080 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
2081 SDValue ArgValue;
2082 CCValAssign &VA = ArgLocs[I];
2083 EVT LocVT = VA.getLocVT();
2084 if (VA.isRegLoc()) {
2085 // Arguments passed in registers
2086 const TargetRegisterClass *RC;
2087 switch (LocVT.getSimpleVT().SimpleTy) {
2088 default:
2089 // Integers smaller than i64 should be promoted to i64.
2090 llvm_unreachable("Unexpected argument type");
2091 case MVT::i32:
2092 NumFixedGPRs += 1;
2093 RC = &SystemZ::GR32BitRegClass;
2094 break;
2095 case MVT::i64:
2096 NumFixedGPRs += 1;
2097 RC = &SystemZ::GR64BitRegClass;
2098 break;
2099 case MVT::f16:
2100 NumFixedFPRs += 1;
2101 RC = &SystemZ::FP16BitRegClass;
2102 break;
2103 case MVT::f32:
2104 NumFixedFPRs += 1;
2105 RC = &SystemZ::FP32BitRegClass;
2106 break;
2107 case MVT::f64:
2108 NumFixedFPRs += 1;
2109 RC = &SystemZ::FP64BitRegClass;
2110 break;
2111 case MVT::f128:
2112 NumFixedFPRs += 2;
2113 RC = &SystemZ::FP128BitRegClass;
2114 break;
2115 case MVT::v16i8:
2116 case MVT::v8i16:
2117 case MVT::v4i32:
2118 case MVT::v2i64:
2119 case MVT::v8f16:
2120 case MVT::v4f32:
2121 case MVT::v2f64:
2122 RC = &SystemZ::VR128BitRegClass;
2123 break;
2124 }
2125
2126 Register VReg = MRI.createVirtualRegister(RC);
2127 MRI.addLiveIn(VA.getLocReg(), VReg);
2128 ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
2129 } else {
2130 assert(VA.isMemLoc() && "Argument not register or memory");
2131
2132 // Create the frame index object for this incoming parameter.
2133 // FIXME: Pre-include call frame size in the offset, should not
2134 // need to manually add it here.
2135 int64_t ArgSPOffset = VA.getLocMemOffset();
2136 if (Subtarget.isTargetXPLINK64()) {
2137 auto &XPRegs =
2138 Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
2139 ArgSPOffset += XPRegs.getCallFrameSize();
2140 }
2141 int FI =
2142 MFI.CreateFixedObject(LocVT.getSizeInBits() / 8, ArgSPOffset, true);
2143
2144 // Create the SelectionDAG nodes corresponding to a load
2145 // from this parameter. Unpromoted ints and floats are
2146 // passed as right-justified 8-byte values.
2147 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2148 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32 ||
2149 VA.getLocVT() == MVT::f16) {
2150 unsigned SlotOffs = VA.getLocVT() == MVT::f16 ? 6 : 4;
2151 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2152 DAG.getIntPtrConstant(SlotOffs, DL));
2153 }
2154 ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
2156 }
2157
2158 // Convert the value of the argument register into the value that's
2159 // being passed.
2160 if (VA.getLocInfo() == CCValAssign::Indirect) {
2161 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
2163 // If the original argument was split (e.g. i128), we need
2164 // to load all parts of it here (using the same address).
2165 MVT PartVT;
2166 unsigned NumParts;
2167 if (analyzeArgSplit(Ins, ArgLocs, I, PartVT, NumParts)) {
2168 for (unsigned PartIdx = 1; PartIdx < NumParts; ++PartIdx) {
2169 ++I;
2170 CCValAssign &PartVA = ArgLocs[I];
2171 unsigned PartOffset = Ins[I].PartOffset;
2172 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
2173 DAG.getIntPtrConstant(PartOffset, DL));
2174 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
2176 assert(PartOffset && "Offset should be non-zero.");
2177 }
2178 }
2179 } else if (Subtarget.isTargetXPLINK64() &&
2180 (VA.getLocInfo() == CCValAssign::SExt ||
2181 VA.getLocInfo() == CCValAssign::ZExt) &&
2182 Ins[I].ArgVT.isSimple()) {
2183 // Some prior z/OS compilers do not always perform the extension of
2184 // short integer arguments or pointers. To accommodate those, do not
2185 // rely on that extension by avoiding any AssertSext/AssertZext nodes by
2186 // directly truncating ArgValue to the original argument type.
2187 MVT OrigVT = Ins[I].ArgVT.getSimpleVT();
2188 InVals.push_back(DAG.getNode(ISD::TRUNCATE, DL, OrigVT, ArgValue));
2189 } else
2190 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
2191 }
2192
2193 if (IsVarArg && Subtarget.isTargetXPLINK64()) {
2194 // Save the number of non-varargs registers for later use by va_start, etc.
2195 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
2196 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
2197
2198 auto *Regs = static_cast<SystemZXPLINK64Registers *>(
2199 Subtarget.getSpecialRegisters());
2200
2201 // Likewise the address (in the form of a frame index) of where the
2202 // first stack vararg would be. The 1-byte size here is arbitrary.
2203 // FIXME: Pre-include call frame size in the offset, should not
2204 // need to manually add it here.
2205 int64_t VarArgOffset = CCInfo.getStackSize() + Regs->getCallFrameSize();
2206 int FI = MFI.CreateFixedObject(1, VarArgOffset, true);
2207 FuncInfo->setVarArgsFrameIndex(FI);
2208 }
2209
2210 if (IsVarArg && Subtarget.isTargetELF()) {
2211 // Save the number of non-varargs registers for later use by va_start, etc.
2212 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
2213 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
2214
2215 // Likewise the address (in the form of a frame index) of where the
2216 // first stack vararg would be. The 1-byte size here is arbitrary.
2217 int64_t VarArgsOffset = CCInfo.getStackSize();
2218 FuncInfo->setVarArgsFrameIndex(
2219 MFI.CreateFixedObject(1, VarArgsOffset, true));
2220
2221 // ...and a similar frame index for the caller-allocated save area
2222 // that will be used to store the incoming registers.
2223 int64_t RegSaveOffset =
2224 -SystemZMC::ELFCallFrameSize + TFL->getRegSpillOffset(MF, SystemZ::R2D) - 16;
2225 unsigned RegSaveIndex = MFI.CreateFixedObject(1, RegSaveOffset, true);
2226 FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
2227
2228 // Store the FPR varargs in the reserved frame slots. (We store the
2229 // GPRs as part of the prologue.)
2230 if (NumFixedFPRs < SystemZ::ELFNumArgFPRs && !useSoftFloat()) {
2232 for (unsigned I = NumFixedFPRs; I < SystemZ::ELFNumArgFPRs; ++I) {
2233 unsigned Offset = TFL->getRegSpillOffset(MF, SystemZ::ELFArgFPRs[I]);
2234 int FI =
2236 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2238 &SystemZ::FP64BitRegClass);
2239 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
2240 MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
2242 }
2243 // Join the stores, which are independent of one another.
2244 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2245 ArrayRef(&MemOps[NumFixedFPRs],
2246 SystemZ::ELFNumArgFPRs - NumFixedFPRs));
2247 }
2248 }
2249
2250 if (Subtarget.isTargetXPLINK64()) {
2251 // Create virual register for handling incoming "ADA" special register (R5)
2252 const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
2253 Register ADAvReg = MRI.createVirtualRegister(RC);
2254 auto *Regs = static_cast<SystemZXPLINK64Registers *>(
2255 Subtarget.getSpecialRegisters());
2256 MRI.addLiveIn(Regs->getADARegister(), ADAvReg);
2257 FuncInfo->setADAVirtualRegister(ADAvReg);
2258 }
2259 return Chain;
2260}
2261
2262static bool canUseSiblingCall(const CCState &ArgCCInfo,
2265 // Punt if there are any indirect or stack arguments, or if the call
2266 // needs the callee-saved argument register R6, or if the call uses
2267 // the callee-saved register arguments SwiftSelf and SwiftError.
2268 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
2269 CCValAssign &VA = ArgLocs[I];
2271 return false;
2272 if (!VA.isRegLoc())
2273 return false;
2274 Register Reg = VA.getLocReg();
2275 if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
2276 return false;
2277 if (Outs[I].Flags.isSwiftSelf() || Outs[I].Flags.isSwiftError())
2278 return false;
2279 }
2280 return true;
2281}
2282
2284 unsigned Offset, bool LoadAdr = false) {
2287 Register ADAvReg = MFI->getADAVirtualRegister();
2289
2290 SDValue Reg = DAG.getRegister(ADAvReg, PtrVT);
2291 SDValue Ofs = DAG.getTargetConstant(Offset, DL, PtrVT);
2292
2293 SDValue Result = DAG.getNode(SystemZISD::ADA_ENTRY, DL, PtrVT, Val, Reg, Ofs);
2294 if (!LoadAdr)
2295 Result = DAG.getLoad(
2296 PtrVT, DL, DAG.getEntryNode(), Result, MachinePointerInfo(), Align(8),
2298
2299 return Result;
2300}
2301
2302// ADA access using Global value
2303// Note: for functions, address of descriptor is returned
2305 EVT PtrVT) {
2306 unsigned ADAtype;
2307 bool LoadAddr = false;
2308 const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV);
2309 bool IsFunction =
2310 (isa<Function>(GV)) || (GA && isa<Function>(GA->getAliaseeObject()));
2311 bool IsInternal = (GV->hasInternalLinkage() || GV->hasPrivateLinkage());
2312
2313 if (IsFunction) {
2314 if (IsInternal) {
2316 LoadAddr = true;
2317 } else
2319 } else {
2321 }
2322 SDValue Val = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ADAtype);
2323
2324 return getADAEntry(DAG, Val, DL, 0, LoadAddr);
2325}
2326
2327static bool getzOSCalleeAndADA(SelectionDAG &DAG, SDValue &Callee, SDValue &ADA,
2328 SDLoc &DL, SDValue &Chain) {
2329 unsigned ADADelta = 0; // ADA offset in desc.
2330 unsigned EPADelta = 8; // EPA offset in desc.
2333
2334 // XPLink calling convention.
2335 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2336 bool IsInternal = (G->getGlobal()->hasInternalLinkage() ||
2337 G->getGlobal()->hasPrivateLinkage());
2338 if (IsInternal) {
2341 Register ADAvReg = MFI->getADAVirtualRegister();
2342 ADA = DAG.getCopyFromReg(Chain, DL, ADAvReg, PtrVT);
2343 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
2344 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2345 return true;
2346 } else {
2348 G->getGlobal(), DL, PtrVT, 0, SystemZII::MO_ADA_DIRECT_FUNC_DESC);
2349 ADA = getADAEntry(DAG, GA, DL, ADADelta);
2350 Callee = getADAEntry(DAG, GA, DL, EPADelta);
2351 }
2352 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2354 E->getSymbol(), PtrVT, SystemZII::MO_ADA_DIRECT_FUNC_DESC);
2355 ADA = getADAEntry(DAG, ES, DL, ADADelta);
2356 Callee = getADAEntry(DAG, ES, DL, EPADelta);
2357 } else {
2358 // Function pointer case
2359 ADA = DAG.getNode(ISD::ADD, DL, PtrVT, Callee,
2360 DAG.getConstant(ADADelta, DL, PtrVT));
2361 ADA = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), ADA,
2363 Callee = DAG.getNode(ISD::ADD, DL, PtrVT, Callee,
2364 DAG.getConstant(EPADelta, DL, PtrVT));
2365 Callee = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Callee,
2367 }
2368 return false;
2369}
2370
2371SDValue
2373 SmallVectorImpl<SDValue> &InVals) const {
2374 SelectionDAG &DAG = CLI.DAG;
2375 SDLoc &DL = CLI.DL;
2377 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2379 SDValue Chain = CLI.Chain;
2380 SDValue Callee = CLI.Callee;
2381 bool &IsTailCall = CLI.IsTailCall;
2382 CallingConv::ID CallConv = CLI.CallConv;
2383 bool IsVarArg = CLI.IsVarArg;
2385 EVT PtrVT = getPointerTy(MF.getDataLayout());
2386 LLVMContext &Ctx = *DAG.getContext();
2387 SystemZCallingConventionRegisters *Regs = Subtarget.getSpecialRegisters();
2388
2389 // FIXME: z/OS support to be added in later.
2390 if (Subtarget.isTargetXPLINK64())
2391 IsTailCall = false;
2392
2393 // Integer args <=32 bits should have an extension attribute.
2394 verifyNarrowIntegerArgs_Call(Outs, &MF.getFunction(), Callee);
2395
2396 // Analyze the operands of the call, assigning locations to each operand.
2398 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, Ctx);
2399 ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
2400
2401 // We don't support GuaranteedTailCallOpt, only automatically-detected
2402 // sibling calls.
2403 if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs, Outs))
2404 IsTailCall = false;
2405
2406 // Get a count of how many bytes are to be pushed on the stack.
2407 unsigned NumBytes = ArgCCInfo.getStackSize();
2408
2409 // Mark the start of the call.
2410 if (!IsTailCall)
2411 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
2412
2413 // Copy argument values to their designated locations.
2415 SmallVector<SDValue, 8> MemOpChains;
2416 SDValue StackPtr;
2417 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
2418 CCValAssign &VA = ArgLocs[I];
2419 SDValue ArgValue = OutVals[I];
2420
2421 if (VA.getLocInfo() == CCValAssign::Indirect) {
2422 // Store the argument in a stack slot and pass its address.
2423 EVT SlotVT;
2424 MVT PartVT;
2425 unsigned NumParts = 1;
2426 if (analyzeArgSplit(Outs, ArgLocs, I, PartVT, NumParts))
2427 SlotVT = EVT::getIntegerVT(Ctx, PartVT.getSizeInBits() * NumParts);
2428 else
2429 SlotVT = Outs[I].VT;
2430 SDValue SpillSlot = DAG.CreateStackTemporary(SlotVT);
2431 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2432
2433 MachinePointerInfo StackPtrInfo =
2435 MemOpChains.push_back(
2436 DAG.getStore(Chain, DL, ArgValue, SpillSlot, StackPtrInfo));
2437 // If the original argument was split (e.g. i128), we need
2438 // to store all parts of it here (and pass just one address).
2439 assert(Outs[I].PartOffset == 0);
2440 for (unsigned PartIdx = 1; PartIdx < NumParts; ++PartIdx) {
2441 ++I;
2442 SDValue PartValue = OutVals[I];
2443 unsigned PartOffset = Outs[I].PartOffset;
2444 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
2445 DAG.getIntPtrConstant(PartOffset, DL));
2446 MemOpChains.push_back(
2447 DAG.getStore(Chain, DL, PartValue, Address,
2448 StackPtrInfo.getWithOffset(PartOffset)));
2449 assert(PartOffset && "Offset should be non-zero.");
2450 assert((PartOffset + PartValue.getValueType().getStoreSize() <=
2451 SlotVT.getStoreSize()) && "Not enough space for argument part!");
2452 }
2453 ArgValue = SpillSlot;
2454 } else
2455 ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
2456
2457 if (VA.isRegLoc()) {
2458 // In XPLINK64, for the 128-bit vararg case, ArgValue is bitcasted to a
2459 // MVT::i128 type. We decompose the 128-bit type to a pair of its high
2460 // and low values.
2461 if (VA.getLocVT() == MVT::i128)
2462 ArgValue = lowerI128ToGR128(DAG, ArgValue);
2463 // Queue up the argument copies and emit them at the end.
2464 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
2465 } else {
2466 assert(VA.isMemLoc() && "Argument not register or memory");
2467
2468 // Work out the address of the stack slot. Unpromoted ints and
2469 // floats are passed as right-justified 8-byte values.
2470 if (!StackPtr.getNode())
2471 StackPtr = DAG.getCopyFromReg(Chain, DL,
2472 Regs->getStackPointerRegister(), PtrVT);
2473 unsigned Offset = Regs->getStackPointerBias() + Regs->getCallFrameSize() +
2474 VA.getLocMemOffset();
2475 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
2476 Offset += 4;
2477 else if (VA.getLocVT() == MVT::f16)
2478 Offset += 6;
2479 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
2481
2482 // Emit the store.
2483 MemOpChains.push_back(
2484 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
2485
2486 // Although long doubles or vectors are passed through the stack when
2487 // they are vararg (non-fixed arguments), if a long double or vector
2488 // occupies the third and fourth slot of the argument list GPR3 should
2489 // still shadow the third slot of the argument list.
2490 if (Subtarget.isTargetXPLINK64() && VA.needsCustom()) {
2491 SDValue ShadowArgValue =
2492 DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, ArgValue,
2493 DAG.getIntPtrConstant(1, DL));
2494 RegsToPass.push_back(std::make_pair(SystemZ::R3D, ShadowArgValue));
2495 }
2496 }
2497 }
2498
2499 // Join the stores, which are independent of one another.
2500 if (!MemOpChains.empty())
2501 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2502
2503 // Accept direct calls by converting symbolic call addresses to the
2504 // associated Target* opcodes. Force %r1 to be used for indirect
2505 // tail calls.
2506 SDValue Glue;
2507
2508 if (Subtarget.isTargetXPLINK64()) {
2509 SDValue ADA;
2510 bool IsBRASL = getzOSCalleeAndADA(DAG, Callee, ADA, DL, Chain);
2511 if (!IsBRASL) {
2512 unsigned CalleeReg = static_cast<SystemZXPLINK64Registers *>(Regs)
2513 ->getAddressOfCalleeRegister();
2514 Chain = DAG.getCopyToReg(Chain, DL, CalleeReg, Callee, Glue);
2515 Glue = Chain.getValue(1);
2516 Callee = DAG.getRegister(CalleeReg, Callee.getValueType());
2517 }
2518 RegsToPass.push_back(std::make_pair(
2519 static_cast<SystemZXPLINK64Registers *>(Regs)->getADARegister(), ADA));
2520 } else {
2521 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2522 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
2523 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2524 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2525 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
2526 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2527 } else if (IsTailCall) {
2528 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
2529 Glue = Chain.getValue(1);
2530 Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
2531 }
2532 }
2533
2534 // Build a sequence of copy-to-reg nodes, chained and glued together.
2535 for (const auto &[Reg, N] : RegsToPass) {
2536 Chain = DAG.getCopyToReg(Chain, DL, Reg, N, Glue);
2537 Glue = Chain.getValue(1);
2538 }
2539
2540 // The first call operand is the chain and the second is the target address.
2542 Ops.push_back(Chain);
2543 Ops.push_back(Callee);
2544
2545 // Add argument registers to the end of the list so that they are
2546 // known live into the call.
2547 for (const auto &[Reg, N] : RegsToPass)
2548 Ops.push_back(DAG.getRegister(Reg, N.getValueType()));
2549
2550 // Add a register mask operand representing the call-preserved registers.
2551 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2552 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2553 assert(Mask && "Missing call preserved mask for calling convention");
2554 Ops.push_back(DAG.getRegisterMask(Mask));
2555
2556 // Glue the call to the argument copies, if any.
2557 if (Glue.getNode())
2558 Ops.push_back(Glue);
2559
2560 // Emit the call.
2561 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2562 if (IsTailCall) {
2563 SDValue Ret = DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
2564 DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge);
2565 return Ret;
2566 }
2567 Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
2568 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2569 Glue = Chain.getValue(1);
2570
2571 // Mark the end of the call, which is glued to the call itself.
2572 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, Glue, DL);
2573 Glue = Chain.getValue(1);
2574
2575 // Assign locations to each value returned by this call.
2577 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, Ctx);
2578 RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
2579
2580 // Copy all of the result registers out of their specified physreg.
2581 for (CCValAssign &VA : RetLocs) {
2582 // Copy the value out, gluing the copy to the end of the call sequence.
2583 SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
2584 VA.getLocVT(), Glue);
2585 Chain = RetValue.getValue(1);
2586 Glue = RetValue.getValue(2);
2587
2588 // Convert the value of the return register into the value that's
2589 // being returned.
2590 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
2591 }
2592
2593 return Chain;
2594}
2595
2596// Generate a call taking the given operands as arguments and returning a
2597// result of type RetVT.
2599 SDValue Chain, SelectionDAG &DAG, const char *CalleeName, EVT RetVT,
2600 ArrayRef<SDValue> Ops, CallingConv::ID CallConv, bool IsSigned, SDLoc DL,
2601 bool DoesNotReturn, bool IsReturnValueUsed) const {
2603 Args.reserve(Ops.size());
2604
2605 for (SDValue Op : Ops) {
2607 Op, Op.getValueType().getTypeForEVT(*DAG.getContext()));
2608 Entry.IsSExt = shouldSignExtendTypeInLibCall(Entry.Ty, IsSigned);
2609 Entry.IsZExt = !Entry.IsSExt;
2610 Args.push_back(Entry);
2611 }
2612
2613 SDValue Callee =
2614 DAG.getExternalSymbol(CalleeName, getPointerTy(DAG.getDataLayout()));
2615
2616 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2618 bool SignExtend = shouldSignExtendTypeInLibCall(RetTy, IsSigned);
2619 CLI.setDebugLoc(DL)
2620 .setChain(Chain)
2621 .setCallee(CallConv, RetTy, Callee, std::move(Args))
2622 .setNoReturn(DoesNotReturn)
2623 .setDiscardResult(!IsReturnValueUsed)
2624 .setSExtResult(SignExtend)
2625 .setZExtResult(!SignExtend);
2626 return LowerCallTo(CLI);
2627}
2628
2630 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
2631 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context,
2632 const Type *RetTy) const {
2633 // Special case that we cannot easily detect in RetCC_SystemZ since
2634 // i128 may not be a legal type.
2635 for (auto &Out : Outs)
2636 if (Out.ArgVT.isScalarInteger() && Out.ArgVT.getSizeInBits() > 64)
2637 return false;
2638
2640 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, Context);
2641 return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ);
2642}
2643
2644SDValue
2646 bool IsVarArg,
2648 const SmallVectorImpl<SDValue> &OutVals,
2649 const SDLoc &DL, SelectionDAG &DAG) const {
2651
2652 // Integer args <=32 bits should have an extension attribute.
2653 verifyNarrowIntegerArgs_Ret(Outs, &MF.getFunction());
2654
2655 // Assign locations to each returned value.
2657 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
2658 RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
2659
2660 // Quick exit for void returns
2661 if (RetLocs.empty())
2662 return DAG.getNode(SystemZISD::RET_GLUE, DL, MVT::Other, Chain);
2663
2664 if (CallConv == CallingConv::GHC)
2665 report_fatal_error("GHC functions return void only");
2666
2667 // Copy the result values into the output registers.
2668 SDValue Glue;
2670 RetOps.push_back(Chain);
2671 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
2672 CCValAssign &VA = RetLocs[I];
2673 SDValue RetValue = OutVals[I];
2674
2675 // Make the return register live on exit.
2676 assert(VA.isRegLoc() && "Can only return in registers!");
2677
2678 // Promote the value as required.
2679 RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
2680
2681 // Chain and glue the copies together.
2682 Register Reg = VA.getLocReg();
2683 Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
2684 Glue = Chain.getValue(1);
2685 RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
2686 }
2687
2688 // Update chain and glue.
2689 RetOps[0] = Chain;
2690 if (Glue.getNode())
2691 RetOps.push_back(Glue);
2692
2693 return DAG.getNode(SystemZISD::RET_GLUE, DL, MVT::Other, RetOps);
2694}
2695
2696// Return true if Op is an intrinsic node with chain that returns the CC value
2697// as its only (other) argument. Provide the associated SystemZISD opcode and
2698// the mask of valid CC values if so.
2699static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
2700 unsigned &CCValid) {
2701 unsigned Id = Op.getConstantOperandVal(1);
2702 switch (Id) {
2703 case Intrinsic::s390_tbegin:
2704 Opcode = SystemZISD::TBEGIN;
2705 CCValid = SystemZ::CCMASK_TBEGIN;
2706 return true;
2707
2708 case Intrinsic::s390_tbegin_nofloat:
2709 Opcode = SystemZISD::TBEGIN_NOFLOAT;
2710 CCValid = SystemZ::CCMASK_TBEGIN;
2711 return true;
2712
2713 case Intrinsic::s390_tend:
2714 Opcode = SystemZISD::TEND;
2715 CCValid = SystemZ::CCMASK_TEND;
2716 return true;
2717
2718 default:
2719 return false;
2720 }
2721}
2722
2723// Return true if Op is an intrinsic node without chain that returns the
2724// CC value as its final argument. Provide the associated SystemZISD
2725// opcode and the mask of valid CC values if so.
2726static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) {
2727 unsigned Id = Op.getConstantOperandVal(0);
2728 switch (Id) {
2729 case Intrinsic::s390_vpkshs:
2730 case Intrinsic::s390_vpksfs:
2731 case Intrinsic::s390_vpksgs:
2732 Opcode = SystemZISD::PACKS_CC;
2733 CCValid = SystemZ::CCMASK_VCMP;
2734 return true;
2735
2736 case Intrinsic::s390_vpklshs:
2737 case Intrinsic::s390_vpklsfs:
2738 case Intrinsic::s390_vpklsgs:
2739 Opcode = SystemZISD::PACKLS_CC;
2740 CCValid = SystemZ::CCMASK_VCMP;
2741 return true;
2742
2743 case Intrinsic::s390_vceqbs:
2744 case Intrinsic::s390_vceqhs:
2745 case Intrinsic::s390_vceqfs:
2746 case Intrinsic::s390_vceqgs:
2747 case Intrinsic::s390_vceqqs:
2748 Opcode = SystemZISD::VICMPES;
2749 CCValid = SystemZ::CCMASK_VCMP;
2750 return true;
2751
2752 case Intrinsic::s390_vchbs:
2753 case Intrinsic::s390_vchhs:
2754 case Intrinsic::s390_vchfs:
2755 case Intrinsic::s390_vchgs:
2756 case Intrinsic::s390_vchqs:
2757 Opcode = SystemZISD::VICMPHS;
2758 CCValid = SystemZ::CCMASK_VCMP;
2759 return true;
2760
2761 case Intrinsic::s390_vchlbs:
2762 case Intrinsic::s390_vchlhs:
2763 case Intrinsic::s390_vchlfs:
2764 case Intrinsic::s390_vchlgs:
2765 case Intrinsic::s390_vchlqs:
2766 Opcode = SystemZISD::VICMPHLS;
2767 CCValid = SystemZ::CCMASK_VCMP;
2768 return true;
2769
2770 case Intrinsic::s390_vtm:
2771 Opcode = SystemZISD::VTM;
2772 CCValid = SystemZ::CCMASK_VCMP;
2773 return true;
2774
2775 case Intrinsic::s390_vfaebs:
2776 case Intrinsic::s390_vfaehs:
2777 case Intrinsic::s390_vfaefs:
2778 Opcode = SystemZISD::VFAE_CC;
2779 CCValid = SystemZ::CCMASK_ANY;
2780 return true;
2781
2782 case Intrinsic::s390_vfaezbs:
2783 case Intrinsic::s390_vfaezhs:
2784 case Intrinsic::s390_vfaezfs:
2785 Opcode = SystemZISD::VFAEZ_CC;
2786 CCValid = SystemZ::CCMASK_ANY;
2787 return true;
2788
2789 case Intrinsic::s390_vfeebs:
2790 case Intrinsic::s390_vfeehs:
2791 case Intrinsic::s390_vfeefs:
2792 Opcode = SystemZISD::VFEE_CC;
2793 CCValid = SystemZ::CCMASK_ANY;
2794 return true;
2795
2796 case Intrinsic::s390_vfeezbs:
2797 case Intrinsic::s390_vfeezhs:
2798 case Intrinsic::s390_vfeezfs:
2799 Opcode = SystemZISD::VFEEZ_CC;
2800 CCValid = SystemZ::CCMASK_ANY;
2801 return true;
2802
2803 case Intrinsic::s390_vfenebs:
2804 case Intrinsic::s390_vfenehs:
2805 case Intrinsic::s390_vfenefs:
2806 Opcode = SystemZISD::VFENE_CC;
2807 CCValid = SystemZ::CCMASK_ANY;
2808 return true;
2809
2810 case Intrinsic::s390_vfenezbs:
2811 case Intrinsic::s390_vfenezhs:
2812 case Intrinsic::s390_vfenezfs:
2813 Opcode = SystemZISD::VFENEZ_CC;
2814 CCValid = SystemZ::CCMASK_ANY;
2815 return true;
2816
2817 case Intrinsic::s390_vistrbs:
2818 case Intrinsic::s390_vistrhs:
2819 case Intrinsic::s390_vistrfs:
2820 Opcode = SystemZISD::VISTR_CC;
2822 return true;
2823
2824 case Intrinsic::s390_vstrcbs:
2825 case Intrinsic::s390_vstrchs:
2826 case Intrinsic::s390_vstrcfs:
2827 Opcode = SystemZISD::VSTRC_CC;
2828 CCValid = SystemZ::CCMASK_ANY;
2829 return true;
2830
2831 case Intrinsic::s390_vstrczbs:
2832 case Intrinsic::s390_vstrczhs:
2833 case Intrinsic::s390_vstrczfs:
2834 Opcode = SystemZISD::VSTRCZ_CC;
2835 CCValid = SystemZ::CCMASK_ANY;
2836 return true;
2837
2838 case Intrinsic::s390_vstrsb:
2839 case Intrinsic::s390_vstrsh:
2840 case Intrinsic::s390_vstrsf:
2841 Opcode = SystemZISD::VSTRS_CC;
2842 CCValid = SystemZ::CCMASK_ANY;
2843 return true;
2844
2845 case Intrinsic::s390_vstrszb:
2846 case Intrinsic::s390_vstrszh:
2847 case Intrinsic::s390_vstrszf:
2848 Opcode = SystemZISD::VSTRSZ_CC;
2849 CCValid = SystemZ::CCMASK_ANY;
2850 return true;
2851
2852 case Intrinsic::s390_vfcedbs:
2853 case Intrinsic::s390_vfcesbs:
2854 Opcode = SystemZISD::VFCMPES;
2855 CCValid = SystemZ::CCMASK_VCMP;
2856 return true;
2857
2858 case Intrinsic::s390_vfchdbs:
2859 case Intrinsic::s390_vfchsbs:
2860 Opcode = SystemZISD::VFCMPHS;
2861 CCValid = SystemZ::CCMASK_VCMP;
2862 return true;
2863
2864 case Intrinsic::s390_vfchedbs:
2865 case Intrinsic::s390_vfchesbs:
2866 Opcode = SystemZISD::VFCMPHES;
2867 CCValid = SystemZ::CCMASK_VCMP;
2868 return true;
2869
2870 case Intrinsic::s390_vftcidb:
2871 case Intrinsic::s390_vftcisb:
2872 Opcode = SystemZISD::VFTCI;
2873 CCValid = SystemZ::CCMASK_VCMP;
2874 return true;
2875
2876 case Intrinsic::s390_tdc:
2877 Opcode = SystemZISD::TDC;
2878 CCValid = SystemZ::CCMASK_TDC;
2879 return true;
2880
2881 default:
2882 return false;
2883 }
2884}
2885
2886// Emit an intrinsic with chain and an explicit CC register result.
2888 unsigned Opcode) {
2889 // Copy all operands except the intrinsic ID.
2890 unsigned NumOps = Op.getNumOperands();
2892 Ops.reserve(NumOps - 1);
2893 Ops.push_back(Op.getOperand(0));
2894 for (unsigned I = 2; I < NumOps; ++I)
2895 Ops.push_back(Op.getOperand(I));
2896
2897 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
2898 SDVTList RawVTs = DAG.getVTList(MVT::i32, MVT::Other);
2899 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
2900 SDValue OldChain = SDValue(Op.getNode(), 1);
2901 SDValue NewChain = SDValue(Intr.getNode(), 1);
2902 DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
2903 return Intr.getNode();
2904}
2905
2906// Emit an intrinsic with an explicit CC register result.
2908 unsigned Opcode) {
2909 // Copy all operands except the intrinsic ID.
2910 SDLoc DL(Op);
2911 unsigned NumOps = Op.getNumOperands();
2913 Ops.reserve(NumOps - 1);
2914 for (unsigned I = 1; I < NumOps; ++I) {
2915 SDValue CurrOper = Op.getOperand(I);
2916 if (CurrOper.getValueType() == MVT::f16) {
2917 assert((Op.getConstantOperandVal(0) == Intrinsic::s390_tdc && I == 1) &&
2918 "Unhandled intrinsic with f16 operand.");
2919 CurrOper = DAG.getFPExtendOrRound(CurrOper, DL, MVT::f32);
2920 }
2921 Ops.push_back(CurrOper);
2922 }
2923
2924 SDValue Intr = DAG.getNode(Opcode, DL, Op->getVTList(), Ops);
2925 return Intr.getNode();
2926}
2927
2928// CC is a comparison that will be implemented using an integer or
2929// floating-point comparison. Return the condition code mask for
2930// a branch on true. In the integer case, CCMASK_CMP_UO is set for
2931// unsigned comparisons and clear for signed ones. In the floating-point
2932// case, CCMASK_CMP_UO has its normal mask meaning (unordered).
2934#define CONV(X) \
2935 case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
2936 case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
2937 case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
2938
2939 switch (CC) {
2940 default:
2941 llvm_unreachable("Invalid integer condition!");
2942
2943 CONV(EQ);
2944 CONV(NE);
2945 CONV(GT);
2946 CONV(GE);
2947 CONV(LT);
2948 CONV(LE);
2949
2950 case ISD::SETO: return SystemZ::CCMASK_CMP_O;
2952 }
2953#undef CONV
2954}
2955
2956// If C can be converted to a comparison against zero, adjust the operands
2957// as necessary.
2958static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
2959 if (C.ICmpType == SystemZICMP::UnsignedOnly)
2960 return;
2961
2962 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
2963 if (!ConstOp1 || ConstOp1->getValueSizeInBits(0) > 64)
2964 return;
2965
2966 int64_t Value = ConstOp1->getSExtValue();
2967 if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
2968 (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
2969 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
2970 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
2971 C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
2972 C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
2973 }
2974}
2975
2976// If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
2977// adjust the operands as necessary.
2978static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL,
2979 Comparison &C) {
2980 // For us to make any changes, it must a comparison between a single-use
2981 // load and a constant.
2982 if (!C.Op0.hasOneUse() ||
2983 C.Op0.getOpcode() != ISD::LOAD ||
2984 C.Op1.getOpcode() != ISD::Constant)
2985 return;
2986
2987 // We must have an 8- or 16-bit load.
2988 auto *Load = cast<LoadSDNode>(C.Op0);
2989 unsigned NumBits = Load->getMemoryVT().getSizeInBits();
2990 if ((NumBits != 8 && NumBits != 16) ||
2991 NumBits != Load->getMemoryVT().getStoreSizeInBits())
2992 return;
2993
2994 // The load must be an extending one and the constant must be within the
2995 // range of the unextended value.
2996 auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
2997 if (!ConstOp1 || ConstOp1->getValueSizeInBits(0) > 64)
2998 return;
2999 uint64_t Value = ConstOp1->getZExtValue();
3000 uint64_t Mask = (1 << NumBits) - 1;
3001 if (Load->getExtensionType() == ISD::SEXTLOAD) {
3002 // Make sure that ConstOp1 is in range of C.Op0.
3003 int64_t SignedValue = ConstOp1->getSExtValue();
3004 if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
3005 return;
3006 if (C.ICmpType != SystemZICMP::SignedOnly) {
3007 // Unsigned comparison between two sign-extended values is equivalent
3008 // to unsigned comparison between two zero-extended values.
3009 Value &= Mask;
3010 } else if (NumBits == 8) {
3011 // Try to treat the comparison as unsigned, so that we can use CLI.
3012 // Adjust CCMask and Value as necessary.
3013 if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
3014 // Test whether the high bit of the byte is set.
3015 Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
3016 else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
3017 // Test whether the high bit of the byte is clear.
3018 Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
3019 else
3020 // No instruction exists for this combination.
3021 return;
3022 C.ICmpType = SystemZICMP::UnsignedOnly;
3023 }
3024 } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
3025 if (Value > Mask)
3026 return;
3027 // If the constant is in range, we can use any comparison.
3028 C.ICmpType = SystemZICMP::Any;
3029 } else
3030 return;
3031
3032 // Make sure that the first operand is an i32 of the right extension type.
3033 ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
3036 if (C.Op0.getValueType() != MVT::i32 ||
3037 Load->getExtensionType() != ExtType) {
3038 C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32, Load->getChain(),
3039 Load->getBasePtr(), Load->getPointerInfo(),
3040 Load->getMemoryVT(), Load->getAlign(),
3041 Load->getMemOperand()->getFlags());
3042 // Update the chain uses.
3043 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), C.Op0.getValue(1));
3044 }
3045
3046 // Make sure that the second operand is an i32 with the right value.
3047 if (C.Op1.getValueType() != MVT::i32 ||
3048 Value != ConstOp1->getZExtValue())
3049 C.Op1 = DAG.getConstant((uint32_t)Value, DL, MVT::i32);
3050}
3051
3052// Return true if Op is either an unextended load, or a load suitable
3053// for integer register-memory comparisons of type ICmpType.
3054static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
3055 auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
3056 if (Load) {
3057 // There are no instructions to compare a register with a memory byte.
3058 if (Load->getMemoryVT() == MVT::i8)
3059 return false;
3060 // Otherwise decide on extension type.
3061 switch (Load->getExtensionType()) {
3062 case ISD::NON_EXTLOAD:
3063 return true;
3064 case ISD::SEXTLOAD:
3065 return ICmpType != SystemZICMP::UnsignedOnly;
3066 case ISD::ZEXTLOAD:
3067 return ICmpType != SystemZICMP::SignedOnly;
3068 default:
3069 break;
3070 }
3071 }
3072 return false;
3073}
3074
3075// Return true if it is better to swap the operands of C.
3076static bool shouldSwapCmpOperands(const Comparison &C) {
3077 // If one side of the compare is a load of the stackguard reference value,
3078 // then that load should be Op1.
3079 if (C.Op0.isMachineOpcode() &&
3080 (C.Op0.getMachineOpcode() == SystemZ::LOAD_STACK_GUARD))
3081 return true;
3082
3083 // Leave i128 and f128 comparisons alone, since they have no memory forms.
3084 if (C.Op0.getValueType() == MVT::i128)
3085 return false;
3086 if (C.Op0.getValueType() == MVT::f128)
3087 return false;
3088
3089 // Always keep a floating-point constant second, since comparisons with
3090 // zero can use LOAD TEST and comparisons with other constants make a
3091 // natural memory operand.
3092 if (isa<ConstantFPSDNode>(C.Op1))
3093 return false;
3094
3095 // Never swap comparisons with zero since there are many ways to optimize
3096 // those later.
3097 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
3098 if (ConstOp1 && ConstOp1->getZExtValue() == 0)
3099 return false;
3100
3101 // Also keep natural memory operands second if the loaded value is
3102 // only used here. Several comparisons have memory forms.
3103 if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
3104 return false;
3105
3106 // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
3107 // In that case we generally prefer the memory to be second.
3108 if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
3109 // The only exceptions are when the second operand is a constant and
3110 // we can use things like CHHSI.
3111 if (!ConstOp1)
3112 return true;
3113 // The unsigned memory-immediate instructions can handle 16-bit
3114 // unsigned integers.
3115 if (C.ICmpType != SystemZICMP::SignedOnly &&
3116 isUInt<16>(ConstOp1->getZExtValue()))
3117 return false;
3118 // The signed memory-immediate instructions can handle 16-bit
3119 // signed integers.
3120 if (C.ICmpType != SystemZICMP::UnsignedOnly &&
3121 isInt<16>(ConstOp1->getSExtValue()))
3122 return false;
3123 return true;
3124 }
3125
3126 // Try to promote the use of CGFR and CLGFR.
3127 unsigned Opcode0 = C.Op0.getOpcode();
3128 if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
3129 return true;
3130 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
3131 return true;
3132 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::AND &&
3133 C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
3134 C.Op0.getConstantOperandVal(1) == 0xffffffff)
3135 return true;
3136
3137 return false;
3138}
3139
3140// Check whether C tests for equality between X and Y and whether X - Y
3141// or Y - X is also computed. In that case it's better to compare the
3142// result of the subtraction against zero.
3144 Comparison &C) {
3145 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3146 C.CCMask == SystemZ::CCMASK_CMP_NE) {
3147 for (SDNode *N : C.Op0->users()) {
3148 if (N->getOpcode() == ISD::SUB &&
3149 ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
3150 (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
3151 // Disable the nsw and nuw flags: the backend needs to handle
3152 // overflow as well during comparison elimination.
3153 N->dropFlags(SDNodeFlags::NoWrap);
3154 C.Op0 = SDValue(N, 0);
3155 C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
3156 return;
3157 }
3158 }
3159 }
3160}
3161
3162// Check whether C compares a floating-point value with zero and if that
3163// floating-point value is also negated. In this case we can use the
3164// negation to set CC, so avoiding separate LOAD AND TEST and
3165// LOAD (NEGATIVE/COMPLEMENT) instructions.
3166static void adjustForFNeg(Comparison &C) {
3167 // This optimization is invalid for strict comparisons, since FNEG
3168 // does not raise any exceptions.
3169 if (C.Chain)
3170 return;
3171 auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
3172 if (C1 && C1->isZero()) {
3173 for (SDNode *N : C.Op0->users()) {
3174 if (N->getOpcode() == ISD::FNEG) {
3175 C.Op0 = SDValue(N, 0);
3176 C.CCMask = SystemZ::reverseCCMask(C.CCMask);
3177 return;
3178 }
3179 }
3180 }
3181}
3182
3183// Check whether C compares (shl X, 32) with 0 and whether X is
3184// also sign-extended. In that case it is better to test the result
3185// of the sign extension using LTGFR.
3186//
3187// This case is important because InstCombine transforms a comparison
3188// with (sext (trunc X)) into a comparison with (shl X, 32).
3189static void adjustForLTGFR(Comparison &C) {
3190 // Check for a comparison between (shl X, 32) and 0.
3191 if (C.Op0.getOpcode() == ISD::SHL && C.Op0.getValueType() == MVT::i64 &&
3192 C.Op1.getOpcode() == ISD::Constant && C.Op1->getAsZExtVal() == 0) {
3193 auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
3194 if (C1 && C1->getZExtValue() == 32) {
3195 SDValue ShlOp0 = C.Op0.getOperand(0);
3196 // See whether X has any SIGN_EXTEND_INREG uses.
3197 for (SDNode *N : ShlOp0->users()) {
3198 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
3199 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
3200 C.Op0 = SDValue(N, 0);
3201 return;
3202 }
3203 }
3204 }
3205 }
3206}
3207
3208// If C compares the truncation of an extending load, try to compare
3209// the untruncated value instead. This exposes more opportunities to
3210// reuse CC.
3211static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL,
3212 Comparison &C) {
3213 if (C.Op0.getOpcode() == ISD::TRUNCATE &&
3214 C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
3215 C.Op1.getOpcode() == ISD::Constant &&
3216 cast<ConstantSDNode>(C.Op1)->getValueSizeInBits(0) <= 64 &&
3217 C.Op1->getAsZExtVal() == 0) {
3218 auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
3219 if (L->getMemoryVT().getStoreSizeInBits().getFixedValue() <=
3220 C.Op0.getValueSizeInBits().getFixedValue()) {
3221 unsigned Type = L->getExtensionType();
3222 if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
3223 (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
3224 C.Op0 = C.Op0.getOperand(0);
3225 C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
3226 }
3227 }
3228 }
3229}
3230
3231// Adjust if a given Compare is a check of the stack guard against a stack
3232// guard instance on the stack. Specifically, this checks if:
3233// - The operands are a load of the stack guard, and a load from a stack slot
3234// - The original opcode is ICMP
3235// - ICMPType is compatible with unsigned comparison.
3237 Comparison &C) {
3238
3239 // Opcode must be ICMP.
3240 if (C.Opcode != SystemZISD::ICMP)
3241 return;
3242 // ICmpType must be Unsigned or Any.
3243 if (C.ICmpType == SystemZICMP::SignedOnly)
3244 return;
3245 // Op0 must be FrameIndex Load.
3246 if (!(ISD::isNormalLoad(C.Op0.getNode()) &&
3247 dyn_cast<FrameIndexSDNode>(C.Op0.getOperand(1))))
3248 return;
3249 // Op1 must be LOAD_STACK_GUARD.
3250 if (!C.Op1.isMachineOpcode() ||
3251 C.Op1.getMachineOpcode() != SystemZ::LOAD_STACK_GUARD)
3252 return;
3253
3254 // At this point we are sure that this is a proper CMP_STACKGUARD
3255 // case, update the opcode to reflect this.
3256 C.Opcode = SystemZISD::CMP_STACKGUARD;
3257 C.Op1 = SDValue();
3258}
3259
3260// Return true if shift operation N has an in-range constant shift value.
3261// Store it in ShiftVal if so.
3262static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
3263 auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
3264 if (!Shift)
3265 return false;
3266
3267 uint64_t Amount = Shift->getZExtValue();
3268 if (Amount >= N.getValueSizeInBits())
3269 return false;
3270
3271 ShiftVal = Amount;
3272 return true;
3273}
3274
3275// Check whether an AND with Mask is suitable for a TEST UNDER MASK
3276// instruction and whether the CC value is descriptive enough to handle
3277// a comparison of type Opcode between the AND result and CmpVal.
3278// CCMask says which comparison result is being tested and BitSize is
3279// the number of bits in the operands. If TEST UNDER MASK can be used,
3280// return the corresponding CC mask, otherwise return 0.
3281static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
3282 uint64_t Mask, uint64_t CmpVal,
3283 unsigned ICmpType) {
3284 assert(Mask != 0 && "ANDs with zero should have been removed by now");
3285
3286 // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
3287 if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
3288 !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
3289 return 0;
3290
3291 // Work out the masks for the lowest and highest bits.
3293 uint64_t Low = uint64_t(1) << llvm::countr_zero(Mask);
3294
3295 // Signed ordered comparisons are effectively unsigned if the sign
3296 // bit is dropped.
3297 bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
3298
3299 // Check for equality comparisons with 0, or the equivalent.
3300 if (CmpVal == 0) {
3301 if (CCMask == SystemZ::CCMASK_CMP_EQ)
3303 if (CCMask == SystemZ::CCMASK_CMP_NE)
3305 }
3306 if (EffectivelyUnsigned && CmpVal > 0 && CmpVal <= Low) {
3307 if (CCMask == SystemZ::CCMASK_CMP_LT)
3309 if (CCMask == SystemZ::CCMASK_CMP_GE)
3311 }
3312 if (EffectivelyUnsigned && CmpVal < Low) {
3313 if (CCMask == SystemZ::CCMASK_CMP_LE)
3315 if (CCMask == SystemZ::CCMASK_CMP_GT)
3317 }
3318
3319 // Check for equality comparisons with the mask, or the equivalent.
3320 if (CmpVal == Mask) {
3321 if (CCMask == SystemZ::CCMASK_CMP_EQ)
3323 if (CCMask == SystemZ::CCMASK_CMP_NE)
3325 }
3326 if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
3327 if (CCMask == SystemZ::CCMASK_CMP_GT)
3329 if (CCMask == SystemZ::CCMASK_CMP_LE)
3331 }
3332 if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
3333 if (CCMask == SystemZ::CCMASK_CMP_GE)
3335 if (CCMask == SystemZ::CCMASK_CMP_LT)
3337 }
3338
3339 // Check for ordered comparisons with the top bit.
3340 if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
3341 if (CCMask == SystemZ::CCMASK_CMP_LE)
3343 if (CCMask == SystemZ::CCMASK_CMP_GT)
3345 }
3346 if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
3347 if (CCMask == SystemZ::CCMASK_CMP_LT)
3349 if (CCMask == SystemZ::CCMASK_CMP_GE)
3351 }
3352
3353 // If there are just two bits, we can do equality checks for Low and High
3354 // as well.
3355 if (Mask == Low + High) {
3356 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
3358 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
3360 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
3362 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
3364 }
3365
3366 // Looks like we've exhausted our options.
3367 return 0;
3368}
3369
3370// See whether C can be implemented as a TEST UNDER MASK instruction.
3371// Update the arguments with the TM version if so.
3373 Comparison &C) {
3374 // Use VECTOR TEST UNDER MASK for i128 operations.
3375 if (C.Op0.getValueType() == MVT::i128) {
3376 // We can use VTM for EQ/NE comparisons of x & y against 0.
3377 if (C.Op0.getOpcode() == ISD::AND &&
3378 (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3379 C.CCMask == SystemZ::CCMASK_CMP_NE)) {
3380 auto *Mask = dyn_cast<ConstantSDNode>(C.Op1);
3381 if (Mask && Mask->getAPIntValue() == 0) {
3382 C.Opcode = SystemZISD::VTM;
3383 C.Op1 = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, C.Op0.getOperand(1));
3384 C.Op0 = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, C.Op0.getOperand(0));
3385 C.CCValid = SystemZ::CCMASK_VCMP;
3386 if (C.CCMask == SystemZ::CCMASK_CMP_EQ)
3387 C.CCMask = SystemZ::CCMASK_VCMP_ALL;
3388 else
3389 C.CCMask = SystemZ::CCMASK_VCMP_ALL ^ C.CCValid;
3390 }
3391 }
3392 return;
3393 }
3394
3395 // Check that we have a comparison with a constant.
3396 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
3397 if (!ConstOp1)
3398 return;
3399 uint64_t CmpVal = ConstOp1->getZExtValue();
3400
3401 // Check whether the nonconstant input is an AND with a constant mask.
3402 Comparison NewC(C);
3403 uint64_t MaskVal;
3404 ConstantSDNode *Mask = nullptr;
3405 if (C.Op0.getOpcode() == ISD::AND) {
3406 NewC.Op0 = C.Op0.getOperand(0);
3407 NewC.Op1 = C.Op0.getOperand(1);
3408 Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
3409 if (!Mask)
3410 return;
3411 MaskVal = Mask->getZExtValue();
3412 } else {
3413 // There is no instruction to compare with a 64-bit immediate
3414 // so use TMHH instead if possible. We need an unsigned ordered
3415 // comparison with an i64 immediate.
3416 if (NewC.Op0.getValueType() != MVT::i64 ||
3417 NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
3418 NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
3419 NewC.ICmpType == SystemZICMP::SignedOnly)
3420 return;
3421 // Convert LE and GT comparisons into LT and GE.
3422 if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
3423 NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
3424 if (CmpVal == uint64_t(-1))
3425 return;
3426 CmpVal += 1;
3427 NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
3428 }
3429 // If the low N bits of Op1 are zero than the low N bits of Op0 can
3430 // be masked off without changing the result.
3431 MaskVal = -(CmpVal & -CmpVal);
3432 NewC.ICmpType = SystemZICMP::UnsignedOnly;
3433 }
3434 if (!MaskVal)
3435 return;
3436
3437 // Check whether the combination of mask, comparison value and comparison
3438 // type are suitable.
3439 unsigned BitSize = NewC.Op0.getValueSizeInBits();
3440 unsigned NewCCMask, ShiftVal;
3441 if (NewC.ICmpType != SystemZICMP::SignedOnly &&
3442 NewC.Op0.getOpcode() == ISD::SHL &&
3443 isSimpleShift(NewC.Op0, ShiftVal) &&
3444 (MaskVal >> ShiftVal != 0) &&
3445 ((CmpVal >> ShiftVal) << ShiftVal) == CmpVal &&
3446 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
3447 MaskVal >> ShiftVal,
3448 CmpVal >> ShiftVal,
3449 SystemZICMP::Any))) {
3450 NewC.Op0 = NewC.Op0.getOperand(0);
3451 MaskVal >>= ShiftVal;
3452 } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
3453 NewC.Op0.getOpcode() == ISD::SRL &&
3454 isSimpleShift(NewC.Op0, ShiftVal) &&
3455 (MaskVal << ShiftVal != 0) &&
3456 ((CmpVal << ShiftVal) >> ShiftVal) == CmpVal &&
3457 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
3458 MaskVal << ShiftVal,
3459 CmpVal << ShiftVal,
3461 NewC.Op0 = NewC.Op0.getOperand(0);
3462 MaskVal <<= ShiftVal;
3463 } else {
3464 NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
3465 NewC.ICmpType);
3466 if (!NewCCMask)
3467 return;
3468 }
3469
3470 // Go ahead and make the change.
3471 C.Opcode = SystemZISD::TM;
3472 C.Op0 = NewC.Op0;
3473 if (Mask && Mask->getZExtValue() == MaskVal)
3474 C.Op1 = SDValue(Mask, 0);
3475 else
3476 C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
3477 C.CCValid = SystemZ::CCMASK_TM;
3478 C.CCMask = NewCCMask;
3479}
3480
3481// Implement i128 comparison in vector registers.
3482static void adjustICmp128(SelectionDAG &DAG, const SDLoc &DL,
3483 Comparison &C) {
3484 if (C.Opcode != SystemZISD::ICMP)
3485 return;
3486 if (C.Op0.getValueType() != MVT::i128)
3487 return;
3488
3489 // Recognize vector comparison reductions.
3490 if ((C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3491 C.CCMask == SystemZ::CCMASK_CMP_NE) &&
3492 (isNullConstant(C.Op1) || isAllOnesConstant(C.Op1))) {
3493 bool CmpEq = C.CCMask == SystemZ::CCMASK_CMP_EQ;
3494 bool CmpNull = isNullConstant(C.Op1);
3495 SDValue Src = peekThroughBitcasts(C.Op0);
3496 if (Src.hasOneUse() && isBitwiseNot(Src)) {
3497 Src = Src.getOperand(0);
3498 CmpNull = !CmpNull;
3499 }
3500 unsigned Opcode = 0;
3501 if (Src.hasOneUse()) {
3502 switch (Src.getOpcode()) {
3503 case SystemZISD::VICMPE: Opcode = SystemZISD::VICMPES; break;
3504 case SystemZISD::VICMPH: Opcode = SystemZISD::VICMPHS; break;
3505 case SystemZISD::VICMPHL: Opcode = SystemZISD::VICMPHLS; break;
3506 case SystemZISD::VFCMPE: Opcode = SystemZISD::VFCMPES; break;
3507 case SystemZISD::VFCMPH: Opcode = SystemZISD::VFCMPHS; break;
3508 case SystemZISD::VFCMPHE: Opcode = SystemZISD::VFCMPHES; break;
3509 default: break;
3510 }
3511 }
3512 if (Opcode) {
3513 C.Opcode = Opcode;
3514 C.Op0 = Src->getOperand(0);
3515 C.Op1 = Src->getOperand(1);
3516 C.CCValid = SystemZ::CCMASK_VCMP;
3518 if (!CmpEq)
3519 C.CCMask ^= C.CCValid;
3520 return;
3521 }
3522 }
3523
3524 // Everything below here is not useful if we have native i128 compares.
3525 if (DAG.getSubtarget<SystemZSubtarget>().hasVectorEnhancements3())
3526 return;
3527
3528 // (In-)Equality comparisons can be implemented via VCEQGS.
3529 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3530 C.CCMask == SystemZ::CCMASK_CMP_NE) {
3531 C.Opcode = SystemZISD::VICMPES;
3532 C.Op0 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, C.Op0);
3533 C.Op1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, C.Op1);
3534 C.CCValid = SystemZ::CCMASK_VCMP;
3535 if (C.CCMask == SystemZ::CCMASK_CMP_EQ)
3536 C.CCMask = SystemZ::CCMASK_VCMP_ALL;
3537 else
3538 C.CCMask = SystemZ::CCMASK_VCMP_ALL ^ C.CCValid;
3539 return;
3540 }
3541
3542 // Normalize other comparisons to GT.
3543 bool Swap = false, Invert = false;
3544 switch (C.CCMask) {
3545 case SystemZ::CCMASK_CMP_GT: break;
3546 case SystemZ::CCMASK_CMP_LT: Swap = true; break;
3547 case SystemZ::CCMASK_CMP_LE: Invert = true; break;
3548 case SystemZ::CCMASK_CMP_GE: Swap = Invert = true; break;
3549 default: llvm_unreachable("Invalid integer condition!");
3550 }
3551 if (Swap)
3552 std::swap(C.Op0, C.Op1);
3553
3554 if (C.ICmpType == SystemZICMP::UnsignedOnly)
3555 C.Opcode = SystemZISD::UCMP128HI;
3556 else
3557 C.Opcode = SystemZISD::SCMP128HI;
3558 C.CCValid = SystemZ::CCMASK_ANY;
3559 C.CCMask = SystemZ::CCMASK_1;
3560
3561 if (Invert)
3562 C.CCMask ^= C.CCValid;
3563}
3564
3565// See whether the comparison argument contains a redundant AND
3566// and remove it if so. This sometimes happens due to the generic
3567// BRCOND expansion.
3569 Comparison &C) {
3570 if (C.Op0.getOpcode() != ISD::AND)
3571 return;
3572 auto *Mask = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
3573 if (!Mask || Mask->getValueSizeInBits(0) > 64)
3574 return;
3575 KnownBits Known = DAG.computeKnownBits(C.Op0.getOperand(0));
3576 if ((~Known.Zero).getZExtValue() & ~Mask->getZExtValue())
3577 return;
3578
3579 C.Op0 = C.Op0.getOperand(0);
3580}
3581
3582// Return a Comparison that tests the condition-code result of intrinsic
3583// node Call against constant integer CC using comparison code Cond.
3584// Opcode is the opcode of the SystemZISD operation for the intrinsic
3585// and CCValid is the set of possible condition-code results.
3586static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
3587 SDValue Call, unsigned CCValid, uint64_t CC,
3589 Comparison C(Call, SDValue(), SDValue());
3590 C.Opcode = Opcode;
3591 C.CCValid = CCValid;
3592 if (Cond == ISD::SETEQ)
3593 // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
3594 C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
3595 else if (Cond == ISD::SETNE)
3596 // ...and the inverse of that.
3597 C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
3598 else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
3599 // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
3600 // always true for CC>3.
3601 C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1;
3602 else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
3603 // ...and the inverse of that.
3604 C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0;
3605 else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
3606 // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
3607 // always true for CC>3.
3608 C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1;
3609 else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
3610 // ...and the inverse of that.
3611 C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0;
3612 else
3613 llvm_unreachable("Unexpected integer comparison type");
3614 C.CCMask &= CCValid;
3615 return C;
3616}
3617
3618// Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
3619static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
3620 ISD::CondCode Cond, const SDLoc &DL,
3621 SDValue Chain = SDValue(),
3622 bool IsSignaling = false) {
3623 if (CmpOp1.getOpcode() == ISD::Constant) {
3624 assert(!Chain);
3625 unsigned Opcode, CCValid;
3626 if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
3627 CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
3628 isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
3629 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid,
3630 CmpOp1->getAsZExtVal(), Cond);
3631 if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
3632 CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 &&
3633 isIntrinsicWithCC(CmpOp0, Opcode, CCValid))
3634 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid,
3635 CmpOp1->getAsZExtVal(), Cond);
3636 }
3637 Comparison C(CmpOp0, CmpOp1, Chain);
3638 C.CCMask = CCMaskForCondCode(Cond);
3639 if (C.Op0.getValueType().isFloatingPoint()) {
3640 C.CCValid = SystemZ::CCMASK_FCMP;
3641 if (!C.Chain)
3642 C.Opcode = SystemZISD::FCMP;
3643 else if (!IsSignaling)
3644 C.Opcode = SystemZISD::STRICT_FCMP;
3645 else
3646 C.Opcode = SystemZISD::STRICT_FCMPS;
3648 } else {
3649 assert(!C.Chain);
3650 C.CCValid = SystemZ::CCMASK_ICMP;
3651 C.Opcode = SystemZISD::ICMP;
3652 // Choose the type of comparison. Equality and inequality tests can
3653 // use either signed or unsigned comparisons. The choice also doesn't
3654 // matter if both sign bits are known to be clear. In those cases we
3655 // want to give the main isel code the freedom to choose whichever
3656 // form fits best.
3657 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3658 C.CCMask == SystemZ::CCMASK_CMP_NE ||
3659 (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
3660 C.ICmpType = SystemZICMP::Any;
3661 else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
3662 C.ICmpType = SystemZICMP::UnsignedOnly;
3663 else
3664 C.ICmpType = SystemZICMP::SignedOnly;
3665 C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
3666 adjustForRedundantAnd(DAG, DL, C);
3667 adjustZeroCmp(DAG, DL, C);
3668 adjustSubwordCmp(DAG, DL, C);
3669 adjustForSubtraction(DAG, DL, C);
3671 adjustICmpTruncate(DAG, DL, C);
3672 }
3673
3674 if (shouldSwapCmpOperands(C)) {
3675 std::swap(C.Op0, C.Op1);
3676 C.CCMask = SystemZ::reverseCCMask(C.CCMask);
3677 }
3678
3680 adjustICmp128(DAG, DL, C);
3682 return C;
3683}
3684
3685// Emit the comparison instruction described by C.
3686static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
3687 if (!C.Op1.getNode()) {
3688 if (C.Opcode == SystemZISD::CMP_STACKGUARD)
3689 return DAG.getNode(SystemZISD::CMP_STACKGUARD, DL, MVT::i32, C.Op0);
3690 SDNode *Node;
3691 switch (C.Op0.getOpcode()) {
3693 Node = emitIntrinsicWithCCAndChain(DAG, C.Op0, C.Opcode);
3694 return SDValue(Node, 0);
3696 Node = emitIntrinsicWithCC(DAG, C.Op0, C.Opcode);
3697 return SDValue(Node, Node->getNumValues() - 1);
3698 default:
3699 llvm_unreachable("Invalid comparison operands");
3700 }
3701 }
3702 if (C.Opcode == SystemZISD::ICMP)
3703 return DAG.getNode(SystemZISD::ICMP, DL, MVT::i32, C.Op0, C.Op1,
3704 DAG.getTargetConstant(C.ICmpType, DL, MVT::i32));
3705 if (C.Opcode == SystemZISD::TM) {
3706 bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
3708 return DAG.getNode(SystemZISD::TM, DL, MVT::i32, C.Op0, C.Op1,
3709 DAG.getTargetConstant(RegisterOnly, DL, MVT::i32));
3710 }
3711 if (C.Opcode == SystemZISD::VICMPES ||
3712 C.Opcode == SystemZISD::VICMPHS ||
3713 C.Opcode == SystemZISD::VICMPHLS ||
3714 C.Opcode == SystemZISD::VFCMPES ||
3715 C.Opcode == SystemZISD::VFCMPHS ||
3716 C.Opcode == SystemZISD::VFCMPHES) {
3717 EVT IntVT = C.Op0.getValueType().changeVectorElementTypeToInteger();
3718 SDVTList VTs = DAG.getVTList(IntVT, MVT::i32);
3719 SDValue Val = DAG.getNode(C.Opcode, DL, VTs, C.Op0, C.Op1);
3720 return SDValue(Val.getNode(), 1);
3721 }
3722 if (C.Chain) {
3723 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
3724 return DAG.getNode(C.Opcode, DL, VTs, C.Chain, C.Op0, C.Op1);
3725 }
3726 return DAG.getNode(C.Opcode, DL, MVT::i32, C.Op0, C.Op1);
3727}
3728
3729// Implement a 32-bit *MUL_LOHI operation by extending both operands to
3730// 64 bits. Extend is the extension type to use. Store the high part
3731// in Hi and the low part in Lo.
3732static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend,
3733 SDValue Op0, SDValue Op1, SDValue &Hi,
3734 SDValue &Lo) {
3735 Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
3736 Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
3737 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
3738 Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
3739 DAG.getConstant(32, DL, MVT::i64));
3740 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
3741 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
3742}
3743
3744// Lower a binary operation that produces two VT results, one in each
3745// half of a GR128 pair. Op0 and Op1 are the VT operands to the operation,
3746// and Opcode performs the GR128 operation. Store the even register result
3747// in Even and the odd register result in Odd.
3748static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
3749 unsigned Opcode, SDValue Op0, SDValue Op1,
3750 SDValue &Even, SDValue &Odd) {
3751 SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped, Op0, Op1);
3752 bool Is32Bit = is32Bit(VT);
3753 Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
3754 Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
3755}
3756
3757// Return an i32 value that is 1 if the CC value produced by CCReg is
3758// in the mask CCMask and 0 otherwise. CC is known to have a value
3759// in CCValid, so other values can be ignored.
3760static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue CCReg,
3761 unsigned CCValid, unsigned CCMask) {
3762 SDValue Ops[] = {DAG.getConstant(1, DL, MVT::i32),
3763 DAG.getConstant(0, DL, MVT::i32),
3764 DAG.getTargetConstant(CCValid, DL, MVT::i32),
3765 DAG.getTargetConstant(CCMask, DL, MVT::i32), CCReg};
3766 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, MVT::i32, Ops);
3767}
3768
3769// Return the SystemISD vector comparison operation for CC, or 0 if it cannot
3770// be done directly. Mode is CmpMode::Int for integer comparisons, CmpMode::FP
3771// for regular floating-point comparisons, CmpMode::StrictFP for strict (quiet)
3772// floating-point comparisons, and CmpMode::SignalingFP for strict signaling
3773// floating-point comparisons.
3776 switch (CC) {
3777 case ISD::SETOEQ:
3778 case ISD::SETEQ:
3779 switch (Mode) {
3780 case CmpMode::Int: return SystemZISD::VICMPE;
3781 case CmpMode::FP: return SystemZISD::VFCMPE;
3782 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPE;
3783 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPES;
3784 }
3785 llvm_unreachable("Bad mode");
3786
3787 case ISD::SETOGE:
3788 case ISD::SETGE:
3789 switch (Mode) {
3790 case CmpMode::Int: return 0;
3791 case CmpMode::FP: return SystemZISD::VFCMPHE;
3792 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPHE;
3793 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHES;
3794 }
3795 llvm_unreachable("Bad mode");
3796
3797 case ISD::SETOGT:
3798 case ISD::SETGT:
3799 switch (Mode) {
3800 case CmpMode::Int: return SystemZISD::VICMPH;
3801 case CmpMode::FP: return SystemZISD::VFCMPH;
3802 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPH;
3803 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHS;
3804 }
3805 llvm_unreachable("Bad mode");
3806
3807 case ISD::SETUGT:
3808 switch (Mode) {
3809 case CmpMode::Int: return SystemZISD::VICMPHL;
3810 case CmpMode::FP: return 0;
3811 case CmpMode::StrictFP: return 0;
3812 case CmpMode::SignalingFP: return 0;
3813 }
3814 llvm_unreachable("Bad mode");
3815
3816 default:
3817 return 0;
3818 }
3819}
3820
3821// Return the SystemZISD vector comparison operation for CC or its inverse,
3822// or 0 if neither can be done directly. Indicate in Invert whether the
3823// result is for the inverse of CC. Mode is as above.
3825 bool &Invert) {
3826 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
3827 Invert = false;
3828 return Opcode;
3829 }
3830
3831 CC = ISD::getSetCCInverse(CC, Mode == CmpMode::Int ? MVT::i32 : MVT::f32);
3832 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
3833 Invert = true;
3834 return Opcode;
3835 }
3836
3837 return 0;
3838}
3839
3840// Return a v2f64 that contains the extended form of elements Start and Start+1
3841// of v4f32 value Op. If Chain is nonnull, return the strict form.
3842static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL,
3843 SDValue Op, SDValue Chain) {
3844 int Mask[] = { Start, -1, Start + 1, -1 };
3845 Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
3846 if (Chain) {
3847 SDVTList VTs = DAG.getVTList(MVT::v2f64, MVT::Other);
3848 return DAG.getNode(SystemZISD::STRICT_VEXTEND, DL, VTs, Chain, Op);
3849 }
3850 return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
3851}
3852
3853// Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
3854// producing a result of type VT. If Chain is nonnull, return the strict form.
3855SDValue SystemZTargetLowering::getVectorCmp(SelectionDAG &DAG, unsigned Opcode,
3856 const SDLoc &DL, EVT VT,
3857 SDValue CmpOp0,
3858 SDValue CmpOp1,
3859 SDValue Chain) const {
3860 // There is no hardware support for v4f32 (unless we have the vector
3861 // enhancements facility 1), so extend the vector into two v2f64s
3862 // and compare those.
3863 if (CmpOp0.getValueType() == MVT::v4f32 &&
3864 !Subtarget.hasVectorEnhancements1()) {
3865 SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0, Chain);
3866 SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0, Chain);
3867 SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1, Chain);
3868 SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1, Chain);
3869 if (Chain) {
3870 SDVTList VTs = DAG.getVTList(MVT::v2i64, MVT::Other);
3871 SDValue HRes = DAG.getNode(Opcode, DL, VTs, Chain, H0, H1);
3872 SDValue LRes = DAG.getNode(Opcode, DL, VTs, Chain, L0, L1);
3873 SDValue Res = DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
3874 SDValue Chains[6] = { H0.getValue(1), L0.getValue(1),
3875 H1.getValue(1), L1.getValue(1),
3876 HRes.getValue(1), LRes.getValue(1) };
3877 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
3878 SDValue Ops[2] = { Res, NewChain };
3879 return DAG.getMergeValues(Ops, DL);
3880 }
3881 SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
3882 SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
3883 return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
3884 }
3885 if (Chain) {
3886 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3887 return DAG.getNode(Opcode, DL, VTs, Chain, CmpOp0, CmpOp1);
3888 }
3889 return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
3890}
3891
3892// Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
3893// an integer mask of type VT. If Chain is nonnull, we have a strict
3894// floating-point comparison. If in addition IsSignaling is true, we have
3895// a strict signaling floating-point comparison.
3896SDValue SystemZTargetLowering::lowerVectorSETCC(SelectionDAG &DAG,
3897 const SDLoc &DL, EVT VT,
3898 ISD::CondCode CC,
3899 SDValue CmpOp0,
3900 SDValue CmpOp1,
3901 SDValue Chain,
3902 bool IsSignaling) const {
3903 bool IsFP = CmpOp0.getValueType().isFloatingPoint();
3904 assert (!Chain || IsFP);
3905 assert (!IsSignaling || Chain);
3906 CmpMode Mode = IsSignaling ? CmpMode::SignalingFP :
3907 Chain ? CmpMode::StrictFP : IsFP ? CmpMode::FP : CmpMode::Int;
3908 bool Invert = false;
3909 SDValue Cmp;
3910 switch (CC) {
3911 // Handle tests for order using (or (ogt y x) (oge x y)).
3912 case ISD::SETUO:
3913 Invert = true;
3914 [[fallthrough]];
3915 case ISD::SETO: {
3916 assert(IsFP && "Unexpected integer comparison");
3917 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
3918 DL, VT, CmpOp1, CmpOp0, Chain);
3919 SDValue GE = getVectorCmp(DAG, getVectorComparison(ISD::SETOGE, Mode),
3920 DL, VT, CmpOp0, CmpOp1, Chain);
3921 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
3922 if (Chain)
3923 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
3924 LT.getValue(1), GE.getValue(1));
3925 break;
3926 }
3927
3928 // Handle <> tests using (or (ogt y x) (ogt x y)).
3929 case ISD::SETUEQ:
3930 Invert = true;
3931 [[fallthrough]];
3932 case ISD::SETONE: {
3933 assert(IsFP && "Unexpected integer comparison");
3934 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
3935 DL, VT, CmpOp1, CmpOp0, Chain);
3936 SDValue GT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
3937 DL, VT, CmpOp0, CmpOp1, Chain);
3938 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
3939 if (Chain)
3940 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
3941 LT.getValue(1), GT.getValue(1));
3942 break;
3943 }
3944
3945 // Otherwise a single comparison is enough. It doesn't really
3946 // matter whether we try the inversion or the swap first, since
3947 // there are no cases where both work.
3948 default:
3949 // Optimize sign-bit comparisons to signed compares.
3950 if (Mode == CmpMode::Int && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
3952 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3953 APInt Mask;
3954 if (CmpOp0.getOpcode() == ISD::AND
3955 && ISD::isConstantSplatVector(CmpOp0.getOperand(1).getNode(), Mask)
3956 && Mask == APInt::getSignMask(EltSize)) {
3957 CC = CC == ISD::SETEQ ? ISD::SETGE : ISD::SETLT;
3958 CmpOp0 = CmpOp0.getOperand(0);
3959 }
3960 }
3961 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
3962 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1, Chain);
3963 else {
3965 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
3966 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0, Chain);
3967 else
3968 llvm_unreachable("Unhandled comparison");
3969 }
3970 if (Chain)
3971 Chain = Cmp.getValue(1);
3972 break;
3973 }
3974 if (Invert) {
3975 SDValue Mask =
3976 DAG.getSplatBuildVector(VT, DL, DAG.getAllOnesConstant(DL, MVT::i64));
3977 Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
3978 }
3979 if (Chain && Chain.getNode() != Cmp.getNode()) {
3980 SDValue Ops[2] = { Cmp, Chain };
3981 Cmp = DAG.getMergeValues(Ops, DL);
3982 }
3983 return Cmp;
3984}
3985
3986SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
3987 SelectionDAG &DAG) const {
3988 SDValue CmpOp0 = Op.getOperand(0);
3989 SDValue CmpOp1 = Op.getOperand(1);
3990 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3991 SDLoc DL(Op);
3992 EVT VT = Op.getValueType();
3993 if (VT.isVector())
3994 return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
3995
3996 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
3997 SDValue CCReg = emitCmp(DAG, DL, C);
3998 return emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
3999}
4000
4001SDValue SystemZTargetLowering::lowerSTRICT_FSETCC(SDValue Op,
4002 SelectionDAG &DAG,
4003 bool IsSignaling) const {
4004 SDValue Chain = Op.getOperand(0);
4005 SDValue CmpOp0 = Op.getOperand(1);
4006 SDValue CmpOp1 = Op.getOperand(2);
4007 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
4008 SDLoc DL(Op);
4009 EVT VT = Op.getNode()->getValueType(0);
4010 if (VT.isVector()) {
4011 SDValue Res = lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1,
4012 Chain, IsSignaling);
4013 return Res.getValue(Op.getResNo());
4014 }
4015
4016 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL, Chain, IsSignaling));
4017 SDValue CCReg = emitCmp(DAG, DL, C);
4018 CCReg->setFlags(Op->getFlags());
4019 SDValue Result = emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
4020 SDValue Ops[2] = { Result, CCReg.getValue(1) };
4021 return DAG.getMergeValues(Ops, DL);
4022}
4023
4024SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4025 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4026 SDValue CmpOp0 = Op.getOperand(2);
4027 SDValue CmpOp1 = Op.getOperand(3);
4028 SDValue Dest = Op.getOperand(4);
4029 SDLoc DL(Op);
4030
4031 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
4032 SDValue CCReg = emitCmp(DAG, DL, C);
4033 return DAG.getNode(
4034 SystemZISD::BR_CCMASK, DL, Op.getValueType(), Op.getOperand(0),
4035 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
4036 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), Dest, CCReg);
4037}
4038
4039// Return true if Pos is CmpOp and Neg is the negative of CmpOp,
4040// allowing Pos and Neg to be wider than CmpOp.
4041static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
4042 return (Neg.getOpcode() == ISD::SUB &&
4043 Neg.getOperand(0).getOpcode() == ISD::Constant &&
4044 Neg.getConstantOperandVal(0) == 0 && Neg.getOperand(1) == Pos &&
4045 (Pos == CmpOp || (Pos.getOpcode() == ISD::SIGN_EXTEND &&
4046 Pos.getOperand(0) == CmpOp)));
4047}
4048
4049// Return the absolute or negative absolute of Op; IsNegative decides which.
4051 bool IsNegative) {
4052 Op = DAG.getNode(ISD::ABS, DL, Op.getValueType(), Op);
4053 if (IsNegative)
4054 Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
4055 DAG.getConstant(0, DL, Op.getValueType()), Op);
4056 return Op;
4057}
4058
4060 Comparison C, SDValue TrueOp, SDValue FalseOp) {
4061 EVT VT = MVT::i128;
4062 unsigned Op;
4063
4064 if (C.CCMask == SystemZ::CCMASK_CMP_NE ||
4065 C.CCMask == SystemZ::CCMASK_CMP_GE ||
4066 C.CCMask == SystemZ::CCMASK_CMP_LE) {
4067 std::swap(TrueOp, FalseOp);
4068 C.CCMask ^= C.CCValid;
4069 }
4070 if (C.CCMask == SystemZ::CCMASK_CMP_LT) {
4071 std::swap(C.Op0, C.Op1);
4072 C.CCMask = SystemZ::CCMASK_CMP_GT;
4073 }
4074 switch (C.CCMask) {
4076 Op = SystemZISD::VICMPE;
4077 break;
4079 if (C.ICmpType == SystemZICMP::UnsignedOnly)
4080 Op = SystemZISD::VICMPHL;
4081 else
4082 Op = SystemZISD::VICMPH;
4083 break;
4084 default:
4085 llvm_unreachable("Unhandled comparison");
4086 break;
4087 }
4088
4089 SDValue Mask = DAG.getNode(Op, DL, VT, C.Op0, C.Op1);
4090 TrueOp = DAG.getNode(ISD::AND, DL, VT, TrueOp, Mask);
4091 FalseOp = DAG.getNode(ISD::AND, DL, VT, FalseOp, DAG.getNOT(DL, Mask, VT));
4092 return DAG.getNode(ISD::OR, DL, VT, TrueOp, FalseOp);
4093}
4094
4095SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
4096 SelectionDAG &DAG) const {
4097 SDValue CmpOp0 = Op.getOperand(0);
4098 SDValue CmpOp1 = Op.getOperand(1);
4099 SDValue TrueOp = Op.getOperand(2);
4100 SDValue FalseOp = Op.getOperand(3);
4101 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4102 SDLoc DL(Op);
4103
4104 // SELECT_CC involving f16 will not have the cmp-ops promoted by the
4105 // legalizer, as it will be handled according to the type of the resulting
4106 // value. Extend them here if needed.
4107 if (CmpOp0.getSimpleValueType() == MVT::f16) {
4108 CmpOp0 = DAG.getFPExtendOrRound(CmpOp0, SDLoc(CmpOp0), MVT::f32);
4109 CmpOp1 = DAG.getFPExtendOrRound(CmpOp1, SDLoc(CmpOp1), MVT::f32);
4110 }
4111
4112 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
4113
4114 // Check for absolute and negative-absolute selections, including those
4115 // where the comparison value is sign-extended (for LPGFR and LNGFR).
4116 // This check supplements the one in DAGCombiner.
4117 if (C.Opcode == SystemZISD::ICMP && C.CCMask != SystemZ::CCMASK_CMP_EQ &&
4118 C.CCMask != SystemZ::CCMASK_CMP_NE &&
4119 C.Op1.getOpcode() == ISD::Constant &&
4120 cast<ConstantSDNode>(C.Op1)->getValueSizeInBits(0) <= 64 &&
4121 C.Op1->getAsZExtVal() == 0) {
4122 if (isAbsolute(C.Op0, TrueOp, FalseOp))
4123 return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
4124 if (isAbsolute(C.Op0, FalseOp, TrueOp))
4125 return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
4126 }
4127
4128 if (Subtarget.hasVectorEnhancements3() &&
4129 C.Opcode == SystemZISD::ICMP &&
4130 C.Op0.getValueType() == MVT::i128 &&
4131 TrueOp.getValueType() == MVT::i128) {
4132 return getI128Select(DAG, DL, C, TrueOp, FalseOp);
4133 }
4134
4135 SDValue CCReg = emitCmp(DAG, DL, C);
4136 SDValue Ops[] = {TrueOp, FalseOp,
4137 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
4138 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), CCReg};
4139
4140 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, Op.getValueType(), Ops);
4141}
4142
4143SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
4144 SelectionDAG &DAG) const {
4145 SDLoc DL(Node);
4146 const GlobalValue *GV = Node->getGlobal();
4147 int64_t Offset = Node->getOffset();
4148 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4150
4151 SDValue Result;
4152 if (Subtarget.isPC32DBLSymbol(GV, CM)) {
4153 if (isInt<32>(Offset)) {
4154 // Assign anchors at 1<<12 byte boundaries.
4155 uint64_t Anchor = Offset & ~uint64_t(0xfff);
4156 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
4157 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4158
4159 // The offset can be folded into the address if it is aligned to a
4160 // halfword.
4161 Offset -= Anchor;
4162 if (Offset != 0 && (Offset & 1) == 0) {
4163 SDValue Full =
4164 DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
4165 Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
4166 Offset = 0;
4167 }
4168 } else {
4169 // Conservatively load a constant offset greater than 32 bits into a
4170 // register below.
4171 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT);
4172 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4173 }
4174 } else if (Subtarget.isTargetELF()) {
4175 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
4176 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4177 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4179 } else if (Subtarget.isTargetzOS()) {
4180 Result = getADAEntry(DAG, GV, DL, PtrVT);
4181 } else
4182 llvm_unreachable("Unexpected Subtarget");
4183
4184 // If there was a non-zero offset that we didn't fold, create an explicit
4185 // addition for it.
4186 if (Offset != 0)
4187 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
4188 DAG.getSignedConstant(Offset, DL, PtrVT));
4189
4190 return Result;
4191}
4192
4193SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
4194 SelectionDAG &DAG,
4195 unsigned Opcode,
4196 SDValue GOTOffset) const {
4197 SDLoc DL(Node);
4198 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4199 SDValue Chain = DAG.getEntryNode();
4200 SDValue Glue;
4201
4204 report_fatal_error("In GHC calling convention TLS is not supported");
4205
4206 // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
4207 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
4208 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
4209 Glue = Chain.getValue(1);
4210 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
4211 Glue = Chain.getValue(1);
4212
4213 // The first call operand is the chain and the second is the TLS symbol.
4215 Ops.push_back(Chain);
4216 Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
4217 Node->getValueType(0),
4218 0, 0));
4219
4220 // Add argument registers to the end of the list so that they are
4221 // known live into the call.
4222 Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
4223 Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
4224
4225 // Add a register mask operand representing the call-preserved registers.
4226 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4227 const uint32_t *Mask =
4228 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
4229 assert(Mask && "Missing call preserved mask for calling convention");
4230 Ops.push_back(DAG.getRegisterMask(Mask));
4231
4232 // Glue the call to the argument copies.
4233 Ops.push_back(Glue);
4234
4235 // Emit the call.
4236 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4237 Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
4238 Glue = Chain.getValue(1);
4239
4240 // Copy the return value from %r2.
4241 return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
4242}
4243
4244SDValue SystemZTargetLowering::lowerThreadPointer(const SDLoc &DL,
4245 SelectionDAG &DAG) const {
4246 SDValue Chain = DAG.getEntryNode();
4247 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4248
4249 // The high part of the thread pointer is in access register 0.
4250 SDValue TPHi = DAG.getCopyFromReg(Chain, DL, SystemZ::A0, MVT::i32);
4251 TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
4252
4253 // The low part of the thread pointer is in access register 1.
4254 SDValue TPLo = DAG.getCopyFromReg(Chain, DL, SystemZ::A1, MVT::i32);
4255 TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
4256
4257 // Merge them into a single 64-bit address.
4258 SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
4259 DAG.getConstant(32, DL, PtrVT));
4260 return DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
4261}
4262
4263SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
4264 SelectionDAG &DAG) const {
4265 if (DAG.getTarget().useEmulatedTLS())
4266 return LowerToTLSEmulatedModel(Node, DAG);
4267 SDLoc DL(Node);
4268 const GlobalValue *GV = Node->getGlobal();
4269 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4270 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
4271
4274 report_fatal_error("In GHC calling convention TLS is not supported");
4275
4276 SDValue TP = lowerThreadPointer(DL, DAG);
4277
4278 // Get the offset of GA from the thread pointer, based on the TLS model.
4279 SDValue Offset;
4280 switch (model) {
4282 // Load the GOT offset of the tls_index (module ID / per-symbol offset).
4283 SystemZConstantPoolValue *CPV =
4285
4286 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4287 Offset = DAG.getLoad(
4288 PtrVT, DL, DAG.getEntryNode(), Offset,
4290
4291 // Call __tls_get_offset to retrieve the offset.
4292 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
4293 break;
4294 }
4295
4297 // Load the GOT offset of the module ID.
4298 SystemZConstantPoolValue *CPV =
4300
4301 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4302 Offset = DAG.getLoad(
4303 PtrVT, DL, DAG.getEntryNode(), Offset,
4305
4306 // Call __tls_get_offset to retrieve the module base offset.
4307 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
4308
4309 // Note: The SystemZLDCleanupPass will remove redundant computations
4310 // of the module base offset. Count total number of local-dynamic
4311 // accesses to trigger execution of that pass.
4312 SystemZMachineFunctionInfo* MFI =
4313 DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>();
4315
4316 // Add the per-symbol offset.
4318
4319 SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4320 DTPOffset = DAG.getLoad(
4321 PtrVT, DL, DAG.getEntryNode(), DTPOffset,
4323
4324 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
4325 break;
4326 }
4327
4328 case TLSModel::InitialExec: {
4329 // Load the offset from the GOT.
4330 Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
4332 Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
4333 Offset =
4334 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset,
4336 break;
4337 }
4338
4339 case TLSModel::LocalExec: {
4340 // Force the offset into the constant pool and load it from there.
4341 SystemZConstantPoolValue *CPV =
4343
4344 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4345 Offset = DAG.getLoad(
4346 PtrVT, DL, DAG.getEntryNode(), Offset,
4348 break;
4349 }
4350 }
4351
4352 // Add the base and offset together.
4353 return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
4354}
4355
4356SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
4357 SelectionDAG &DAG) const {
4358 SDLoc DL(Node);
4359 const BlockAddress *BA = Node->getBlockAddress();
4360 int64_t Offset = Node->getOffset();
4361 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4362
4363 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
4364 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4365 return Result;
4366}
4367
4368SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
4369 SelectionDAG &DAG) const {
4370 SDLoc DL(JT);
4371 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4372 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
4373
4374 // Use LARL to load the address of the table.
4375 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4376}
4377
4378SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
4379 SelectionDAG &DAG) const {
4380 SDLoc DL(CP);
4381 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4382
4383 SDValue Result;
4385 Result =
4386 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign());
4387 else
4388 Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign(),
4389 CP->getOffset());
4390
4391 // Use LARL to load the address of the constant pool entry.
4392 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4393}
4394
4395SDValue SystemZTargetLowering::lowerFRAMEADDR(SDValue Op,
4396 SelectionDAG &DAG) const {
4397 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
4399 MachineFrameInfo &MFI = MF.getFrameInfo();
4400 MFI.setFrameAddressIsTaken(true);
4401
4402 SDLoc DL(Op);
4403 unsigned Depth = Op.getConstantOperandVal(0);
4404 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4405
4406 // By definition, the frame address is the address of the back chain. (In
4407 // the case of packed stack without backchain, return the address where the
4408 // backchain would have been stored. This will either be an unused space or
4409 // contain a saved register).
4410 int BackChainIdx = TFL->getOrCreateFramePointerSaveIndex(MF);
4411 SDValue BackChain = DAG.getFrameIndex(BackChainIdx, PtrVT);
4412
4413 if (Depth > 0) {
4414 // FIXME The frontend should detect this case.
4415 if (!MF.getSubtarget<SystemZSubtarget>().hasBackChain())
4416 report_fatal_error("Unsupported stack frame traversal count");
4417
4418 SDValue Offset = DAG.getConstant(TFL->getBackchainOffset(MF), DL, PtrVT);
4419 while (Depth--) {
4420 BackChain = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), BackChain,
4421 MachinePointerInfo());
4422 BackChain = DAG.getNode(ISD::ADD, DL, PtrVT, BackChain, Offset);
4423 }
4424 }
4425
4426 return BackChain;
4427}
4428
4429SDValue SystemZTargetLowering::lowerRETURNADDR(SDValue Op,
4430 SelectionDAG &DAG) const {
4432 MachineFrameInfo &MFI = MF.getFrameInfo();
4433 MFI.setReturnAddressIsTaken(true);
4434
4435 SDLoc DL(Op);
4436 unsigned Depth = Op.getConstantOperandVal(0);
4437 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4438
4439 if (Depth > 0) {
4440 // FIXME The frontend should detect this case.
4441 if (!MF.getSubtarget<SystemZSubtarget>().hasBackChain())
4442 report_fatal_error("Unsupported stack frame traversal count");
4443
4444 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
4445 const auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
4446 int Offset = TFL->getReturnAddressOffset(MF);
4447 SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, FrameAddr,
4448 DAG.getSignedConstant(Offset, DL, PtrVT));
4449 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr,
4450 MachinePointerInfo());
4451 }
4452
4453 // Return R14D (Elf) / R7D (XPLINK), which has the return address. Mark it an
4454 // implicit live-in.
4455 SystemZCallingConventionRegisters *CCR = Subtarget.getSpecialRegisters();
4457 &SystemZ::GR64BitRegClass);
4458 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, LinkReg, PtrVT);
4459}
4460
4461SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
4462 SelectionDAG &DAG) const {
4463 SDLoc DL(Op);
4464 SDValue In = Op.getOperand(0);
4465 EVT InVT = In.getValueType();
4466 EVT ResVT = Op.getValueType();
4467
4468 // Convert loads directly. This is normally done by DAGCombiner,
4469 // but we need this case for bitcasts that are created during lowering
4470 // and which are then lowered themselves.
4471 if (auto *LoadN = dyn_cast<LoadSDNode>(In))
4472 if (ISD::isNormalLoad(LoadN)) {
4473 SDValue NewLoad = DAG.getLoad(ResVT, DL, LoadN->getChain(),
4474 LoadN->getBasePtr(), LoadN->getMemOperand());
4475 // Update the chain uses.
4476 DAG.ReplaceAllUsesOfValueWith(SDValue(LoadN, 1), NewLoad.getValue(1));
4477 return NewLoad;
4478 }
4479
4480 if (InVT == MVT::i32 && ResVT == MVT::f32) {
4481 SDValue In64;
4482 if (Subtarget.hasHighWord()) {
4483 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
4484 MVT::i64);
4485 In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
4486 MVT::i64, SDValue(U64, 0), In);
4487 } else {
4488 In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
4489 In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
4490 DAG.getConstant(32, DL, MVT::i64));
4491 }
4492 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
4493 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32,
4494 DL, MVT::f32, Out64);
4495 }
4496 if (InVT == MVT::f32 && ResVT == MVT::i32) {
4497 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
4498 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
4499 MVT::f64, SDValue(U64, 0), In);
4500 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
4501 if (Subtarget.hasHighWord())
4502 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
4503 MVT::i32, Out64);
4504 SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
4505 DAG.getConstant(32, DL, MVT::i64));
4506 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
4507 }
4508 llvm_unreachable("Unexpected bitcast combination");
4509}
4510
4511SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
4512 SelectionDAG &DAG) const {
4513
4514 if (Subtarget.isTargetXPLINK64())
4515 return lowerVASTART_XPLINK(Op, DAG);
4516 else
4517 return lowerVASTART_ELF(Op, DAG);
4518}
4519
4520SDValue SystemZTargetLowering::lowerVASTART_XPLINK(SDValue Op,
4521 SelectionDAG &DAG) const {
4523 SystemZMachineFunctionInfo *FuncInfo =
4524 MF.getInfo<SystemZMachineFunctionInfo>();
4525
4526 SDLoc DL(Op);
4527
4528 // vastart just stores the address of the VarArgsFrameIndex slot into the
4529 // memory location argument.
4530 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4531 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4532 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4533 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4534 MachinePointerInfo(SV));
4535}
4536
4537SDValue SystemZTargetLowering::lowerVASTART_ELF(SDValue Op,
4538 SelectionDAG &DAG) const {
4540 SystemZMachineFunctionInfo *FuncInfo =
4541 MF.getInfo<SystemZMachineFunctionInfo>();
4542 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4543
4544 SDValue Chain = Op.getOperand(0);
4545 SDValue Addr = Op.getOperand(1);
4546 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4547 SDLoc DL(Op);
4548
4549 // The initial values of each field.
4550 const unsigned NumFields = 4;
4551 SDValue Fields[NumFields] = {
4552 DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
4553 DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
4554 DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
4555 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
4556 };
4557
4558 // Store each field into its respective slot.
4559 SDValue MemOps[NumFields];
4560 unsigned Offset = 0;
4561 for (unsigned I = 0; I < NumFields; ++I) {
4562 SDValue FieldAddr = Addr;
4563 if (Offset != 0)
4564 FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
4566 MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
4567 MachinePointerInfo(SV, Offset));
4568 Offset += 8;
4569 }
4570 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4571}
4572
4573SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
4574 SelectionDAG &DAG) const {
4575 SDValue Chain = Op.getOperand(0);
4576 SDValue DstPtr = Op.getOperand(1);
4577 SDValue SrcPtr = Op.getOperand(2);
4578 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4579 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4580 SDLoc DL(Op);
4581
4582 uint32_t Sz =
4583 Subtarget.isTargetXPLINK64() ? DAG.getDataLayout().getPointerSize(0) : 32;
4584 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(Sz, DL),
4585 Align(8), Align(8), /*isVolatile*/ false,
4586 /*AlwaysInline*/ false,
4587 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(DstSV),
4588 MachinePointerInfo(SrcSV));
4589}
4590
4591SDValue
4592SystemZTargetLowering::lowerDYNAMIC_STACKALLOC(SDValue Op,
4593 SelectionDAG &DAG) const {
4594 if (Subtarget.isTargetXPLINK64())
4595 return lowerDYNAMIC_STACKALLOC_XPLINK(Op, DAG);
4596 else
4597 return lowerDYNAMIC_STACKALLOC_ELF(Op, DAG);
4598}
4599
4600SDValue
4601SystemZTargetLowering::lowerDYNAMIC_STACKALLOC_XPLINK(SDValue Op,
4602 SelectionDAG &DAG) const {
4603 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
4605 bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack");
4606 SDValue Chain = Op.getOperand(0);
4607 SDValue Size = Op.getOperand(1);
4608 SDValue Align = Op.getOperand(2);
4609 SDLoc DL(Op);
4610
4611 // If user has set the no alignment function attribute, ignore
4612 // alloca alignments.
4613 uint64_t AlignVal = (RealignOpt ? Align->getAsZExtVal() : 0);
4614
4615 uint64_t StackAlign = TFI->getStackAlignment();
4616 uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
4617 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
4618
4619 SDValue NeededSpace = Size;
4620
4621 // Add extra space for alignment if needed.
4622 EVT PtrVT = getPointerTy(MF.getDataLayout());
4623 if (ExtraAlignSpace)
4624 NeededSpace = DAG.getNode(ISD::ADD, DL, PtrVT, NeededSpace,
4625 DAG.getConstant(ExtraAlignSpace, DL, PtrVT));
4626
4627 bool IsSigned = false;
4628 bool DoesNotReturn = false;
4629 bool IsReturnValueUsed = false;
4630 EVT VT = Op.getValueType();
4631 SDValue AllocaCall =
4632 makeExternalCall(Chain, DAG, "@@ALCAXP", VT, ArrayRef(NeededSpace),
4633 CallingConv::C, IsSigned, DL, DoesNotReturn,
4634 IsReturnValueUsed)
4635 .first;
4636
4637 // Perform a CopyFromReg from %GPR4 (stack pointer register). Chain and Glue
4638 // to end of call in order to ensure it isn't broken up from the call
4639 // sequence.
4640 auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
4641 Register SPReg = Regs.getStackPointerRegister();
4642 Chain = AllocaCall.getValue(1);
4643 SDValue Glue = AllocaCall.getValue(2);
4644 SDValue NewSPRegNode = DAG.getCopyFromReg(Chain, DL, SPReg, PtrVT, Glue);
4645 Chain = NewSPRegNode.getValue(1);
4646
4647 MVT PtrMVT = getPointerMemTy(MF.getDataLayout());
4648 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, PtrMVT);
4649 SDValue Result = DAG.getNode(ISD::ADD, DL, PtrMVT, NewSPRegNode, ArgAdjust);
4650
4651 // Dynamically realign if needed.
4652 if (ExtraAlignSpace) {
4653 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
4654 DAG.getConstant(ExtraAlignSpace, DL, PtrVT));
4655 Result = DAG.getNode(ISD::AND, DL, PtrVT, Result,
4656 DAG.getConstant(~(RequiredAlign - 1), DL, PtrVT));
4657 }
4658
4659 SDValue Ops[2] = {Result, Chain};
4660 return DAG.getMergeValues(Ops, DL);
4661}
4662
4663SDValue
4664SystemZTargetLowering::lowerDYNAMIC_STACKALLOC_ELF(SDValue Op,
4665 SelectionDAG &DAG) const {
4666 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
4668 bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack");
4669 bool StoreBackchain = MF.getSubtarget<SystemZSubtarget>().hasBackChain();
4670
4671 SDValue Chain = Op.getOperand(0);
4672 SDValue Size = Op.getOperand(1);
4673 SDValue Align = Op.getOperand(2);
4674 SDLoc DL(Op);
4675
4676 // If user has set the no alignment function attribute, ignore
4677 // alloca alignments.
4678 uint64_t AlignVal = (RealignOpt ? Align->getAsZExtVal() : 0);
4679
4680 uint64_t StackAlign = TFI->getStackAlignment();
4681 uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
4682 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
4683
4685 SDValue NeededSpace = Size;
4686
4687 // Get a reference to the stack pointer.
4688 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
4689
4690 // If we need a backchain, save it now.
4691 SDValue Backchain;
4692 if (StoreBackchain)
4693 Backchain = DAG.getLoad(MVT::i64, DL, Chain, getBackchainAddress(OldSP, DAG),
4694 MachinePointerInfo());
4695
4696 // Add extra space for alignment if needed.
4697 if (ExtraAlignSpace)
4698 NeededSpace = DAG.getNode(ISD::ADD, DL, MVT::i64, NeededSpace,
4699 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
4700
4701 // Get the new stack pointer value.
4702 SDValue NewSP;
4703 if (hasInlineStackProbe(MF)) {
4704 NewSP = DAG.getNode(SystemZISD::PROBED_ALLOCA, DL,
4705 DAG.getVTList(MVT::i64, MVT::Other), Chain, OldSP, NeededSpace);
4706 Chain = NewSP.getValue(1);
4707 }
4708 else {
4709 NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, NeededSpace);
4710 // Copy the new stack pointer back.
4711 Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
4712 }
4713
4714 // The allocated data lives above the 160 bytes allocated for the standard
4715 // frame, plus any outgoing stack arguments. We don't know how much that
4716 // amounts to yet, so emit a special ADJDYNALLOC placeholder.
4717 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
4718 SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
4719
4720 // Dynamically realign if needed.
4721 if (RequiredAlign > StackAlign) {
4722 Result =
4723 DAG.getNode(ISD::ADD, DL, MVT::i64, Result,
4724 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
4725 Result =
4726 DAG.getNode(ISD::AND, DL, MVT::i64, Result,
4727 DAG.getConstant(~(RequiredAlign - 1), DL, MVT::i64));
4728 }
4729
4730 if (StoreBackchain)
4731 Chain = DAG.getStore(Chain, DL, Backchain, getBackchainAddress(NewSP, DAG),
4732 MachinePointerInfo());
4733
4734 SDValue Ops[2] = { Result, Chain };
4735 return DAG.getMergeValues(Ops, DL);
4736}
4737
4738SDValue SystemZTargetLowering::lowerGET_DYNAMIC_AREA_OFFSET(
4739 SDValue Op, SelectionDAG &DAG) const {
4740 SDLoc DL(Op);
4741
4742 return DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
4743}
4744
4745SDValue SystemZTargetLowering::lowerMULH(SDValue Op,
4746 SelectionDAG &DAG,
4747 unsigned Opcode) const {
4748 EVT VT = Op.getValueType();
4749 SDLoc DL(Op);
4750 SDValue Even, Odd;
4751
4752 // This custom expander is only used on z17 and later for 64-bit types.
4753 assert(!is32Bit(VT));
4754 assert(Subtarget.hasMiscellaneousExtensions2());
4755
4756 // SystemZISD::xMUL_LOHI returns the low result in the odd register and
4757 // the high result in the even register. Return the latter.
4758 lowerGR128Binary(DAG, DL, VT, Opcode,
4759 Op.getOperand(0), Op.getOperand(1), Even, Odd);
4760 return Even;
4761}
4762
4763SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
4764 SelectionDAG &DAG) const {
4765 EVT VT = Op.getValueType();
4766 SDLoc DL(Op);
4767 SDValue Ops[2];
4768 if (is32Bit(VT))
4769 // Just do a normal 64-bit multiplication and extract the results.
4770 // We define this so that it can be used for constant division.
4771 lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
4772 Op.getOperand(1), Ops[1], Ops[0]);
4773 else if (Subtarget.hasMiscellaneousExtensions2())
4774 // SystemZISD::SMUL_LOHI returns the low result in the odd register and
4775 // the high result in the even register. ISD::SMUL_LOHI is defined to
4776 // return the low half first, so the results are in reverse order.
4777 lowerGR128Binary(DAG, DL, VT, SystemZISD::SMUL_LOHI,
4778 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
4779 else {
4780 // Do a full 128-bit multiplication based on SystemZISD::UMUL_LOHI:
4781 //
4782 // (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
4783 //
4784 // but using the fact that the upper halves are either all zeros
4785 // or all ones:
4786 //
4787 // (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
4788 //
4789 // and grouping the right terms together since they are quicker than the
4790 // multiplication:
4791 //
4792 // (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
4793 SDValue C63 = DAG.getConstant(63, DL, MVT::i64);
4794 SDValue LL = Op.getOperand(0);
4795 SDValue RL = Op.getOperand(1);
4796 SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
4797 SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
4798 // SystemZISD::UMUL_LOHI returns the low result in the odd register and
4799 // the high result in the even register. ISD::SMUL_LOHI is defined to
4800 // return the low half first, so the results are in reverse order.
4801 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
4802 LL, RL, Ops[1], Ops[0]);
4803 SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
4804 SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
4805 SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
4806 Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
4807 }
4808 return DAG.getMergeValues(Ops, DL);
4809}
4810
4811SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
4812 SelectionDAG &DAG) const {
4813 EVT VT = Op.getValueType();
4814 SDLoc DL(Op);
4815 SDValue Ops[2];
4816 if (is32Bit(VT))
4817 // Just do a normal 64-bit multiplication and extract the results.
4818 // We define this so that it can be used for constant division.
4819 lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
4820 Op.getOperand(1), Ops[1], Ops[0]);
4821 else
4822 // SystemZISD::UMUL_LOHI returns the low result in the odd register and
4823 // the high result in the even register. ISD::UMUL_LOHI is defined to
4824 // return the low half first, so the results are in reverse order.
4825 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
4826 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
4827 return DAG.getMergeValues(Ops, DL);
4828}
4829
4830SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
4831 SelectionDAG &DAG) const {
4832 SDValue Op0 = Op.getOperand(0);
4833 SDValue Op1 = Op.getOperand(1);
4834 EVT VT = Op.getValueType();
4835 SDLoc DL(Op);
4836
4837 // We use DSGF for 32-bit division. This means the first operand must
4838 // always be 64-bit, and the second operand should be 32-bit whenever
4839 // that is possible, to improve performance.
4840 if (is32Bit(VT))
4841 Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
4842 else if (DAG.ComputeNumSignBits(Op1) > 32)
4843 Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
4844
4845 // DSG(F) returns the remainder in the even register and the
4846 // quotient in the odd register.
4847 SDValue Ops[2];
4848 lowerGR128Binary(DAG, DL, VT, SystemZISD::SDIVREM, Op0, Op1, Ops[1], Ops[0]);
4849 return DAG.getMergeValues(Ops, DL);
4850}
4851
4852SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
4853 SelectionDAG &DAG) const {
4854 EVT VT = Op.getValueType();
4855 SDLoc DL(Op);
4856
4857 // DL(G) returns the remainder in the even register and the
4858 // quotient in the odd register.
4859 SDValue Ops[2];
4860 lowerGR128Binary(DAG, DL, VT, SystemZISD::UDIVREM,
4861 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
4862 return DAG.getMergeValues(Ops, DL);
4863}
4864
4865SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
4866 assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
4867
4868 // Get the known-zero masks for each operand.
4869 SDValue Ops[] = {Op.getOperand(0), Op.getOperand(1)};
4870 KnownBits Known[2] = {DAG.computeKnownBits(Ops[0]),
4871 DAG.computeKnownBits(Ops[1])};
4872
4873 // See if the upper 32 bits of one operand and the lower 32 bits of the
4874 // other are known zero. They are the low and high operands respectively.
4875 uint64_t Masks[] = { Known[0].Zero.getZExtValue(),
4876 Known[1].Zero.getZExtValue() };
4877 unsigned High, Low;
4878 if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
4879 High = 1, Low = 0;
4880 else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
4881 High = 0, Low = 1;
4882 else
4883 return Op;
4884
4885 SDValue LowOp = Ops[Low];
4886 SDValue HighOp = Ops[High];
4887
4888 // If the high part is a constant, we're better off using IILH.
4889 if (HighOp.getOpcode() == ISD::Constant)
4890 return Op;
4891
4892 // If the low part is a constant that is outside the range of LHI,
4893 // then we're better off using IILF.
4894 if (LowOp.getOpcode() == ISD::Constant) {
4895 int64_t Value = int32_t(LowOp->getAsZExtVal());
4896 if (!isInt<16>(Value))
4897 return Op;
4898 }
4899
4900 // Check whether the high part is an AND that doesn't change the
4901 // high 32 bits and just masks out low bits. We can skip it if so.
4902 if (HighOp.getOpcode() == ISD::AND &&
4903 HighOp.getOperand(1).getOpcode() == ISD::Constant) {
4904 SDValue HighOp0 = HighOp.getOperand(0);
4906 if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
4907 HighOp = HighOp0;
4908 }
4909
4910 // Take advantage of the fact that all GR32 operations only change the
4911 // low 32 bits by truncating Low to an i32 and inserting it directly
4912 // using a subreg. The interesting cases are those where the truncation
4913 // can be folded.
4914 SDLoc DL(Op);
4915 SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
4916 return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
4917 MVT::i64, HighOp, Low32);
4918}
4919
4920// Lower SADDO/SSUBO/UADDO/USUBO nodes.
4921SDValue SystemZTargetLowering::lowerXALUO(SDValue Op,
4922 SelectionDAG &DAG) const {
4923 SDNode *N = Op.getNode();
4924 SDValue LHS = N->getOperand(0);
4925 SDValue RHS = N->getOperand(1);
4926 SDLoc DL(N);
4927
4928 if (N->getValueType(0) == MVT::i128) {
4929 unsigned BaseOp = 0;
4930 unsigned FlagOp = 0;
4931 bool IsBorrow = false;
4932 switch (Op.getOpcode()) {
4933 default: llvm_unreachable("Unknown instruction!");
4934 case ISD::UADDO:
4935 BaseOp = ISD::ADD;
4936 FlagOp = SystemZISD::VACC;
4937 break;
4938 case ISD::USUBO:
4939 BaseOp = ISD::SUB;
4940 FlagOp = SystemZISD::VSCBI;
4941 IsBorrow = true;
4942 break;
4943 }
4944 SDValue Result = DAG.getNode(BaseOp, DL, MVT::i128, LHS, RHS);
4945 SDValue Flag = DAG.getNode(FlagOp, DL, MVT::i128, LHS, RHS);
4946 Flag = DAG.getNode(ISD::AssertZext, DL, MVT::i128, Flag,
4947 DAG.getValueType(MVT::i1));
4948 Flag = DAG.getZExtOrTrunc(Flag, DL, N->getValueType(1));
4949 if (IsBorrow)
4950 Flag = DAG.getNode(ISD::XOR, DL, Flag.getValueType(),
4951 Flag, DAG.getConstant(1, DL, Flag.getValueType()));
4952 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Flag);
4953 }
4954
4955 unsigned BaseOp = 0;
4956 unsigned CCValid = 0;
4957 unsigned CCMask = 0;
4958
4959 switch (Op.getOpcode()) {
4960 default: llvm_unreachable("Unknown instruction!");
4961 case ISD::SADDO:
4962 BaseOp = SystemZISD::SADDO;
4963 CCValid = SystemZ::CCMASK_ARITH;
4965 break;
4966 case ISD::SSUBO:
4967 BaseOp = SystemZISD::SSUBO;
4968 CCValid = SystemZ::CCMASK_ARITH;
4970 break;
4971 case ISD::UADDO:
4972 BaseOp = SystemZISD::UADDO;
4973 CCValid = SystemZ::CCMASK_LOGICAL;
4975 break;
4976 case ISD::USUBO:
4977 BaseOp = SystemZISD::USUBO;
4978 CCValid = SystemZ::CCMASK_LOGICAL;
4980 break;
4981 }
4982
4983 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
4984 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
4985
4986 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
4987 if (N->getValueType(1) == MVT::i1)
4988 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
4989
4990 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
4991}
4992
4993static bool isAddCarryChain(SDValue Carry) {
4994 while (Carry.getOpcode() == ISD::UADDO_CARRY &&
4995 Carry->getValueType(0) != MVT::i128)
4996 Carry = Carry.getOperand(2);
4997 return Carry.getOpcode() == ISD::UADDO &&
4998 Carry->getValueType(0) != MVT::i128;
4999}
5000
5001static bool isSubBorrowChain(SDValue Carry) {
5002 while (Carry.getOpcode() == ISD::USUBO_CARRY &&
5003 Carry->getValueType(0) != MVT::i128)
5004 Carry = Carry.getOperand(2);
5005 return Carry.getOpcode() == ISD::USUBO &&
5006 Carry->getValueType(0) != MVT::i128;
5007}
5008
5009// Lower UADDO_CARRY/USUBO_CARRY nodes.
5010SDValue SystemZTargetLowering::lowerUADDSUBO_CARRY(SDValue Op,
5011 SelectionDAG &DAG) const {
5012
5013 SDNode *N = Op.getNode();
5014 MVT VT = N->getSimpleValueType(0);
5015
5016 // Let legalize expand this if it isn't a legal type yet.
5017 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
5018 return SDValue();
5019
5020 SDValue LHS = N->getOperand(0);
5021 SDValue RHS = N->getOperand(1);
5022 SDValue Carry = Op.getOperand(2);
5023 SDLoc DL(N);
5024
5025 if (VT == MVT::i128) {
5026 unsigned BaseOp = 0;
5027 unsigned FlagOp = 0;
5028 bool IsBorrow = false;
5029 switch (Op.getOpcode()) {
5030 default: llvm_unreachable("Unknown instruction!");
5031 case ISD::UADDO_CARRY:
5032 BaseOp = SystemZISD::VAC;
5033 FlagOp = SystemZISD::VACCC;
5034 break;
5035 case ISD::USUBO_CARRY:
5036 BaseOp = SystemZISD::VSBI;
5037 FlagOp = SystemZISD::VSBCBI;
5038 IsBorrow = true;
5039 break;
5040 }
5041 if (IsBorrow)
5042 Carry = DAG.getNode(ISD::XOR, DL, Carry.getValueType(),
5043 Carry, DAG.getConstant(1, DL, Carry.getValueType()));
5044 Carry = DAG.getZExtOrTrunc(Carry, DL, MVT::i128);
5045 SDValue Result = DAG.getNode(BaseOp, DL, MVT::i128, LHS, RHS, Carry);
5046 SDValue Flag = DAG.getNode(FlagOp, DL, MVT::i128, LHS, RHS, Carry);
5047 Flag = DAG.getNode(ISD::AssertZext, DL, MVT::i128, Flag,
5048 DAG.getValueType(MVT::i1));
5049 Flag = DAG.getZExtOrTrunc(Flag, DL, N->getValueType(1));
5050 if (IsBorrow)
5051 Flag = DAG.getNode(ISD::XOR, DL, Flag.getValueType(),
5052 Flag, DAG.getConstant(1, DL, Flag.getValueType()));
5053 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Flag);
5054 }
5055
5056 unsigned BaseOp = 0;
5057 unsigned CCValid = 0;
5058 unsigned CCMask = 0;
5059
5060 switch (Op.getOpcode()) {
5061 default: llvm_unreachable("Unknown instruction!");
5062 case ISD::UADDO_CARRY:
5063 if (!isAddCarryChain(Carry))
5064 return SDValue();
5065
5066 BaseOp = SystemZISD::ADDCARRY;
5067 CCValid = SystemZ::CCMASK_LOGICAL;
5069 break;
5070 case ISD::USUBO_CARRY:
5071 if (!isSubBorrowChain(Carry))
5072 return SDValue();
5073
5074 BaseOp = SystemZISD::SUBCARRY;
5075 CCValid = SystemZ::CCMASK_LOGICAL;
5077 break;
5078 }
5079
5080 // Set the condition code from the carry flag.
5081 Carry = DAG.getNode(SystemZISD::GET_CCMASK, DL, MVT::i32, Carry,
5082 DAG.getConstant(CCValid, DL, MVT::i32),
5083 DAG.getConstant(CCMask, DL, MVT::i32));
5084
5085 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5086 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS, Carry);
5087
5088 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
5089 if (N->getValueType(1) == MVT::i1)
5090 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
5091
5092 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
5093}
5094
5095SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op,
5096 SelectionDAG &DAG) const {
5097 EVT VT = Op.getValueType();
5098 SDLoc DL(Op);
5099 Op = Op.getOperand(0);
5100
5101 if (VT.getScalarSizeInBits() == 128) {
5102 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op);
5103 Op = DAG.getNode(ISD::CTPOP, DL, MVT::v2i64, Op);
5104 SDValue Tmp = DAG.getSplatBuildVector(MVT::v2i64, DL,
5105 DAG.getConstant(0, DL, MVT::i64));
5106 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
5107 return Op;
5108 }
5109
5110 // Handle vector types via VPOPCT.
5111 if (VT.isVector()) {
5112 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op);
5113 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op);
5114 switch (VT.getScalarSizeInBits()) {
5115 case 8:
5116 break;
5117 case 16: {
5118 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
5119 SDValue Shift = DAG.getConstant(8, DL, MVT::i32);
5120 SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift);
5121 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
5122 Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift);
5123 break;
5124 }
5125 case 32: {
5126 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
5127 DAG.getConstant(0, DL, MVT::i32));
5128 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
5129 break;
5130 }
5131 case 64: {
5132 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
5133 DAG.getConstant(0, DL, MVT::i32));
5134 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp);
5135 Tmp = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, Tmp);
5136 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
5137 break;
5138 }
5139 default:
5140 llvm_unreachable("Unexpected type");
5141 }
5142 return Op;
5143 }
5144
5145 // Get the known-zero mask for the operand.
5146 KnownBits Known = DAG.computeKnownBits(Op);
5147 unsigned NumSignificantBits = Known.getMaxValue().getActiveBits();
5148 if (NumSignificantBits == 0)
5149 return DAG.getConstant(0, DL, VT);
5150
5151 // Skip known-zero high parts of the operand.
5152 int64_t OrigBitSize = VT.getSizeInBits();
5153 int64_t BitSize = llvm::bit_ceil(NumSignificantBits);
5154 BitSize = std::min(BitSize, OrigBitSize);
5155
5156 // The POPCNT instruction counts the number of bits in each byte.
5157 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op);
5158 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op);
5159 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
5160
5161 // Add up per-byte counts in a binary tree. All bits of Op at
5162 // position larger than BitSize remain zero throughout.
5163 for (int64_t I = BitSize / 2; I >= 8; I = I / 2) {
5164 SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT));
5165 if (BitSize != OrigBitSize)
5166 Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp,
5167 DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT));
5168 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
5169 }
5170
5171 // Extract overall result from high byte.
5172 if (BitSize > 8)
5173 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5174 DAG.getConstant(BitSize - 8, DL, VT));
5175
5176 return Op;
5177}
5178
5179SDValue SystemZTargetLowering::lowerATOMIC_FENCE(SDValue Op,
5180 SelectionDAG &DAG) const {
5181 SDLoc DL(Op);
5182 AtomicOrdering FenceOrdering =
5183 static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
5184 SyncScope::ID FenceSSID =
5185 static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
5186
5187 // The only fence that needs an instruction is a sequentially-consistent
5188 // cross-thread fence.
5189 if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
5190 FenceSSID == SyncScope::System) {
5191 return SDValue(DAG.getMachineNode(SystemZ::Serialize, DL, MVT::Other,
5192 Op.getOperand(0)),
5193 0);
5194 }
5195
5196 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
5197 return DAG.getNode(ISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
5198}
5199
5200SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
5201 SelectionDAG &DAG) const {
5202 EVT RegVT = Op.getValueType();
5203 if (RegVT.getSizeInBits() == 128)
5204 return lowerATOMIC_LDST_I128(Op, DAG);
5205 return lowerLoadF16(Op, DAG);
5206}
5207
5208SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
5209 SelectionDAG &DAG) const {
5210 auto *Node = cast<AtomicSDNode>(Op.getNode());
5211 if (Node->getMemoryVT().getSizeInBits() == 128)
5212 return lowerATOMIC_LDST_I128(Op, DAG);
5213 return lowerStoreF16(Op, DAG);
5214}
5215
5216SDValue SystemZTargetLowering::lowerATOMIC_LDST_I128(SDValue Op,
5217 SelectionDAG &DAG) const {
5218 auto *Node = cast<AtomicSDNode>(Op.getNode());
5219 assert(
5220 (Node->getMemoryVT() == MVT::i128 || Node->getMemoryVT() == MVT::f128) &&
5221 "Only custom lowering i128 or f128.");
5222 // Use same code to handle both legal and non-legal i128 types.
5224 LowerOperationWrapper(Node, Results, DAG);
5225 return DAG.getMergeValues(Results, SDLoc(Op));
5226}
5227
5228// Prepare for a Compare And Swap for a subword operation. This needs to be
5229// done in memory with 4 bytes at natural alignment.
5231 SDValue &AlignedAddr, SDValue &BitShift,
5232 SDValue &NegBitShift) {
5233 EVT PtrVT = Addr.getValueType();
5234 EVT WideVT = MVT::i32;
5235
5236 // Get the address of the containing word.
5237 AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
5238 DAG.getSignedConstant(-4, DL, PtrVT));
5239
5240 // Get the number of bits that the word must be rotated left in order
5241 // to bring the field to the top bits of a GR32.
5242 BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
5243 DAG.getConstant(3, DL, PtrVT));
5244 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
5245
5246 // Get the complementing shift amount, for rotating a field in the top
5247 // bits back to its proper position.
5248 NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
5249 DAG.getConstant(0, DL, WideVT), BitShift);
5250
5251}
5252
5253// Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation. Lower the first
5254// two into the fullword ATOMIC_LOADW_* operation given by Opcode.
5255SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op,
5256 SelectionDAG &DAG,
5257 unsigned Opcode) const {
5258 auto *Node = cast<AtomicSDNode>(Op.getNode());
5259
5260 // 32-bit operations need no special handling.
5261 EVT NarrowVT = Node->getMemoryVT();
5262 EVT WideVT = MVT::i32;
5263 if (NarrowVT == WideVT)
5264 return Op;
5265
5266 int64_t BitSize = NarrowVT.getSizeInBits();
5267 SDValue ChainIn = Node->getChain();
5268 SDValue Addr = Node->getBasePtr();
5269 SDValue Src2 = Node->getVal();
5270 MachineMemOperand *MMO = Node->getMemOperand();
5271 SDLoc DL(Node);
5272
5273 // Convert atomic subtracts of constants into additions.
5274 if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
5275 if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
5276 Opcode = SystemZISD::ATOMIC_LOADW_ADD;
5277 Src2 = DAG.getSignedConstant(-Const->getSExtValue(), DL,
5278 Src2.getValueType());
5279 }
5280
5281 SDValue AlignedAddr, BitShift, NegBitShift;
5282 getCSAddressAndShifts(Addr, DAG, DL, AlignedAddr, BitShift, NegBitShift);
5283
5284 // Extend the source operand to 32 bits and prepare it for the inner loop.
5285 // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
5286 // operations require the source to be shifted in advance. (This shift
5287 // can be folded if the source is constant.) For AND and NAND, the lower
5288 // bits must be set, while for other opcodes they should be left clear.
5289 if (Opcode != SystemZISD::ATOMIC_SWAPW)
5290 Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
5291 DAG.getConstant(32 - BitSize, DL, WideVT));
5292 if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
5293 Opcode == SystemZISD::ATOMIC_LOADW_NAND)
5294 Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
5295 DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT));
5296
5297 // Construct the ATOMIC_LOADW_* node.
5298 SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
5299 SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
5300 DAG.getConstant(BitSize, DL, WideVT) };
5301 SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
5302 NarrowVT, MMO);
5303
5304 // Rotate the result of the final CS so that the field is in the lower
5305 // bits of a GR32, then truncate it.
5306 SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
5307 DAG.getConstant(BitSize, DL, WideVT));
5308 SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
5309
5310 SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
5311 return DAG.getMergeValues(RetOps, DL);
5312}
5313
5314// Op is an ATOMIC_LOAD_SUB operation. Lower 8- and 16-bit operations into
5315// ATOMIC_LOADW_SUBs and convert 32- and 64-bit operations into additions.
5316SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
5317 SelectionDAG &DAG) const {
5318 auto *Node = cast<AtomicSDNode>(Op.getNode());
5319 EVT MemVT = Node->getMemoryVT();
5320 if (MemVT == MVT::i32 || MemVT == MVT::i64) {
5321 // A full-width operation: negate and use LAA(G).
5322 assert(Op.getValueType() == MemVT && "Mismatched VTs");
5323 assert(Subtarget.hasInterlockedAccess1() &&
5324 "Should have been expanded by AtomicExpand pass.");
5325 SDValue Src2 = Node->getVal();
5326 SDLoc DL(Src2);
5327 SDValue NegSrc2 =
5328 DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT), Src2);
5329 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT,
5330 Node->getChain(), Node->getBasePtr(), NegSrc2,
5331 Node->getMemOperand());
5332 }
5333
5334 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
5335}
5336
5337// Lower 8/16/32/64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS node.
5338SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
5339 SelectionDAG &DAG) const {
5340 auto *Node = cast<AtomicSDNode>(Op.getNode());
5341 SDValue ChainIn = Node->getOperand(0);
5342 SDValue Addr = Node->getOperand(1);
5343 SDValue CmpVal = Node->getOperand(2);
5344 SDValue SwapVal = Node->getOperand(3);
5345 MachineMemOperand *MMO = Node->getMemOperand();
5346 SDLoc DL(Node);
5347
5348 if (Node->getMemoryVT() == MVT::i128) {
5349 // Use same code to handle both legal and non-legal i128 types.
5351 LowerOperationWrapper(Node, Results, DAG);
5352 return DAG.getMergeValues(Results, DL);
5353 }
5354
5355 // We have native support for 32-bit and 64-bit compare and swap, but we
5356 // still need to expand extracting the "success" result from the CC.
5357 EVT NarrowVT = Node->getMemoryVT();
5358 EVT WideVT = NarrowVT == MVT::i64 ? MVT::i64 : MVT::i32;
5359 if (NarrowVT == WideVT) {
5360 SDVTList Tys = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
5361 SDValue Ops[] = { ChainIn, Addr, CmpVal, SwapVal };
5362 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP,
5363 DL, Tys, Ops, NarrowVT, MMO);
5364 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
5366
5367 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), AtomicOp.getValue(0));
5368 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
5369 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
5370 return SDValue();
5371 }
5372
5373 // Convert 8-bit and 16-bit compare and swap to a loop, implemented
5374 // via a fullword ATOMIC_CMP_SWAPW operation.
5375 int64_t BitSize = NarrowVT.getSizeInBits();
5376
5377 SDValue AlignedAddr, BitShift, NegBitShift;
5378 getCSAddressAndShifts(Addr, DAG, DL, AlignedAddr, BitShift, NegBitShift);
5379
5380 // Construct the ATOMIC_CMP_SWAPW node.
5381 SDVTList VTList = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
5382 SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
5383 NegBitShift, DAG.getConstant(BitSize, DL, WideVT) };
5384 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
5385 VTList, Ops, NarrowVT, MMO);
5386 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
5388
5389 // emitAtomicCmpSwapW() will zero extend the result (original value).
5390 SDValue OrigVal = DAG.getNode(ISD::AssertZext, DL, WideVT, AtomicOp.getValue(0),
5391 DAG.getValueType(NarrowVT));
5392 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), OrigVal);
5393 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
5394 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
5395 return SDValue();
5396}
5397
5399SystemZTargetLowering::getTargetMMOFlags(const Instruction &I) const {
5400 // Because of how we convert atomic_load and atomic_store to normal loads and
5401 // stores in the DAG, we need to ensure that the MMOs are marked volatile
5402 // since DAGCombine hasn't been updated to account for atomic, but non
5403 // volatile loads. (See D57601)
5404 if (auto *SI = dyn_cast<StoreInst>(&I))
5405 if (SI->isAtomic())
5407 if (auto *LI = dyn_cast<LoadInst>(&I))
5408 if (LI->isAtomic())
5410 if (auto *AI = dyn_cast<AtomicRMWInst>(&I))
5411 if (AI->isAtomic())
5413 if (auto *AI = dyn_cast<AtomicCmpXchgInst>(&I))
5414 if (AI->isAtomic())
5417}
5418
5419SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
5420 SelectionDAG &DAG) const {
5422 auto *Regs = Subtarget.getSpecialRegisters();
5424 report_fatal_error("Variable-sized stack allocations are not supported "
5425 "in GHC calling convention");
5426 return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
5427 Regs->getStackPointerRegister(), Op.getValueType());
5428}
5429
5430SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
5431 SelectionDAG &DAG) const {
5433 auto *Regs = Subtarget.getSpecialRegisters();
5434 bool StoreBackchain = MF.getSubtarget<SystemZSubtarget>().hasBackChain();
5435
5437 report_fatal_error("Variable-sized stack allocations are not supported "
5438 "in GHC calling convention");
5439
5440 SDValue Chain = Op.getOperand(0);
5441 SDValue NewSP = Op.getOperand(1);
5442 SDValue Backchain;
5443 SDLoc DL(Op);
5444
5445 if (StoreBackchain) {
5446 SDValue OldSP = DAG.getCopyFromReg(
5447 Chain, DL, Regs->getStackPointerRegister(), MVT::i64);
5448 Backchain = DAG.getLoad(MVT::i64, DL, Chain, getBackchainAddress(OldSP, DAG),
5449 MachinePointerInfo());
5450 }
5451
5452 Chain = DAG.getCopyToReg(Chain, DL, Regs->getStackPointerRegister(), NewSP);
5453
5454 if (StoreBackchain)
5455 Chain = DAG.getStore(Chain, DL, Backchain, getBackchainAddress(NewSP, DAG),
5456 MachinePointerInfo());
5457
5458 return Chain;
5459}
5460
5461SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
5462 SelectionDAG &DAG) const {
5463 bool IsData = Op.getConstantOperandVal(4);
5464 if (!IsData)
5465 // Just preserve the chain.
5466 return Op.getOperand(0);
5467
5468 SDLoc DL(Op);
5469 bool IsWrite = Op.getConstantOperandVal(2);
5470 unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
5471 auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
5472 SDValue Ops[] = {Op.getOperand(0), DAG.getTargetConstant(Code, DL, MVT::i32),
5473 Op.getOperand(1)};
5474 return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, DL,
5475 Node->getVTList(), Ops,
5476 Node->getMemoryVT(), Node->getMemOperand());
5477}
5478
5479SDValue
5480SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
5481 SelectionDAG &DAG) const {
5482 unsigned Opcode, CCValid;
5483 if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) {
5484 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
5485 SDNode *Node = emitIntrinsicWithCCAndChain(DAG, Op, Opcode);
5486 SDValue CC = getCCResult(DAG, SDValue(Node, 0));
5487 DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC);
5488 return SDValue();
5489 }
5490
5491 return SDValue();
5492}
5493
5494SDValue
5495SystemZTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
5496 SelectionDAG &DAG) const {
5497 unsigned Opcode, CCValid;
5498 if (isIntrinsicWithCC(Op, Opcode, CCValid)) {
5499 SDNode *Node = emitIntrinsicWithCC(DAG, Op, Opcode);
5500 if (Op->getNumValues() == 1)
5501 return getCCResult(DAG, SDValue(Node, 0));
5502 assert(Op->getNumValues() == 2 && "Expected a CC and non-CC result");
5503 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), Op->getVTList(),
5504 SDValue(Node, 0), getCCResult(DAG, SDValue(Node, 1)));
5505 }
5506
5507 unsigned Id = Op.getConstantOperandVal(0);
5508 switch (Id) {
5509 case Intrinsic::thread_pointer:
5510 return lowerThreadPointer(SDLoc(Op), DAG);
5511
5512 case Intrinsic::s390_vpdi:
5513 return DAG.getNode(SystemZISD::PERMUTE_DWORDS, SDLoc(Op), Op.getValueType(),
5514 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5515
5516 case Intrinsic::s390_vperm:
5517 return DAG.getNode(SystemZISD::PERMUTE, SDLoc(Op), Op.getValueType(),
5518 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5519
5520 case Intrinsic::s390_vuphb:
5521 case Intrinsic::s390_vuphh:
5522 case Intrinsic::s390_vuphf:
5523 case Intrinsic::s390_vuphg:
5524 return DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(Op), Op.getValueType(),
5525 Op.getOperand(1));
5526
5527 case Intrinsic::s390_vuplhb:
5528 case Intrinsic::s390_vuplhh:
5529 case Intrinsic::s390_vuplhf:
5530 case Intrinsic::s390_vuplhg:
5531 return DAG.getNode(SystemZISD::UNPACKL_HIGH, SDLoc(Op), Op.getValueType(),
5532 Op.getOperand(1));
5533
5534 case Intrinsic::s390_vuplb:
5535 case Intrinsic::s390_vuplhw:
5536 case Intrinsic::s390_vuplf:
5537 case Intrinsic::s390_vuplg:
5538 return DAG.getNode(SystemZISD::UNPACK_LOW, SDLoc(Op), Op.getValueType(),
5539 Op.getOperand(1));
5540
5541 case Intrinsic::s390_vupllb:
5542 case Intrinsic::s390_vupllh:
5543 case Intrinsic::s390_vupllf:
5544 case Intrinsic::s390_vupllg:
5545 return DAG.getNode(SystemZISD::UNPACKL_LOW, SDLoc(Op), Op.getValueType(),
5546 Op.getOperand(1));
5547
5548 case Intrinsic::s390_vsumb:
5549 case Intrinsic::s390_vsumh:
5550 case Intrinsic::s390_vsumgh:
5551 case Intrinsic::s390_vsumgf:
5552 case Intrinsic::s390_vsumqf:
5553 case Intrinsic::s390_vsumqg:
5554 return DAG.getNode(SystemZISD::VSUM, SDLoc(Op), Op.getValueType(),
5555 Op.getOperand(1), Op.getOperand(2));
5556
5557 case Intrinsic::s390_vaq:
5558 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5559 Op.getOperand(1), Op.getOperand(2));
5560 case Intrinsic::s390_vaccb:
5561 case Intrinsic::s390_vacch:
5562 case Intrinsic::s390_vaccf:
5563 case Intrinsic::s390_vaccg:
5564 case Intrinsic::s390_vaccq:
5565 return DAG.getNode(SystemZISD::VACC, SDLoc(Op), Op.getValueType(),
5566 Op.getOperand(1), Op.getOperand(2));
5567 case Intrinsic::s390_vacq:
5568 return DAG.getNode(SystemZISD::VAC, SDLoc(Op), Op.getValueType(),
5569 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5570 case Intrinsic::s390_vacccq:
5571 return DAG.getNode(SystemZISD::VACCC, SDLoc(Op), Op.getValueType(),
5572 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5573
5574 case Intrinsic::s390_vsq:
5575 return DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(),
5576 Op.getOperand(1), Op.getOperand(2));
5577 case Intrinsic::s390_vscbib:
5578 case Intrinsic::s390_vscbih:
5579 case Intrinsic::s390_vscbif:
5580 case Intrinsic::s390_vscbig:
5581 case Intrinsic::s390_vscbiq:
5582 return DAG.getNode(SystemZISD::VSCBI, SDLoc(Op), Op.getValueType(),
5583 Op.getOperand(1), Op.getOperand(2));
5584 case Intrinsic::s390_vsbiq:
5585 return DAG.getNode(SystemZISD::VSBI, SDLoc(Op), Op.getValueType(),
5586 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5587 case Intrinsic::s390_vsbcbiq:
5588 return DAG.getNode(SystemZISD::VSBCBI, SDLoc(Op), Op.getValueType(),
5589 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5590
5591 case Intrinsic::s390_vmhb:
5592 case Intrinsic::s390_vmhh:
5593 case Intrinsic::s390_vmhf:
5594 case Intrinsic::s390_vmhg:
5595 case Intrinsic::s390_vmhq:
5596 return DAG.getNode(ISD::MULHS, SDLoc(Op), Op.getValueType(),
5597 Op.getOperand(1), Op.getOperand(2));
5598 case Intrinsic::s390_vmlhb:
5599 case Intrinsic::s390_vmlhh:
5600 case Intrinsic::s390_vmlhf:
5601 case Intrinsic::s390_vmlhg:
5602 case Intrinsic::s390_vmlhq:
5603 return DAG.getNode(ISD::MULHU, SDLoc(Op), Op.getValueType(),
5604 Op.getOperand(1), Op.getOperand(2));
5605
5606 case Intrinsic::s390_vmahb:
5607 case Intrinsic::s390_vmahh:
5608 case Intrinsic::s390_vmahf:
5609 case Intrinsic::s390_vmahg:
5610 case Intrinsic::s390_vmahq:
5611 return DAG.getNode(SystemZISD::VMAH, SDLoc(Op), Op.getValueType(),
5612 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5613 case Intrinsic::s390_vmalhb:
5614 case Intrinsic::s390_vmalhh:
5615 case Intrinsic::s390_vmalhf:
5616 case Intrinsic::s390_vmalhg:
5617 case Intrinsic::s390_vmalhq:
5618 return DAG.getNode(SystemZISD::VMALH, SDLoc(Op), Op.getValueType(),
5619 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5620
5621 case Intrinsic::s390_vmeb:
5622 case Intrinsic::s390_vmeh:
5623 case Intrinsic::s390_vmef:
5624 case Intrinsic::s390_vmeg:
5625 return DAG.getNode(SystemZISD::VME, SDLoc(Op), Op.getValueType(),
5626 Op.getOperand(1), Op.getOperand(2));
5627 case Intrinsic::s390_vmleb:
5628 case Intrinsic::s390_vmleh:
5629 case Intrinsic::s390_vmlef:
5630 case Intrinsic::s390_vmleg:
5631 return DAG.getNode(SystemZISD::VMLE, SDLoc(Op), Op.getValueType(),
5632 Op.getOperand(1), Op.getOperand(2));
5633 case Intrinsic::s390_vmob:
5634 case Intrinsic::s390_vmoh:
5635 case Intrinsic::s390_vmof:
5636 case Intrinsic::s390_vmog:
5637 return DAG.getNode(SystemZISD::VMO, SDLoc(Op), Op.getValueType(),
5638 Op.getOperand(1), Op.getOperand(2));
5639 case Intrinsic::s390_vmlob:
5640 case Intrinsic::s390_vmloh:
5641 case Intrinsic::s390_vmlof:
5642 case Intrinsic::s390_vmlog:
5643 return DAG.getNode(SystemZISD::VMLO, SDLoc(Op), Op.getValueType(),
5644 Op.getOperand(1), Op.getOperand(2));
5645
5646 case Intrinsic::s390_vmaeb:
5647 case Intrinsic::s390_vmaeh:
5648 case Intrinsic::s390_vmaef:
5649 case Intrinsic::s390_vmaeg:
5650 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5651 DAG.getNode(SystemZISD::VME, SDLoc(Op), Op.getValueType(),
5652 Op.getOperand(1), Op.getOperand(2)),
5653 Op.getOperand(3));
5654 case Intrinsic::s390_vmaleb:
5655 case Intrinsic::s390_vmaleh:
5656 case Intrinsic::s390_vmalef:
5657 case Intrinsic::s390_vmaleg:
5658 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5659 DAG.getNode(SystemZISD::VMLE, SDLoc(Op), Op.getValueType(),
5660 Op.getOperand(1), Op.getOperand(2)),
5661 Op.getOperand(3));
5662 case Intrinsic::s390_vmaob:
5663 case Intrinsic::s390_vmaoh:
5664 case Intrinsic::s390_vmaof:
5665 case Intrinsic::s390_vmaog:
5666 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5667 DAG.getNode(SystemZISD::VMO, SDLoc(Op), Op.getValueType(),
5668 Op.getOperand(1), Op.getOperand(2)),
5669 Op.getOperand(3));
5670 case Intrinsic::s390_vmalob:
5671 case Intrinsic::s390_vmaloh:
5672 case Intrinsic::s390_vmalof:
5673 case Intrinsic::s390_vmalog:
5674 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5675 DAG.getNode(SystemZISD::VMLO, SDLoc(Op), Op.getValueType(),
5676 Op.getOperand(1), Op.getOperand(2)),
5677 Op.getOperand(3));
5678 }
5679
5680 return SDValue();
5681}
5682
5683namespace {
5684// Says that SystemZISD operation Opcode can be used to perform the equivalent
5685// of a VPERM with permute vector Bytes. If Opcode takes three operands,
5686// Operand is the constant third operand, otherwise it is the number of
5687// bytes in each element of the result.
5688struct Permute {
5689 unsigned Opcode;
5690 unsigned Operand;
5691 unsigned char Bytes[SystemZ::VectorBytes];
5692};
5693}
5694
5695static const Permute PermuteForms[] = {
5696 // VMRHG
5697 { SystemZISD::MERGE_HIGH, 8,
5698 { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } },
5699 // VMRHF
5700 { SystemZISD::MERGE_HIGH, 4,
5701 { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } },
5702 // VMRHH
5703 { SystemZISD::MERGE_HIGH, 2,
5704 { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } },
5705 // VMRHB
5706 { SystemZISD::MERGE_HIGH, 1,
5707 { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } },
5708 // VMRLG
5709 { SystemZISD::MERGE_LOW, 8,
5710 { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } },
5711 // VMRLF
5712 { SystemZISD::MERGE_LOW, 4,
5713 { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
5714 // VMRLH
5715 { SystemZISD::MERGE_LOW, 2,
5716 { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
5717 // VMRLB
5718 { SystemZISD::MERGE_LOW, 1,
5719 { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
5720 // VPKG
5721 { SystemZISD::PACK, 4,
5722 { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } },
5723 // VPKF
5724 { SystemZISD::PACK, 2,
5725 { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
5726 // VPKH
5727 { SystemZISD::PACK, 1,
5728 { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
5729 // VPDI V1, V2, 4 (low half of V1, high half of V2)
5730 { SystemZISD::PERMUTE_DWORDS, 4,
5731 { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } },
5732 // VPDI V1, V2, 1 (high half of V1, low half of V2)
5733 { SystemZISD::PERMUTE_DWORDS, 1,
5734 { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } }
5735};
5736
5737// Called after matching a vector shuffle against a particular pattern.
5738// Both the original shuffle and the pattern have two vector operands.
5739// OpNos[0] is the operand of the original shuffle that should be used for
5740// operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything.
5741// OpNos[1] is the same for operand 1 of the pattern. Resolve these -1s and
5742// set OpNo0 and OpNo1 to the shuffle operands that should actually be used
5743// for operands 0 and 1 of the pattern.
5744static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) {
5745 if (OpNos[0] < 0) {
5746 if (OpNos[1] < 0)
5747 return false;
5748 OpNo0 = OpNo1 = OpNos[1];
5749 } else if (OpNos[1] < 0) {
5750 OpNo0 = OpNo1 = OpNos[0];
5751 } else {
5752 OpNo0 = OpNos[0];
5753 OpNo1 = OpNos[1];
5754 }
5755 return true;
5756}
5757
5758// Bytes is a VPERM-like permute vector, except that -1 is used for
5759// undefined bytes. Return true if the VPERM can be implemented using P.
5760// When returning true set OpNo0 to the VPERM operand that should be
5761// used for operand 0 of P and likewise OpNo1 for operand 1 of P.
5762//
5763// For example, if swapping the VPERM operands allows P to match, OpNo0
5764// will be 1 and OpNo1 will be 0. If instead Bytes only refers to one
5765// operand, but rewriting it to use two duplicated operands allows it to
5766// match P, then OpNo0 and OpNo1 will be the same.
5767static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P,
5768 unsigned &OpNo0, unsigned &OpNo1) {
5769 int OpNos[] = { -1, -1 };
5770 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
5771 int Elt = Bytes[I];
5772 if (Elt >= 0) {
5773 // Make sure that the two permute vectors use the same suboperand
5774 // byte number. Only the operand numbers (the high bits) are
5775 // allowed to differ.
5776 if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1))
5777 return false;
5778 int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes;
5779 int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes;
5780 // Make sure that the operand mappings are consistent with previous
5781 // elements.
5782 if (OpNos[ModelOpNo] == 1 - RealOpNo)
5783 return false;
5784 OpNos[ModelOpNo] = RealOpNo;
5785 }
5786 }
5787 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
5788}
5789
5790// As above, but search for a matching permute.
5791static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes,
5792 unsigned &OpNo0, unsigned &OpNo1) {
5793 for (auto &P : PermuteForms)
5794 if (matchPermute(Bytes, P, OpNo0, OpNo1))
5795 return &P;
5796 return nullptr;
5797}
5798
5799// Bytes is a VPERM-like permute vector, except that -1 is used for
5800// undefined bytes. This permute is an operand of an outer permute.
5801// See whether redistributing the -1 bytes gives a shuffle that can be
5802// implemented using P. If so, set Transform to a VPERM-like permute vector
5803// that, when applied to the result of P, gives the original permute in Bytes.
5805 const Permute &P,
5806 SmallVectorImpl<int> &Transform) {
5807 unsigned To = 0;
5808 for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) {
5809 int Elt = Bytes[From];
5810 if (Elt < 0)
5811 // Byte number From of the result is undefined.
5812 Transform[From] = -1;
5813 else {
5814 while (P.Bytes[To] != Elt) {
5815 To += 1;
5816 if (To == SystemZ::VectorBytes)
5817 return false;
5818 }
5819 Transform[From] = To;
5820 }
5821 }
5822 return true;
5823}
5824
5825// As above, but search for a matching permute.
5826static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes,
5827 SmallVectorImpl<int> &Transform) {
5828 for (auto &P : PermuteForms)
5829 if (matchDoublePermute(Bytes, P, Transform))
5830 return &P;
5831 return nullptr;
5832}
5833
5834// Convert the mask of the given shuffle op into a byte-level mask,
5835// as if it had type vNi8.
5836static bool getVPermMask(SDValue ShuffleOp,
5837 SmallVectorImpl<int> &Bytes) {
5838 EVT VT = ShuffleOp.getValueType();
5839 unsigned NumElements = VT.getVectorNumElements();
5840 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
5841
5842 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(ShuffleOp)) {
5843 Bytes.resize(NumElements * BytesPerElement, -1);
5844 for (unsigned I = 0; I < NumElements; ++I) {
5845 int Index = VSN->getMaskElt(I);
5846 if (Index >= 0)
5847 for (unsigned J = 0; J < BytesPerElement; ++J)
5848 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
5849 }
5850 return true;
5851 }
5852 if (SystemZISD::SPLAT == ShuffleOp.getOpcode() &&
5853 isa<ConstantSDNode>(ShuffleOp.getOperand(1))) {
5854 unsigned Index = ShuffleOp.getConstantOperandVal(1);
5855 Bytes.resize(NumElements * BytesPerElement, -1);
5856 for (unsigned I = 0; I < NumElements; ++I)
5857 for (unsigned J = 0; J < BytesPerElement; ++J)
5858 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
5859 return true;
5860 }
5861 return false;
5862}
5863
5864// Bytes is a VPERM-like permute vector, except that -1 is used for
5865// undefined bytes. See whether bytes [Start, Start + BytesPerElement) of
5866// the result come from a contiguous sequence of bytes from one input.
5867// Set Base to the selector for the first byte if so.
5868static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start,
5869 unsigned BytesPerElement, int &Base) {
5870 Base = -1;
5871 for (unsigned I = 0; I < BytesPerElement; ++I) {
5872 if (Bytes[Start + I] >= 0) {
5873 unsigned Elem = Bytes[Start + I];
5874 if (Base < 0) {
5875 Base = Elem - I;
5876 // Make sure the bytes would come from one input operand.
5877 if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size())
5878 return false;
5879 } else if (unsigned(Base) != Elem - I)
5880 return false;
5881 }
5882 }
5883 return true;
5884}
5885
5886// Bytes is a VPERM-like permute vector, except that -1 is used for
5887// undefined bytes. Return true if it can be performed using VSLDB.
5888// When returning true, set StartIndex to the shift amount and OpNo0
5889// and OpNo1 to the VPERM operands that should be used as the first
5890// and second shift operand respectively.
5892 unsigned &StartIndex, unsigned &OpNo0,
5893 unsigned &OpNo1) {
5894 int OpNos[] = { -1, -1 };
5895 int Shift = -1;
5896 for (unsigned I = 0; I < 16; ++I) {
5897 int Index = Bytes[I];
5898 if (Index >= 0) {
5899 int ExpectedShift = (Index - I) % SystemZ::VectorBytes;
5900 int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes;
5901 int RealOpNo = unsigned(Index) / SystemZ::VectorBytes;
5902 if (Shift < 0)
5903 Shift = ExpectedShift;
5904 else if (Shift != ExpectedShift)
5905 return false;
5906 // Make sure that the operand mappings are consistent with previous
5907 // elements.
5908 if (OpNos[ModelOpNo] == 1 - RealOpNo)
5909 return false;
5910 OpNos[ModelOpNo] = RealOpNo;
5911 }
5912 }
5913 StartIndex = Shift;
5914 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
5915}
5916
5917// Create a node that performs P on operands Op0 and Op1, casting the
5918// operands to the appropriate type. The type of the result is determined by P.
5920 const Permute &P, SDValue Op0, SDValue Op1) {
5921 // VPDI (PERMUTE_DWORDS) always operates on v2i64s. The input
5922 // elements of a PACK are twice as wide as the outputs.
5923 unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 :
5924 P.Opcode == SystemZISD::PACK ? P.Operand * 2 :
5925 P.Operand);
5926 // Cast both operands to the appropriate type.
5927 MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8),
5928 SystemZ::VectorBytes / InBytes);
5929 Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0);
5930 Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1);
5931 SDValue Op;
5932 if (P.Opcode == SystemZISD::PERMUTE_DWORDS) {
5933 SDValue Op2 = DAG.getTargetConstant(P.Operand, DL, MVT::i32);
5934 Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2);
5935 } else if (P.Opcode == SystemZISD::PACK) {
5936 MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8),
5937 SystemZ::VectorBytes / P.Operand);
5938 Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1);
5939 } else {
5940 Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1);
5941 }
5942 return Op;
5943}
5944
5945static bool isZeroVector(SDValue N) {
5946 if (N->getOpcode() == ISD::BITCAST)
5947 N = N->getOperand(0);
5948 if (N->getOpcode() == ISD::SPLAT_VECTOR)
5949 if (auto *Op = dyn_cast<ConstantSDNode>(N->getOperand(0)))
5950 return Op->getZExtValue() == 0;
5951 return ISD::isBuildVectorAllZeros(N.getNode());
5952}
5953
5954// Return the index of the zero/undef vector, or UINT32_MAX if not found.
5955static uint32_t findZeroVectorIdx(SDValue *Ops, unsigned Num) {
5956 for (unsigned I = 0; I < Num ; I++)
5957 if (isZeroVector(Ops[I]))
5958 return I;
5959 return UINT32_MAX;
5960}
5961
5962// Bytes is a VPERM-like permute vector, except that -1 is used for
5963// undefined bytes. Implement it on operands Ops[0] and Ops[1] using
5964// VSLDB or VPERM.
5966 SDValue *Ops,
5967 const SmallVectorImpl<int> &Bytes) {
5968 for (unsigned I = 0; I < 2; ++I)
5969 Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]);
5970
5971 // First see whether VSLDB can be used.
5972 unsigned StartIndex, OpNo0, OpNo1;
5973 if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1))
5974 return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0],
5975 Ops[OpNo1],
5976 DAG.getTargetConstant(StartIndex, DL, MVT::i32));
5977
5978 // Fall back on VPERM. Construct an SDNode for the permute vector. Try to
5979 // eliminate a zero vector by reusing any zero index in the permute vector.
5980 unsigned ZeroVecIdx = findZeroVectorIdx(&Ops[0], 2);
5981 if (ZeroVecIdx != UINT32_MAX) {
5982 bool MaskFirst = true;
5983 int ZeroIdx = -1;
5984 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
5985 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
5986 unsigned Byte = unsigned(Bytes[I]) % SystemZ::VectorBytes;
5987 if (OpNo == ZeroVecIdx && I == 0) {
5988 // If the first byte is zero, use mask as first operand.
5989 ZeroIdx = 0;
5990 break;
5991 }
5992 if (OpNo != ZeroVecIdx && Byte == 0) {
5993 // If mask contains a zero, use it by placing that vector first.
5994 ZeroIdx = I + SystemZ::VectorBytes;
5995 MaskFirst = false;
5996 break;
5997 }
5998 }
5999 if (ZeroIdx != -1) {
6000 SDValue IndexNodes[SystemZ::VectorBytes];
6001 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
6002 if (Bytes[I] >= 0) {
6003 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
6004 unsigned Byte = unsigned(Bytes[I]) % SystemZ::VectorBytes;
6005 if (OpNo == ZeroVecIdx)
6006 IndexNodes[I] = DAG.getConstant(ZeroIdx, DL, MVT::i32);
6007 else {
6008 unsigned BIdx = MaskFirst ? Byte + SystemZ::VectorBytes : Byte;
6009 IndexNodes[I] = DAG.getConstant(BIdx, DL, MVT::i32);
6010 }
6011 } else
6012 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
6013 }
6014 SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
6015 SDValue Src = ZeroVecIdx == 0 ? Ops[1] : Ops[0];
6016 if (MaskFirst)
6017 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Mask, Src,
6018 Mask);
6019 else
6020 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Src, Mask,
6021 Mask);
6022 }
6023 }
6024
6025 SDValue IndexNodes[SystemZ::VectorBytes];
6026 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
6027 if (Bytes[I] >= 0)
6028 IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32);
6029 else
6030 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
6031 SDValue Op2 = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
6032 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0],
6033 (!Ops[1].isUndef() ? Ops[1] : Ops[0]), Op2);
6034}
6035
6036namespace {
6037// Describes a general N-operand vector shuffle.
6038struct GeneralShuffle {
6039 GeneralShuffle(EVT vt)
6040 : VT(vt), UnpackFromEltSize(UINT_MAX), UnpackLow(false) {}
6041 void addUndef();
6042 bool add(SDValue, unsigned);
6043 SDValue getNode(SelectionDAG &, const SDLoc &);
6044 void tryPrepareForUnpack();
6045 bool unpackWasPrepared() { return UnpackFromEltSize <= 4; }
6046 SDValue insertUnpackIfPrepared(SelectionDAG &DAG, const SDLoc &DL, SDValue Op);
6047
6048 // The operands of the shuffle.
6050
6051 // Index I is -1 if byte I of the result is undefined. Otherwise the
6052 // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand
6053 // Bytes[I] / SystemZ::VectorBytes.
6055
6056 // The type of the shuffle result.
6057 EVT VT;
6058
6059 // Holds a value of 1, 2 or 4 if a final unpack has been prepared for.
6060 unsigned UnpackFromEltSize;
6061 // True if the final unpack uses the low half.
6062 bool UnpackLow;
6063};
6064} // namespace
6065
6066// Add an extra undefined element to the shuffle.
6067void GeneralShuffle::addUndef() {
6068 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
6069 for (unsigned I = 0; I < BytesPerElement; ++I)
6070 Bytes.push_back(-1);
6071}
6072
6073// Add an extra element to the shuffle, taking it from element Elem of Op.
6074// A null Op indicates a vector input whose value will be calculated later;
6075// there is at most one such input per shuffle and it always has the same
6076// type as the result. Aborts and returns false if the source vector elements
6077// of an EXTRACT_VECTOR_ELT are smaller than the destination elements. Per
6078// LLVM they become implicitly extended, but this is rare and not optimized.
6079bool GeneralShuffle::add(SDValue Op, unsigned Elem) {
6080 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
6081
6082 // The source vector can have wider elements than the result,
6083 // either through an explicit TRUNCATE or because of type legalization.
6084 // We want the least significant part.
6085 EVT FromVT = Op.getNode() ? Op.getValueType() : VT;
6086 unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize();
6087
6088 // Return false if the source elements are smaller than their destination
6089 // elements.
6090 if (FromBytesPerElement < BytesPerElement)
6091 return false;
6092
6093 unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes +
6094 (FromBytesPerElement - BytesPerElement));
6095
6096 // Look through things like shuffles and bitcasts.
6097 while (Op.getNode()) {
6098 if (Op.getOpcode() == ISD::BITCAST)
6099 Op = Op.getOperand(0);
6100 else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) {
6101 // See whether the bytes we need come from a contiguous part of one
6102 // operand.
6104 if (!getVPermMask(Op, OpBytes))
6105 break;
6106 int NewByte;
6107 if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte))
6108 break;
6109 if (NewByte < 0) {
6110 addUndef();
6111 return true;
6112 }
6113 Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes);
6114 Byte = unsigned(NewByte) % SystemZ::VectorBytes;
6115 } else if (Op.isUndef()) {
6116 addUndef();
6117 return true;
6118 } else
6119 break;
6120 }
6121
6122 // Make sure that the source of the extraction is in Ops.
6123 unsigned OpNo = 0;
6124 for (; OpNo < Ops.size(); ++OpNo)
6125 if (Ops[OpNo] == Op)
6126 break;
6127 if (OpNo == Ops.size())
6128 Ops.push_back(Op);
6129
6130 // Add the element to Bytes.
6131 unsigned Base = OpNo * SystemZ::VectorBytes + Byte;
6132 for (unsigned I = 0; I < BytesPerElement; ++I)
6133 Bytes.push_back(Base + I);
6134
6135 return true;
6136}
6137
6138// Return SDNodes for the completed shuffle.
6139SDValue GeneralShuffle::getNode(SelectionDAG &DAG, const SDLoc &DL) {
6140 assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector");
6141
6142 if (Ops.size() == 0)
6143 return DAG.getUNDEF(VT);
6144
6145 // Use a single unpack if possible as the last operation.
6146 tryPrepareForUnpack();
6147
6148 // Make sure that there are at least two shuffle operands.
6149 if (Ops.size() == 1)
6150 Ops.push_back(DAG.getUNDEF(MVT::v16i8));
6151
6152 // Create a tree of shuffles, deferring root node until after the loop.
6153 // Try to redistribute the undefined elements of non-root nodes so that
6154 // the non-root shuffles match something like a pack or merge, then adjust
6155 // the parent node's permute vector to compensate for the new order.
6156 // Among other things, this copes with vectors like <2 x i16> that were
6157 // padded with undefined elements during type legalization.
6158 //
6159 // In the best case this redistribution will lead to the whole tree
6160 // using packs and merges. It should rarely be a loss in other cases.
6161 unsigned Stride = 1;
6162 for (; Stride * 2 < Ops.size(); Stride *= 2) {
6163 for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) {
6164 SDValue SubOps[] = { Ops[I], Ops[I + Stride] };
6165
6166 // Create a mask for just these two operands.
6168 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
6169 unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes;
6170 unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes;
6171 if (OpNo == I)
6172 NewBytes[J] = Byte;
6173 else if (OpNo == I + Stride)
6174 NewBytes[J] = SystemZ::VectorBytes + Byte;
6175 else
6176 NewBytes[J] = -1;
6177 }
6178 // See if it would be better to reorganize NewMask to avoid using VPERM.
6180 if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) {
6181 Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]);
6182 // Applying NewBytesMap to Ops[I] gets back to NewBytes.
6183 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
6184 if (NewBytes[J] >= 0) {
6185 assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
6186 "Invalid double permute");
6187 Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J];
6188 } else
6189 assert(NewBytesMap[J] < 0 && "Invalid double permute");
6190 }
6191 } else {
6192 // Just use NewBytes on the operands.
6193 Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes);
6194 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J)
6195 if (NewBytes[J] >= 0)
6196 Bytes[J] = I * SystemZ::VectorBytes + J;
6197 }
6198 }
6199 }
6200
6201 // Now we just have 2 inputs. Put the second operand in Ops[1].
6202 if (Stride > 1) {
6203 Ops[1] = Ops[Stride];
6204 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
6205 if (Bytes[I] >= int(SystemZ::VectorBytes))
6206 Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes;
6207 }
6208
6209 // Look for an instruction that can do the permute without resorting
6210 // to VPERM.
6211 unsigned OpNo0, OpNo1;
6212 SDValue Op;
6213 if (unpackWasPrepared() && Ops[1].isUndef())
6214 Op = Ops[0];
6215 else if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1))
6216 Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]);
6217 else
6218 Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes);
6219
6220 Op = insertUnpackIfPrepared(DAG, DL, Op);
6221
6222 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
6223}
6224
6225#ifndef NDEBUG
6226static void dumpBytes(const SmallVectorImpl<int> &Bytes, std::string Msg) {
6227 dbgs() << Msg.c_str() << " { ";
6228 for (unsigned I = 0; I < Bytes.size(); I++)
6229 dbgs() << Bytes[I] << " ";
6230 dbgs() << "}\n";
6231}
6232#endif
6233
6234// If the Bytes vector matches an unpack operation, prepare to do the unpack
6235// after all else by removing the zero vector and the effect of the unpack on
6236// Bytes.
6237void GeneralShuffle::tryPrepareForUnpack() {
6238 uint32_t ZeroVecOpNo = findZeroVectorIdx(&Ops[0], Ops.size());
6239 if (ZeroVecOpNo == UINT32_MAX || Ops.size() == 1)
6240 return;
6241
6242 // Only do this if removing the zero vector reduces the depth, otherwise
6243 // the critical path will increase with the final unpack.
6244 if (Ops.size() > 2 &&
6245 Log2_32_Ceil(Ops.size()) == Log2_32_Ceil(Ops.size() - 1))
6246 return;
6247
6248 // Find an unpack that would allow removing the zero vector from Ops.
6249 UnpackFromEltSize = 1;
6250 for (; UnpackFromEltSize <= 4; UnpackFromEltSize *= 2) {
6251 bool MatchUnpack = true;
6253 for (unsigned Elt = 0; Elt < SystemZ::VectorBytes; Elt++) {
6254 unsigned ToEltSize = UnpackFromEltSize * 2;
6255 bool IsZextByte = (Elt % ToEltSize) < UnpackFromEltSize;
6256 if (!IsZextByte)
6257 SrcBytes.push_back(Bytes[Elt]);
6258 if (Bytes[Elt] != -1) {
6259 unsigned OpNo = unsigned(Bytes[Elt]) / SystemZ::VectorBytes;
6260 if (IsZextByte != (OpNo == ZeroVecOpNo)) {
6261 MatchUnpack = false;
6262 break;
6263 }
6264 }
6265 }
6266 if (MatchUnpack) {
6267 if (Ops.size() == 2) {
6268 // Don't use unpack if a single source operand needs rearrangement.
6269 bool CanUseUnpackLow = true, CanUseUnpackHigh = true;
6270 for (unsigned i = 0; i < SystemZ::VectorBytes / 2; i++) {
6271 if (SrcBytes[i] == -1)
6272 continue;
6273 if (SrcBytes[i] % 16 != int(i))
6274 CanUseUnpackHigh = false;
6275 if (SrcBytes[i] % 16 != int(i + SystemZ::VectorBytes / 2))
6276 CanUseUnpackLow = false;
6277 if (!CanUseUnpackLow && !CanUseUnpackHigh) {
6278 UnpackFromEltSize = UINT_MAX;
6279 return;
6280 }
6281 }
6282 if (!CanUseUnpackHigh)
6283 UnpackLow = true;
6284 }
6285 break;
6286 }
6287 }
6288 if (UnpackFromEltSize > 4)
6289 return;
6290
6291 LLVM_DEBUG(dbgs() << "Preparing for final unpack of element size "
6292 << UnpackFromEltSize << ". Zero vector is Op#" << ZeroVecOpNo
6293 << ".\n";
6294 dumpBytes(Bytes, "Original Bytes vector:"););
6295
6296 // Apply the unpack in reverse to the Bytes array.
6297 unsigned B = 0;
6298 if (UnpackLow) {
6299 while (B < SystemZ::VectorBytes / 2)
6300 Bytes[B++] = -1;
6301 }
6302 for (unsigned Elt = 0; Elt < SystemZ::VectorBytes;) {
6303 Elt += UnpackFromEltSize;
6304 for (unsigned i = 0; i < UnpackFromEltSize; i++, Elt++, B++)
6305 Bytes[B] = Bytes[Elt];
6306 }
6307 if (!UnpackLow) {
6308 while (B < SystemZ::VectorBytes)
6309 Bytes[B++] = -1;
6310 }
6311
6312 // Remove the zero vector from Ops
6313 Ops.erase(&Ops[ZeroVecOpNo]);
6314 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
6315 if (Bytes[I] >= 0) {
6316 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
6317 if (OpNo > ZeroVecOpNo)
6318 Bytes[I] -= SystemZ::VectorBytes;
6319 }
6320
6321 LLVM_DEBUG(dumpBytes(Bytes, "Resulting Bytes vector, zero vector removed:");
6322 dbgs() << "\n";);
6323}
6324
6325SDValue GeneralShuffle::insertUnpackIfPrepared(SelectionDAG &DAG,
6326 const SDLoc &DL,
6327 SDValue Op) {
6328 if (!unpackWasPrepared())
6329 return Op;
6330 unsigned InBits = UnpackFromEltSize * 8;
6331 EVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBits),
6332 SystemZ::VectorBits / InBits);
6333 SDValue PackedOp = DAG.getNode(ISD::BITCAST, DL, InVT, Op);
6334 unsigned OutBits = InBits * 2;
6335 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(OutBits),
6336 SystemZ::VectorBits / OutBits);
6337 return DAG.getNode(UnpackLow ? SystemZISD::UNPACKL_LOW
6338 : SystemZISD::UNPACKL_HIGH,
6339 DL, OutVT, PackedOp);
6340}
6341
6342// Return true if the given BUILD_VECTOR is a scalar-to-vector conversion.
6344 for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I)
6345 if (!Op.getOperand(I).isUndef())
6346 return false;
6347 return true;
6348}
6349
6350// Return a vector of type VT that contains Value in the first element.
6351// The other elements don't matter.
6353 SDValue Value) {
6354 // If we have a constant, replicate it to all elements and let the
6355 // BUILD_VECTOR lowering take care of it.
6356 if (Value.getOpcode() == ISD::Constant ||
6357 Value.getOpcode() == ISD::ConstantFP) {
6359 return DAG.getBuildVector(VT, DL, Ops);
6360 }
6361 if (Value.isUndef())
6362 return DAG.getUNDEF(VT);
6363 return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
6364}
6365
6366// Return a vector of type VT in which Op0 is in element 0 and Op1 is in
6367// element 1. Used for cases in which replication is cheap.
6369 SDValue Op0, SDValue Op1) {
6370 if (Op0.isUndef()) {
6371 if (Op1.isUndef())
6372 return DAG.getUNDEF(VT);
6373 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1);
6374 }
6375 if (Op1.isUndef())
6376 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0);
6377 return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT,
6378 buildScalarToVector(DAG, DL, VT, Op0),
6379 buildScalarToVector(DAG, DL, VT, Op1));
6380}
6381
6382// Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64
6383// vector for them.
6385 SDValue Op1) {
6386 if (Op0.isUndef() && Op1.isUndef())
6387 return DAG.getUNDEF(MVT::v2i64);
6388 // If one of the two inputs is undefined then replicate the other one,
6389 // in order to avoid using another register unnecessarily.
6390 if (Op0.isUndef())
6391 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
6392 else if (Op1.isUndef())
6393 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
6394 else {
6395 Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
6396 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
6397 }
6398 return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1);
6399}
6400
6401// If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually
6402// better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for
6403// the non-EXTRACT_VECTOR_ELT elements. See if the given BUILD_VECTOR
6404// would benefit from this representation and return it if so.
6406 BuildVectorSDNode *BVN) {
6407 EVT VT = BVN->getValueType(0);
6408 unsigned NumElements = VT.getVectorNumElements();
6409
6410 // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation
6411 // on byte vectors. If there are non-EXTRACT_VECTOR_ELT elements that still
6412 // need a BUILD_VECTOR, add an additional placeholder operand for that
6413 // BUILD_VECTOR and store its operands in ResidueOps.
6414 GeneralShuffle GS(VT);
6416 bool FoundOne = false;
6417 for (unsigned I = 0; I < NumElements; ++I) {
6418 SDValue Op = BVN->getOperand(I);
6419 if (Op.getOpcode() == ISD::TRUNCATE)
6420 Op = Op.getOperand(0);
6421 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6422 Op.getOperand(1).getOpcode() == ISD::Constant) {
6423 unsigned Elem = Op.getConstantOperandVal(1);
6424 if (!GS.add(Op.getOperand(0), Elem))
6425 return SDValue();
6426 FoundOne = true;
6427 } else if (Op.isUndef()) {
6428 GS.addUndef();
6429 } else {
6430 if (!GS.add(SDValue(), ResidueOps.size()))
6431 return SDValue();
6432 ResidueOps.push_back(BVN->getOperand(I));
6433 }
6434 }
6435
6436 // Nothing to do if there are no EXTRACT_VECTOR_ELTs.
6437 if (!FoundOne)
6438 return SDValue();
6439
6440 // Create the BUILD_VECTOR for the remaining elements, if any.
6441 if (!ResidueOps.empty()) {
6442 while (ResidueOps.size() < NumElements)
6443 ResidueOps.push_back(DAG.getUNDEF(ResidueOps[0].getValueType()));
6444 for (auto &Op : GS.Ops) {
6445 if (!Op.getNode()) {
6446 Op = DAG.getBuildVector(VT, SDLoc(BVN), ResidueOps);
6447 break;
6448 }
6449 }
6450 }
6451 return GS.getNode(DAG, SDLoc(BVN));
6452}
6453
6454bool SystemZTargetLowering::isVectorElementLoad(SDValue Op) const {
6455 if (Op.getOpcode() == ISD::LOAD && cast<LoadSDNode>(Op)->isUnindexed())
6456 return true;
6457 if (auto *AL = dyn_cast<AtomicSDNode>(Op))
6458 if (AL->getOpcode() == ISD::ATOMIC_LOAD)
6459 return true;
6460 if (Subtarget.hasVectorEnhancements2() && Op.getOpcode() == SystemZISD::LRV)
6461 return true;
6462 return false;
6463}
6464
6466 unsigned MergedBits, EVT VT, SDValue Op0,
6467 SDValue Op1) {
6468 MVT IntVecVT = MVT::getVectorVT(MVT::getIntegerVT(MergedBits),
6469 SystemZ::VectorBits / MergedBits);
6470 assert(VT.getSizeInBits() == 128 && IntVecVT.getSizeInBits() == 128 &&
6471 "Handling full vectors only.");
6472 Op0 = DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0);
6473 Op1 = DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op1);
6474 SDValue Op = DAG.getNode(SystemZISD::MERGE_HIGH, DL, IntVecVT, Op0, Op1);
6475 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
6476}
6477
6479 EVT VT, SmallVectorImpl<SDValue> &Elems,
6480 unsigned Pos) {
6481 SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[Pos + 0], Elems[Pos + 1]);
6482 SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[Pos + 2], Elems[Pos + 3]);
6483 // Avoid unnecessary undefs by reusing the other operand.
6484 if (Op01.isUndef()) {
6485 if (Op23.isUndef())
6486 return Op01;
6487 Op01 = Op23;
6488 } else if (Op23.isUndef())
6489 Op23 = Op01;
6490 // Merging identical replications is a no-op.
6491 if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23)
6492 return Op01;
6493 unsigned MergedBits = VT.getSimpleVT().getScalarSizeInBits() * 2;
6494 return mergeHighParts(DAG, DL, MergedBits, VT, Op01, Op23);
6495}
6496
6497// Combine GPR scalar values Elems into a vector of type VT.
6498SDValue
6499SystemZTargetLowering::buildVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
6500 SmallVectorImpl<SDValue> &Elems) const {
6501 // See whether there is a single replicated value.
6502 SDValue Single;
6503 unsigned int NumElements = Elems.size();
6504 unsigned int Count = 0;
6505 for (auto Elem : Elems) {
6506 if (!Elem.isUndef()) {
6507 if (!Single.getNode())
6508 Single = Elem;
6509 else if (Elem != Single) {
6510 Single = SDValue();
6511 break;
6512 }
6513 Count += 1;
6514 }
6515 }
6516 // There are three cases here:
6517 //
6518 // - if the only defined element is a loaded one, the best sequence
6519 // is a replicating load.
6520 //
6521 // - otherwise, if the only defined element is an i64 value, we will
6522 // end up with the same VLVGP sequence regardless of whether we short-cut
6523 // for replication or fall through to the later code.
6524 //
6525 // - otherwise, if the only defined element is an i32 or smaller value,
6526 // we would need 2 instructions to replicate it: VLVGP followed by VREPx.
6527 // This is only a win if the single defined element is used more than once.
6528 // In other cases we're better off using a single VLVGx.
6529 if (Single.getNode() && (Count > 1 || isVectorElementLoad(Single)))
6530 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single);
6531
6532 // If all elements are loads, use VLREP/VLEs (below).
6533 bool AllLoads = true;
6534 for (auto Elem : Elems)
6535 if (!isVectorElementLoad(Elem)) {
6536 AllLoads = false;
6537 break;
6538 }
6539
6540 // The best way of building a v2i64 from two i64s is to use VLVGP.
6541 if (VT == MVT::v2i64 && !AllLoads)
6542 return joinDwords(DAG, DL, Elems[0], Elems[1]);
6543
6544 // Use a 64-bit merge high to combine two doubles.
6545 if (VT == MVT::v2f64 && !AllLoads)
6546 return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
6547
6548 // Build v4f32 values directly from the FPRs:
6549 //
6550 // <Axxx> <Bxxx> <Cxxxx> <Dxxx>
6551 // V V VMRHF
6552 // <ABxx> <CDxx>
6553 // V VMRHG
6554 // <ABCD>
6555 if (VT == MVT::v4f32 && !AllLoads)
6556 return buildFPVecFromScalars4(DAG, DL, VT, Elems, 0);
6557
6558 // Same for v8f16.
6559 if (VT == MVT::v8f16 && !AllLoads) {
6560 SDValue Op0123 = buildFPVecFromScalars4(DAG, DL, VT, Elems, 0);
6561 SDValue Op4567 = buildFPVecFromScalars4(DAG, DL, VT, Elems, 4);
6562 // Avoid unnecessary undefs by reusing the other operand.
6563 if (Op0123.isUndef())
6564 Op0123 = Op4567;
6565 else if (Op4567.isUndef())
6566 Op4567 = Op0123;
6567 // Merging identical replications is a no-op.
6568 if (Op0123.getOpcode() == SystemZISD::REPLICATE && Op0123 == Op4567)
6569 return Op0123;
6570 return mergeHighParts(DAG, DL, 64, VT, Op0123, Op4567);
6571 }
6572
6573 // Collect the constant terms.
6576
6577 unsigned NumConstants = 0;
6578 for (unsigned I = 0; I < NumElements; ++I) {
6579 SDValue Elem = Elems[I];
6580 if (Elem.getOpcode() == ISD::Constant ||
6581 Elem.getOpcode() == ISD::ConstantFP) {
6582 NumConstants += 1;
6583 Constants[I] = Elem;
6584 Done[I] = true;
6585 }
6586 }
6587 // If there was at least one constant, fill in the other elements of
6588 // Constants with undefs to get a full vector constant and use that
6589 // as the starting point.
6590 SDValue Result;
6591 SDValue ReplicatedVal;
6592 if (NumConstants > 0) {
6593 for (unsigned I = 0; I < NumElements; ++I)
6594 if (!Constants[I].getNode())
6595 Constants[I] = DAG.getUNDEF(Elems[I].getValueType());
6596 Result = DAG.getBuildVector(VT, DL, Constants);
6597 } else {
6598 // Otherwise try to use VLREP or VLVGP to start the sequence in order to
6599 // avoid a false dependency on any previous contents of the vector
6600 // register.
6601
6602 // Use a VLREP if at least one element is a load. Make sure to replicate
6603 // the load with the most elements having its value.
6604 std::map<const SDNode*, unsigned> UseCounts;
6605 SDNode *LoadMaxUses = nullptr;
6606 for (unsigned I = 0; I < NumElements; ++I)
6607 if (isVectorElementLoad(Elems[I])) {
6608 SDNode *Ld = Elems[I].getNode();
6609 unsigned Count = ++UseCounts[Ld];
6610 if (LoadMaxUses == nullptr || UseCounts[LoadMaxUses] < Count)
6611 LoadMaxUses = Ld;
6612 }
6613 if (LoadMaxUses != nullptr) {
6614 ReplicatedVal = SDValue(LoadMaxUses, 0);
6615 Result = DAG.getNode(SystemZISD::REPLICATE, DL, VT, ReplicatedVal);
6616 } else {
6617 // Try to use VLVGP.
6618 unsigned I1 = NumElements / 2 - 1;
6619 unsigned I2 = NumElements - 1;
6620 bool Def1 = !Elems[I1].isUndef();
6621 bool Def2 = !Elems[I2].isUndef();
6622 if (Def1 || Def2) {
6623 SDValue Elem1 = Elems[Def1 ? I1 : I2];
6624 SDValue Elem2 = Elems[Def2 ? I2 : I1];
6625 Result = DAG.getNode(ISD::BITCAST, DL, VT,
6626 joinDwords(DAG, DL, Elem1, Elem2));
6627 Done[I1] = true;
6628 Done[I2] = true;
6629 } else
6630 Result = DAG.getUNDEF(VT);
6631 }
6632 }
6633
6634 // Use VLVGx to insert the other elements.
6635 for (unsigned I = 0; I < NumElements; ++I)
6636 if (!Done[I] && !Elems[I].isUndef() && Elems[I] != ReplicatedVal)
6637 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I],
6638 DAG.getConstant(I, DL, MVT::i32));
6639 return Result;
6640}
6641
6642SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op,
6643 SelectionDAG &DAG) const {
6644 auto *BVN = cast<BuildVectorSDNode>(Op.getNode());
6645 SDLoc DL(Op);
6646 EVT VT = Op.getValueType();
6647
6648 if (BVN->isConstant()) {
6649 if (SystemZVectorConstantInfo(BVN).isVectorConstantLegal(Subtarget))
6650 return Op;
6651
6652 // Fall back to loading it from memory.
6653 return SDValue();
6654 }
6655
6656 // See if we should use shuffles to construct the vector from other vectors.
6657 if (SDValue Res = tryBuildVectorShuffle(DAG, BVN))
6658 return Res;
6659
6660 // Detect SCALAR_TO_VECTOR conversions.
6662 return buildScalarToVector(DAG, DL, VT, Op.getOperand(0));
6663
6664 // Otherwise use buildVector to build the vector up from GPRs.
6665 unsigned NumElements = Op.getNumOperands();
6667 for (unsigned I = 0; I < NumElements; ++I)
6668 Ops[I] = Op.getOperand(I);
6669 return buildVector(DAG, DL, VT, Ops);
6670}
6671
6672SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
6673 SelectionDAG &DAG) const {
6674 auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode());
6675 SDLoc DL(Op);
6676 EVT VT = Op.getValueType();
6677 unsigned NumElements = VT.getVectorNumElements();
6678
6679 if (VSN->isSplat()) {
6680 SDValue Op0 = Op.getOperand(0);
6681 unsigned Index = VSN->getSplatIndex();
6682 assert(Index < VT.getVectorNumElements() &&
6683 "Splat index should be defined and in first operand");
6684 // See whether the value we're splatting is directly available as a scalar.
6685 if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
6687 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index));
6688 // Otherwise keep it as a vector-to-vector operation.
6689 return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0),
6690 DAG.getTargetConstant(Index, DL, MVT::i32));
6691 }
6692
6693 GeneralShuffle GS(VT);
6694 for (unsigned I = 0; I < NumElements; ++I) {
6695 int Elt = VSN->getMaskElt(I);
6696 if (Elt < 0)
6697 GS.addUndef();
6698 else if (!GS.add(Op.getOperand(unsigned(Elt) / NumElements),
6699 unsigned(Elt) % NumElements))
6700 return SDValue();
6701 }
6702 return GS.getNode(DAG, SDLoc(VSN));
6703}
6704
6705SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
6706 SelectionDAG &DAG) const {
6707 SDLoc DL(Op);
6708 // Just insert the scalar into element 0 of an undefined vector.
6709 return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL,
6710 Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
6711 Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32));
6712}
6713
6714// Shift the lower 2 bytes of Op to the left in order to insert into the
6715// upper 2 bytes of the FP register.
6717 assert(Op.getSimpleValueType() == MVT::i64 &&
6718 "Expexted to convert i64 to f16.");
6719 SDLoc DL(Op);
6720 SDValue Shft = DAG.getNode(ISD::SHL, DL, MVT::i64, Op,
6721 DAG.getConstant(48, DL, MVT::i64));
6722 SDValue BCast = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Shft);
6723 SDValue F16Val =
6724 DAG.getTargetExtractSubreg(SystemZ::subreg_h16, DL, MVT::f16, BCast);
6725 return F16Val;
6726}
6727
6728// Extract Op into GPR and shift the 2 f16 bytes to the right.
6730 assert(Op.getSimpleValueType() == MVT::f16 &&
6731 "Expected to convert f16 to i64.");
6732 SDNode *U32 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
6733 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h16, DL, MVT::f64,
6734 SDValue(U32, 0), Op);
6735 SDValue BCast = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
6736 SDValue Shft = DAG.getNode(ISD::SRL, DL, MVT::i64, BCast,
6737 DAG.getConstant(48, DL, MVT::i32));
6738 return Shft;
6739}
6740
6741SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
6742 SelectionDAG &DAG) const {
6743 // Handle insertions of floating-point values.
6744 SDLoc DL(Op);
6745 SDValue Op0 = Op.getOperand(0);
6746 SDValue Op1 = Op.getOperand(1);
6747 SDValue Op2 = Op.getOperand(2);
6748 EVT VT = Op.getValueType();
6749
6750 // Insertions into constant indices of a v2f64 can be done using VPDI.
6751 // However, if the inserted value is a bitcast or a constant then it's
6752 // better to use GPRs, as below.
6753 if (VT == MVT::v2f64 &&
6754 Op1.getOpcode() != ISD::BITCAST &&
6755 Op1.getOpcode() != ISD::ConstantFP &&
6756 Op2.getOpcode() == ISD::Constant) {
6757 uint64_t Index = Op2->getAsZExtVal();
6758 unsigned Mask = VT.getVectorNumElements() - 1;
6759 if (Index <= Mask)
6760 return Op;
6761 }
6762
6763 // Otherwise bitcast to the equivalent integer form and insert via a GPR.
6764 MVT IntVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
6765 MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements());
6766 SDValue IntOp1 =
6767 VT == MVT::v8f16
6768 ? DAG.getZExtOrTrunc(convertFromF16(Op1, DL, DAG), DL, MVT::i32)
6769 : DAG.getNode(ISD::BITCAST, DL, IntVT, Op1);
6770 SDValue Res =
6771 DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT,
6772 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), IntOp1, Op2);
6773 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
6774}
6775
6776SDValue
6777SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
6778 SelectionDAG &DAG) const {
6779 // Handle extractions of floating-point values.
6780 SDLoc DL(Op);
6781 SDValue Op0 = Op.getOperand(0);
6782 SDValue Op1 = Op.getOperand(1);
6783 EVT VT = Op.getValueType();
6784 EVT VecVT = Op0.getValueType();
6785
6786 // Extractions of constant indices can be done directly.
6787 if (auto *CIndexN = dyn_cast<ConstantSDNode>(Op1)) {
6788 uint64_t Index = CIndexN->getZExtValue();
6789 unsigned Mask = VecVT.getVectorNumElements() - 1;
6790 if (Index <= Mask)
6791 return Op;
6792 }
6793
6794 // Otherwise bitcast to the equivalent integer form and extract via a GPR.
6795 MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
6796 MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements());
6797 MVT ExtrVT = IntVT == MVT::i16 ? MVT::i32 : IntVT;
6798 SDValue Extr = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrVT,
6799 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1);
6800 if (VT == MVT::f16)
6801 return convertToF16(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Extr), DAG);
6802 return DAG.getNode(ISD::BITCAST, DL, VT, Extr);
6803}
6804
6805SDValue SystemZTargetLowering::
6806lowerSIGN_EXTEND_VECTOR_INREG(SDValue Op, SelectionDAG &DAG) const {
6807 SDValue PackedOp = Op.getOperand(0);
6808 EVT OutVT = Op.getValueType();
6809 EVT InVT = PackedOp.getValueType();
6810 unsigned ToBits = OutVT.getScalarSizeInBits();
6811 unsigned FromBits = InVT.getScalarSizeInBits();
6812 unsigned StartOffset = 0;
6813
6814 // If the input is a VECTOR_SHUFFLE, there are a number of important
6815 // cases where we can directly implement the sign-extension of the
6816 // original input lanes of the shuffle.
6817 if (PackedOp.getOpcode() == ISD::VECTOR_SHUFFLE) {
6818 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(PackedOp.getNode());
6819 ArrayRef<int> ShuffleMask = SVN->getMask();
6820 int OutNumElts = OutVT.getVectorNumElements();
6821
6822 // Recognize the special case where the sign-extension can be done
6823 // by the VSEG instruction. Handled via the default expander.
6824 if (ToBits == 64 && OutNumElts == 2) {
6825 int NumElem = ToBits / FromBits;
6826 if (ShuffleMask[0] == NumElem - 1 && ShuffleMask[1] == 2 * NumElem - 1)
6827 return SDValue();
6828 }
6829
6830 // Recognize the special case where we can fold the shuffle by
6831 // replacing some of the UNPACK_HIGH with UNPACK_LOW.
6832 int StartOffsetCandidate = -1;
6833 for (int Elt = 0; Elt < OutNumElts; Elt++) {
6834 if (ShuffleMask[Elt] == -1)
6835 continue;
6836 if (ShuffleMask[Elt] % OutNumElts == Elt) {
6837 if (StartOffsetCandidate == -1)
6838 StartOffsetCandidate = ShuffleMask[Elt] - Elt;
6839 if (StartOffsetCandidate == ShuffleMask[Elt] - Elt)
6840 continue;
6841 }
6842 StartOffsetCandidate = -1;
6843 break;
6844 }
6845 if (StartOffsetCandidate != -1) {
6846 StartOffset = StartOffsetCandidate;
6847 PackedOp = PackedOp.getOperand(0);
6848 }
6849 }
6850
6851 do {
6852 FromBits *= 2;
6853 unsigned OutNumElts = SystemZ::VectorBits / FromBits;
6854 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(FromBits), OutNumElts);
6855 unsigned Opcode = SystemZISD::UNPACK_HIGH;
6856 if (StartOffset >= OutNumElts) {
6857 Opcode = SystemZISD::UNPACK_LOW;
6858 StartOffset -= OutNumElts;
6859 }
6860 PackedOp = DAG.getNode(Opcode, SDLoc(PackedOp), OutVT, PackedOp);
6861 } while (FromBits != ToBits);
6862 return PackedOp;
6863}
6864
6865// Lower a ZERO_EXTEND_VECTOR_INREG to a vector shuffle with a zero vector.
6866SDValue SystemZTargetLowering::
6867lowerZERO_EXTEND_VECTOR_INREG(SDValue Op, SelectionDAG &DAG) const {
6868 SDValue PackedOp = Op.getOperand(0);
6869 SDLoc DL(Op);
6870 EVT OutVT = Op.getValueType();
6871 EVT InVT = PackedOp.getValueType();
6872 unsigned InNumElts = InVT.getVectorNumElements();
6873 unsigned OutNumElts = OutVT.getVectorNumElements();
6874 unsigned NumInPerOut = InNumElts / OutNumElts;
6875
6876 SDValue ZeroVec =
6877 DAG.getSplatVector(InVT, DL, DAG.getConstant(0, DL, InVT.getScalarType()));
6878
6879 SmallVector<int, 16> Mask(InNumElts);
6880 unsigned ZeroVecElt = InNumElts;
6881 for (unsigned PackedElt = 0; PackedElt < OutNumElts; PackedElt++) {
6882 unsigned MaskElt = PackedElt * NumInPerOut;
6883 unsigned End = MaskElt + NumInPerOut - 1;
6884 for (; MaskElt < End; MaskElt++)
6885 Mask[MaskElt] = ZeroVecElt++;
6886 Mask[MaskElt] = PackedElt;
6887 }
6888 SDValue Shuf = DAG.getVectorShuffle(InVT, DL, PackedOp, ZeroVec, Mask);
6889 return DAG.getNode(ISD::BITCAST, DL, OutVT, Shuf);
6890}
6891
6892SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG,
6893 unsigned ByScalar) const {
6894 // Look for cases where a vector shift can use the *_BY_SCALAR form.
6895 SDValue Op0 = Op.getOperand(0);
6896 SDValue Op1 = Op.getOperand(1);
6897 SDLoc DL(Op);
6898 EVT VT = Op.getValueType();
6899 unsigned ElemBitSize = VT.getScalarSizeInBits();
6900
6901 // See whether the shift vector is a splat represented as BUILD_VECTOR.
6902 if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) {
6903 APInt SplatBits, SplatUndef;
6904 unsigned SplatBitSize;
6905 bool HasAnyUndefs;
6906 // Check for constant splats. Use ElemBitSize as the minimum element
6907 // width and reject splats that need wider elements.
6908 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6909 ElemBitSize, true) &&
6910 SplatBitSize == ElemBitSize) {
6911 SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff,
6912 DL, MVT::i32);
6913 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
6914 }
6915 // Check for variable splats.
6916 BitVector UndefElements;
6917 SDValue Splat = BVN->getSplatValue(&UndefElements);
6918 if (Splat) {
6919 // Since i32 is the smallest legal type, we either need a no-op
6920 // or a truncation.
6921 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat);
6922 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
6923 }
6924 }
6925
6926 // See whether the shift vector is a splat represented as SHUFFLE_VECTOR,
6927 // and the shift amount is directly available in a GPR.
6928 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) {
6929 if (VSN->isSplat()) {
6930 SDValue VSNOp0 = VSN->getOperand(0);
6931 unsigned Index = VSN->getSplatIndex();
6932 assert(Index < VT.getVectorNumElements() &&
6933 "Splat index should be defined and in first operand");
6934 if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
6935 VSNOp0.getOpcode() == ISD::BUILD_VECTOR) {
6936 // Since i32 is the smallest legal type, we either need a no-op
6937 // or a truncation.
6938 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
6939 VSNOp0.getOperand(Index));
6940 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
6941 }
6942 }
6943 }
6944
6945 // Otherwise just treat the current form as legal.
6946 return Op;
6947}
6948
6949SDValue SystemZTargetLowering::lowerFSHL(SDValue Op, SelectionDAG &DAG) const {
6950 SDLoc DL(Op);
6951
6952 // i128 FSHL with a constant amount that is a multiple of 8 can be
6953 // implemented via VECTOR_SHUFFLE. If we have the vector-enhancements-2
6954 // facility, FSHL with a constant amount less than 8 can be implemented
6955 // via SHL_DOUBLE_BIT, and FSHL with other constant amounts by a
6956 // combination of the two.
6957 if (auto *ShiftAmtNode = dyn_cast<ConstantSDNode>(Op.getOperand(2))) {
6958 uint64_t ShiftAmt = ShiftAmtNode->getZExtValue() & 127;
6959 if ((ShiftAmt & 7) == 0 || Subtarget.hasVectorEnhancements2()) {
6960 SDValue Op0 = DAG.getBitcast(MVT::v16i8, Op.getOperand(0));
6961 SDValue Op1 = DAG.getBitcast(MVT::v16i8, Op.getOperand(1));
6962 if (ShiftAmt > 120) {
6963 // For N in 121..128, fshl N == fshr (128 - N), and for 1 <= N < 8
6964 // SHR_DOUBLE_BIT emits fewer instructions.
6965 SDValue Val =
6966 DAG.getNode(SystemZISD::SHR_DOUBLE_BIT, DL, MVT::v16i8, Op0, Op1,
6967 DAG.getTargetConstant(128 - ShiftAmt, DL, MVT::i32));
6968 return DAG.getBitcast(MVT::i128, Val);
6969 }
6970 SmallVector<int, 16> Mask(16);
6971 for (unsigned Elt = 0; Elt < 16; Elt++)
6972 Mask[Elt] = (ShiftAmt >> 3) + Elt;
6973 SDValue Shuf1 = DAG.getVectorShuffle(MVT::v16i8, DL, Op0, Op1, Mask);
6974 if ((ShiftAmt & 7) == 0)
6975 return DAG.getBitcast(MVT::i128, Shuf1);
6976 SDValue Shuf2 = DAG.getVectorShuffle(MVT::v16i8, DL, Op1, Op1, Mask);
6977 SDValue Val =
6978 DAG.getNode(SystemZISD::SHL_DOUBLE_BIT, DL, MVT::v16i8, Shuf1, Shuf2,
6979 DAG.getTargetConstant(ShiftAmt & 7, DL, MVT::i32));
6980 return DAG.getBitcast(MVT::i128, Val);
6981 }
6982 }
6983
6984 return SDValue();
6985}
6986
6987SDValue SystemZTargetLowering::lowerFSHR(SDValue Op, SelectionDAG &DAG) const {
6988 SDLoc DL(Op);
6989
6990 // i128 FSHR with a constant amount that is a multiple of 8 can be
6991 // implemented via VECTOR_SHUFFLE. If we have the vector-enhancements-2
6992 // facility, FSHR with a constant amount less than 8 can be implemented
6993 // via SHR_DOUBLE_BIT, and FSHR with other constant amounts by a
6994 // combination of the two.
6995 if (auto *ShiftAmtNode = dyn_cast<ConstantSDNode>(Op.getOperand(2))) {
6996 uint64_t ShiftAmt = ShiftAmtNode->getZExtValue() & 127;
6997 if ((ShiftAmt & 7) == 0 || Subtarget.hasVectorEnhancements2()) {
6998 SDValue Op0 = DAG.getBitcast(MVT::v16i8, Op.getOperand(0));
6999 SDValue Op1 = DAG.getBitcast(MVT::v16i8, Op.getOperand(1));
7000 if (ShiftAmt > 120) {
7001 // For N in 121..128, fshr N == fshl (128 - N), and for 1 <= N < 8
7002 // SHL_DOUBLE_BIT emits fewer instructions.
7003 SDValue Val =
7004 DAG.getNode(SystemZISD::SHL_DOUBLE_BIT, DL, MVT::v16i8, Op0, Op1,
7005 DAG.getTargetConstant(128 - ShiftAmt, DL, MVT::i32));
7006 return DAG.getBitcast(MVT::i128, Val);
7007 }
7008 SmallVector<int, 16> Mask(16);
7009 for (unsigned Elt = 0; Elt < 16; Elt++)
7010 Mask[Elt] = 16 - (ShiftAmt >> 3) + Elt;
7011 SDValue Shuf1 = DAG.getVectorShuffle(MVT::v16i8, DL, Op0, Op1, Mask);
7012 if ((ShiftAmt & 7) == 0)
7013 return DAG.getBitcast(MVT::i128, Shuf1);
7014 SDValue Shuf2 = DAG.getVectorShuffle(MVT::v16i8, DL, Op0, Op0, Mask);
7015 SDValue Val =
7016 DAG.getNode(SystemZISD::SHR_DOUBLE_BIT, DL, MVT::v16i8, Shuf2, Shuf1,
7017 DAG.getTargetConstant(ShiftAmt & 7, DL, MVT::i32));
7018 return DAG.getBitcast(MVT::i128, Val);
7019 }
7020 }
7021
7022 return SDValue();
7023}
7024
7026 SDLoc DL(Op);
7027 SDValue Src = Op.getOperand(0);
7028 MVT DstVT = Op.getSimpleValueType();
7029
7031 unsigned SrcAS = N->getSrcAddressSpace();
7032
7033 assert(SrcAS != N->getDestAddressSpace() &&
7034 "addrspacecast must be between different address spaces");
7035
7036 // addrspacecast [0 <- 1] : Assinging a ptr32 value to a 64-bit pointer.
7037 // addrspacecast [1 <- 0] : Assigining a 64-bit pointer to a ptr32 value.
7038 if (SrcAS == SYSTEMZAS::PTR32 && DstVT == MVT::i64) {
7039 Op = DAG.getNode(ISD::AND, DL, MVT::i32, Src,
7040 DAG.getConstant(0x7fffffff, DL, MVT::i32));
7041 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, DstVT, Op);
7042 } else if (DstVT == MVT::i32) {
7043 Op = DAG.getNode(ISD::TRUNCATE, DL, DstVT, Src);
7044 Op = DAG.getNode(ISD::AND, DL, MVT::i32, Op,
7045 DAG.getConstant(0x7fffffff, DL, MVT::i32));
7046 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, DstVT, Op);
7047 } else {
7048 report_fatal_error("Bad address space in addrspacecast");
7049 }
7050 return Op;
7051}
7052
7053SDValue SystemZTargetLowering::lowerFP_EXTEND(SDValue Op,
7054 SelectionDAG &DAG) const {
7055 SDValue In = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
7056 if (In.getSimpleValueType() != MVT::f16)
7057 return Op; // Legal
7058 return SDValue(); // Let legalizer emit the libcall.
7059}
7060
7062 MVT VT, SDValue Arg, SDLoc DL,
7063 SDValue Chain, bool IsStrict) const {
7064 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected request for libcall!");
7065 MakeLibCallOptions CallOptions;
7066 SDValue Result;
7067 std::tie(Result, Chain) =
7068 makeLibCall(DAG, LC, VT, Arg, CallOptions, DL, Chain);
7069 return IsStrict ? DAG.getMergeValues({Result, Chain}, DL) : Result;
7070}
7071
7072SDValue SystemZTargetLowering::lower_FP_TO_INT(SDValue Op,
7073 SelectionDAG &DAG) const {
7074 bool IsSigned = (Op->getOpcode() == ISD::FP_TO_SINT ||
7075 Op->getOpcode() == ISD::STRICT_FP_TO_SINT);
7076 bool IsStrict = Op->isStrictFPOpcode();
7077 SDLoc DL(Op);
7078 MVT VT = Op.getSimpleValueType();
7079 SDValue InOp = Op.getOperand(IsStrict ? 1 : 0);
7080 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
7081 EVT InVT = InOp.getValueType();
7082
7083 // FP to unsigned is not directly supported on z10. Promoting an i32
7084 // result to (signed) i64 doesn't generate an inexact condition (fp
7085 // exception) for values that are outside the i32 range but in the i64
7086 // range, so use the default expansion.
7087 if (!Subtarget.hasFPExtension() && !IsSigned)
7088 // Expand i32/i64. F16 values will be recognized to fit and extended.
7089 return SDValue();
7090
7091 // Conversion from f16 is done via f32.
7092 if (InOp.getSimpleValueType() == MVT::f16) {
7094 LowerOperationWrapper(Op.getNode(), Results, DAG);
7095 return DAG.getMergeValues(Results, DL);
7096 }
7097
7098 if (VT == MVT::i128) {
7099 RTLIB::Libcall LC =
7100 IsSigned ? RTLIB::getFPTOSINT(InVT, VT) : RTLIB::getFPTOUINT(InVT, VT);
7101 return useLibCall(DAG, LC, VT, InOp, DL, Chain, IsStrict);
7102 }
7103
7104 return Op; // Legal
7105}
7106
7107SDValue SystemZTargetLowering::lower_INT_TO_FP(SDValue Op,
7108 SelectionDAG &DAG) const {
7109 bool IsSigned = (Op->getOpcode() == ISD::SINT_TO_FP ||
7110 Op->getOpcode() == ISD::STRICT_SINT_TO_FP);
7111 bool IsStrict = Op->isStrictFPOpcode();
7112 SDLoc DL(Op);
7113 MVT VT = Op.getSimpleValueType();
7114 SDValue InOp = Op.getOperand(IsStrict ? 1 : 0);
7115 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
7116 EVT InVT = InOp.getValueType();
7117
7118 // Conversion to f16 is done via f32.
7119 if (VT == MVT::f16) {
7121 LowerOperationWrapper(Op.getNode(), Results, DAG);
7122 return DAG.getMergeValues(Results, DL);
7123 }
7124
7125 // Unsigned to fp is not directly supported on z10.
7126 if (!Subtarget.hasFPExtension() && !IsSigned)
7127 return SDValue(); // Expand i64.
7128
7129 if (InVT == MVT::i128) {
7130 RTLIB::Libcall LC =
7131 IsSigned ? RTLIB::getSINTTOFP(InVT, VT) : RTLIB::getUINTTOFP(InVT, VT);
7132 return useLibCall(DAG, LC, VT, InOp, DL, Chain, IsStrict);
7133 }
7134
7135 return Op; // Legal
7136}
7137
7138// Lower an f16 LOAD in case of no vector support.
7139SDValue SystemZTargetLowering::lowerLoadF16(SDValue Op,
7140 SelectionDAG &DAG) const {
7141 EVT RegVT = Op.getValueType();
7142 assert(RegVT == MVT::f16 && "Expected to lower an f16 load.");
7143 (void)RegVT;
7144
7145 // Load as integer.
7146 SDLoc DL(Op);
7147 SDValue NewLd;
7148 if (auto *AtomicLd = dyn_cast<AtomicSDNode>(Op.getNode())) {
7149 assert(EVT(RegVT) == AtomicLd->getMemoryVT() && "Unhandled f16 load");
7150 NewLd = DAG.getAtomicLoad(ISD::EXTLOAD, DL, MVT::i16, MVT::i64,
7151 AtomicLd->getChain(), AtomicLd->getBasePtr(),
7152 AtomicLd->getMemOperand());
7153 } else {
7154 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
7155 assert(EVT(RegVT) == Ld->getMemoryVT() && "Unhandled f16 load");
7156 NewLd = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i64, Ld->getChain(),
7157 Ld->getBasePtr(), Ld->getPointerInfo(), MVT::i16,
7158 Ld->getBaseAlign(), Ld->getMemOperand()->getFlags());
7159 }
7160 SDValue F16Val = convertToF16(NewLd, DAG);
7161 return DAG.getMergeValues({F16Val, NewLd.getValue(1)}, DL);
7162}
7163
7164// Lower an f16 STORE in case of no vector support.
7165SDValue SystemZTargetLowering::lowerStoreF16(SDValue Op,
7166 SelectionDAG &DAG) const {
7167 SDLoc DL(Op);
7168 SDValue Shft = convertFromF16(Op->getOperand(1), DL, DAG);
7169
7170 if (auto *AtomicSt = dyn_cast<AtomicSDNode>(Op.getNode()))
7171 return DAG.getAtomic(ISD::ATOMIC_STORE, DL, MVT::i16, AtomicSt->getChain(),
7172 Shft, AtomicSt->getBasePtr(),
7173 AtomicSt->getMemOperand());
7174
7175 StoreSDNode *St = cast<StoreSDNode>(Op.getNode());
7176 return DAG.getTruncStore(St->getChain(), DL, Shft, St->getBasePtr(), MVT::i16,
7177 St->getMemOperand());
7178}
7179
7180SDValue SystemZTargetLowering::lowerIS_FPCLASS(SDValue Op,
7181 SelectionDAG &DAG) const {
7182 SDLoc DL(Op);
7183 MVT ResultVT = Op.getSimpleValueType();
7184 SDValue Arg = Op.getOperand(0);
7185 unsigned Check = Op.getConstantOperandVal(1);
7186
7187 unsigned TDCMask = 0;
7188 if (Check & fcSNan)
7190 if (Check & fcQNan)
7192 if (Check & fcPosInf)
7194 if (Check & fcNegInf)
7196 if (Check & fcPosNormal)
7198 if (Check & fcNegNormal)
7200 if (Check & fcPosSubnormal)
7202 if (Check & fcNegSubnormal)
7204 if (Check & fcPosZero)
7205 TDCMask |= SystemZ::TDCMASK_ZERO_PLUS;
7206 if (Check & fcNegZero)
7207 TDCMask |= SystemZ::TDCMASK_ZERO_MINUS;
7208 SDValue TDCMaskV = DAG.getConstant(TDCMask, DL, MVT::i64);
7209
7210 SDValue Intr = DAG.getNode(SystemZISD::TDC, DL, ResultVT, Arg, TDCMaskV);
7211 return getCCResult(DAG, Intr);
7212}
7213
7214SDValue SystemZTargetLowering::lowerREADCYCLECOUNTER(SDValue Op,
7215 SelectionDAG &DAG) const {
7216 SDLoc DL(Op);
7217 SDValue Chain = Op.getOperand(0);
7218
7219 // STCKF only supports a memory operand, so we have to use a temporary.
7220 SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
7221 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
7222 MachinePointerInfo MPI =
7224
7225 // Use STCFK to store the TOD clock into the temporary.
7226 SDValue StoreOps[] = {Chain, StackPtr};
7227 Chain = DAG.getMemIntrinsicNode(
7228 SystemZISD::STCKF, DL, DAG.getVTList(MVT::Other), StoreOps, MVT::i64,
7229 MPI, MaybeAlign(), MachineMemOperand::MOStore);
7230
7231 // And read it back from there.
7232 return DAG.getLoad(MVT::i64, DL, Chain, StackPtr, MPI);
7233}
7234
7236 SelectionDAG &DAG) const {
7237 switch (Op.getOpcode()) {
7238 case ISD::FRAMEADDR:
7239 return lowerFRAMEADDR(Op, DAG);
7240 case ISD::RETURNADDR:
7241 return lowerRETURNADDR(Op, DAG);
7242 case ISD::BR_CC:
7243 return lowerBR_CC(Op, DAG);
7244 case ISD::SELECT_CC:
7245 return lowerSELECT_CC(Op, DAG);
7246 case ISD::SETCC:
7247 return lowerSETCC(Op, DAG);
7248 case ISD::STRICT_FSETCC:
7249 return lowerSTRICT_FSETCC(Op, DAG, false);
7251 return lowerSTRICT_FSETCC(Op, DAG, true);
7252 case ISD::GlobalAddress:
7253 return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
7255 return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
7256 case ISD::BlockAddress:
7257 return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
7258 case ISD::JumpTable:
7259 return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
7260 case ISD::ConstantPool:
7261 return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
7262 case ISD::BITCAST:
7263 return lowerBITCAST(Op, DAG);
7264 case ISD::VASTART:
7265 return lowerVASTART(Op, DAG);
7266 case ISD::VACOPY:
7267 return lowerVACOPY(Op, DAG);
7269 return lowerDYNAMIC_STACKALLOC(Op, DAG);
7271 return lowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
7272 case ISD::MULHS:
7273 return lowerMULH(Op, DAG, SystemZISD::SMUL_LOHI);
7274 case ISD::MULHU:
7275 return lowerMULH(Op, DAG, SystemZISD::UMUL_LOHI);
7276 case ISD::SMUL_LOHI:
7277 return lowerSMUL_LOHI(Op, DAG);
7278 case ISD::UMUL_LOHI:
7279 return lowerUMUL_LOHI(Op, DAG);
7280 case ISD::SDIVREM:
7281 return lowerSDIVREM(Op, DAG);
7282 case ISD::UDIVREM:
7283 return lowerUDIVREM(Op, DAG);
7284 case ISD::SADDO:
7285 case ISD::SSUBO:
7286 case ISD::UADDO:
7287 case ISD::USUBO:
7288 return lowerXALUO(Op, DAG);
7289 case ISD::UADDO_CARRY:
7290 case ISD::USUBO_CARRY:
7291 return lowerUADDSUBO_CARRY(Op, DAG);
7292 case ISD::OR:
7293 return lowerOR(Op, DAG);
7294 case ISD::CTPOP:
7295 return lowerCTPOP(Op, DAG);
7296 case ISD::VECREDUCE_ADD:
7297 return lowerVECREDUCE_ADD(Op, DAG);
7298 case ISD::ATOMIC_FENCE:
7299 return lowerATOMIC_FENCE(Op, DAG);
7300 case ISD::ATOMIC_SWAP:
7301 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_SWAPW);
7302 case ISD::ATOMIC_STORE:
7303 return lowerATOMIC_STORE(Op, DAG);
7304 case ISD::ATOMIC_LOAD:
7305 return lowerATOMIC_LOAD(Op, DAG);
7307 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
7309 return lowerATOMIC_LOAD_SUB(Op, DAG);
7311 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
7313 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
7315 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
7317 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
7319 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
7321 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
7323 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
7325 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
7327 return lowerATOMIC_CMP_SWAP(Op, DAG);
7328 case ISD::STACKSAVE:
7329 return lowerSTACKSAVE(Op, DAG);
7330 case ISD::STACKRESTORE:
7331 return lowerSTACKRESTORE(Op, DAG);
7332 case ISD::PREFETCH:
7333 return lowerPREFETCH(Op, DAG);
7335 return lowerINTRINSIC_W_CHAIN(Op, DAG);
7337 return lowerINTRINSIC_WO_CHAIN(Op, DAG);
7338 case ISD::BUILD_VECTOR:
7339 return lowerBUILD_VECTOR(Op, DAG);
7341 return lowerVECTOR_SHUFFLE(Op, DAG);
7343 return lowerSCALAR_TO_VECTOR(Op, DAG);
7345 return lowerINSERT_VECTOR_ELT(Op, DAG);
7347 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
7349 return lowerSIGN_EXTEND_VECTOR_INREG(Op, DAG);
7351 return lowerZERO_EXTEND_VECTOR_INREG(Op, DAG);
7352 case ISD::SHL:
7353 return lowerShift(Op, DAG, SystemZISD::VSHL_BY_SCALAR);
7354 case ISD::SRL:
7355 return lowerShift(Op, DAG, SystemZISD::VSRL_BY_SCALAR);
7356 case ISD::SRA:
7357 return lowerShift(Op, DAG, SystemZISD::VSRA_BY_SCALAR);
7358 case ISD::ADDRSPACECAST:
7359 return lowerAddrSpaceCast(Op, DAG);
7360 case ISD::ROTL:
7361 return lowerShift(Op, DAG, SystemZISD::VROTL_BY_SCALAR);
7362 case ISD::FSHL:
7363 return lowerFSHL(Op, DAG);
7364 case ISD::FSHR:
7365 return lowerFSHR(Op, DAG);
7366 case ISD::FP_EXTEND:
7368 return lowerFP_EXTEND(Op, DAG);
7369 case ISD::FP_TO_UINT:
7370 case ISD::FP_TO_SINT:
7373 return lower_FP_TO_INT(Op, DAG);
7374 case ISD::UINT_TO_FP:
7375 case ISD::SINT_TO_FP:
7378 return lower_INT_TO_FP(Op, DAG);
7379 case ISD::LOAD:
7380 return lowerLoadF16(Op, DAG);
7381 case ISD::STORE:
7382 return lowerStoreF16(Op, DAG);
7383 case ISD::IS_FPCLASS:
7384 return lowerIS_FPCLASS(Op, DAG);
7385 case ISD::GET_ROUNDING:
7386 return lowerGET_ROUNDING(Op, DAG);
7388 return lowerREADCYCLECOUNTER(Op, DAG);
7391 // These operations are legal on our platform, but we cannot actually
7392 // set the operation action to Legal as common code would treat this
7393 // as equivalent to Expand. Instead, we keep the operation action to
7394 // Custom and just leave them unchanged here.
7395 return Op;
7396
7397 default:
7398 llvm_unreachable("Unexpected node to lower");
7399 }
7400}
7401
7403 const SDLoc &SL) {
7404 // If i128 is legal, just use a normal bitcast.
7405 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128))
7406 return DAG.getBitcast(MVT::f128, Src);
7407
7408 // Otherwise, f128 must live in FP128, so do a partwise move.
7410 &SystemZ::FP128BitRegClass);
7411
7412 SDValue Hi, Lo;
7413 std::tie(Lo, Hi) = DAG.SplitScalar(Src, SL, MVT::i64, MVT::i64);
7414
7415 Hi = DAG.getBitcast(MVT::f64, Hi);
7416 Lo = DAG.getBitcast(MVT::f64, Lo);
7417
7418 SDNode *Pair = DAG.getMachineNode(
7419 SystemZ::REG_SEQUENCE, SL, MVT::f128,
7420 {DAG.getTargetConstant(SystemZ::FP128BitRegClassID, SL, MVT::i32), Lo,
7421 DAG.getTargetConstant(SystemZ::subreg_l64, SL, MVT::i32), Hi,
7422 DAG.getTargetConstant(SystemZ::subreg_h64, SL, MVT::i32)});
7423 return SDValue(Pair, 0);
7424}
7425
7427 const SDLoc &SL) {
7428 // If i128 is legal, just use a normal bitcast.
7429 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128))
7430 return DAG.getBitcast(MVT::i128, Src);
7431
7432 // Otherwise, f128 must live in FP128, so do a partwise move.
7434 &SystemZ::FP128BitRegClass);
7435
7436 SDValue LoFP =
7437 DAG.getTargetExtractSubreg(SystemZ::subreg_l64, SL, MVT::f64, Src);
7438 SDValue HiFP =
7439 DAG.getTargetExtractSubreg(SystemZ::subreg_h64, SL, MVT::f64, Src);
7440 SDValue Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i64, LoFP);
7441 SDValue Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i64, HiFP);
7442
7443 return DAG.getNode(ISD::BUILD_PAIR, SL, MVT::i128, Lo, Hi);
7444}
7445
7446// Lower operations with invalid operand or result types.
7447void
7450 SelectionDAG &DAG) const {
7451 switch (N->getOpcode()) {
7452 case ISD::ATOMIC_LOAD: {
7453 SDLoc DL(N);
7454 SDVTList Tys = DAG.getVTList(MVT::Untyped, MVT::Other);
7455 SDValue Ops[] = { N->getOperand(0), N->getOperand(1) };
7456 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
7457 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_LOAD_128,
7458 DL, Tys, Ops, MVT::i128, MMO);
7459
7460 SDValue Lowered = lowerGR128ToI128(DAG, Res);
7461 if (N->getValueType(0) == MVT::f128)
7462 Lowered = expandBitCastI128ToF128(DAG, Lowered, DL);
7463 Results.push_back(Lowered);
7464 Results.push_back(Res.getValue(1));
7465 break;
7466 }
7467 case ISD::ATOMIC_STORE: {
7468 SDLoc DL(N);
7469 SDVTList Tys = DAG.getVTList(MVT::Other);
7470 SDValue Val = N->getOperand(1);
7471 if (Val.getValueType() == MVT::f128)
7472 Val = expandBitCastF128ToI128(DAG, Val, DL);
7473 Val = lowerI128ToGR128(DAG, Val);
7474
7475 SDValue Ops[] = {N->getOperand(0), Val, N->getOperand(2)};
7476 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
7477 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_STORE_128,
7478 DL, Tys, Ops, MVT::i128, MMO);
7479 // We have to enforce sequential consistency by performing a
7480 // serialization operation after the store.
7481 if (cast<AtomicSDNode>(N)->getSuccessOrdering() ==
7483 Res = SDValue(DAG.getMachineNode(SystemZ::Serialize, DL,
7484 MVT::Other, Res), 0);
7485 Results.push_back(Res);
7486 break;
7487 }
7489 SDLoc DL(N);
7490 SDVTList Tys = DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other);
7491 SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
7492 lowerI128ToGR128(DAG, N->getOperand(2)),
7493 lowerI128ToGR128(DAG, N->getOperand(3)) };
7494 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
7495 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP_128,
7496 DL, Tys, Ops, MVT::i128, MMO);
7497 SDValue Success = emitSETCC(DAG, DL, Res.getValue(1),
7499 Success = DAG.getZExtOrTrunc(Success, DL, N->getValueType(1));
7500 Results.push_back(lowerGR128ToI128(DAG, Res));
7501 Results.push_back(Success);
7502 Results.push_back(Res.getValue(2));
7503 break;
7504 }
7505 case ISD::BITCAST: {
7506 if (useSoftFloat())
7507 return;
7508 SDLoc DL(N);
7509 SDValue Src = N->getOperand(0);
7510 EVT SrcVT = Src.getValueType();
7511 EVT ResVT = N->getValueType(0);
7512 if (ResVT == MVT::i128 && SrcVT == MVT::f128)
7513 Results.push_back(expandBitCastF128ToI128(DAG, Src, DL));
7514 else if (SrcVT == MVT::i16 && ResVT == MVT::f16) {
7515 if (Subtarget.hasVector()) {
7516 SDValue In32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Src);
7517 Results.push_back(SDValue(
7518 DAG.getMachineNode(SystemZ::LEFR_16, DL, MVT::f16, In32), 0));
7519 } else {
7520 SDValue In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Src);
7521 Results.push_back(convertToF16(In64, DAG));
7522 }
7523 } else if (SrcVT == MVT::f16 && ResVT == MVT::i16) {
7524 SDValue ExtractedVal =
7525 Subtarget.hasVector()
7526 ? SDValue(DAG.getMachineNode(SystemZ::LFER_16, DL, MVT::i32, Src),
7527 0)
7528 : convertFromF16(Src, DL, DAG);
7529 Results.push_back(DAG.getZExtOrTrunc(ExtractedVal, DL, ResVT));
7530 }
7531 break;
7532 }
7533 case ISD::UINT_TO_FP:
7534 case ISD::SINT_TO_FP:
7537 if (useSoftFloat())
7538 return;
7539 bool IsStrict = N->isStrictFPOpcode();
7540 SDLoc DL(N);
7541 SDValue InOp = N->getOperand(IsStrict ? 1 : 0);
7542 EVT ResVT = N->getValueType(0);
7543 SDValue Chain = IsStrict ? N->getOperand(0) : DAG.getEntryNode();
7544 if (ResVT == MVT::f16) {
7545 if (!IsStrict) {
7546 SDValue OpF32 = DAG.getNode(N->getOpcode(), DL, MVT::f32, InOp);
7547 Results.push_back(DAG.getFPExtendOrRound(OpF32, DL, MVT::f16));
7548 } else {
7549 SDValue OpF32 =
7550 DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::f32, MVT::Other),
7551 {Chain, InOp});
7552 SDValue F16Res;
7553 std::tie(F16Res, Chain) = DAG.getStrictFPExtendOrRound(
7554 OpF32, OpF32.getValue(1), DL, MVT::f16);
7555 Results.push_back(F16Res);
7556 Results.push_back(Chain);
7557 }
7558 }
7559 break;
7560 }
7561 case ISD::FP_TO_UINT:
7562 case ISD::FP_TO_SINT:
7565 if (useSoftFloat())
7566 return;
7567 bool IsStrict = N->isStrictFPOpcode();
7568 SDLoc DL(N);
7569 EVT ResVT = N->getValueType(0);
7570 SDValue InOp = N->getOperand(IsStrict ? 1 : 0);
7571 EVT InVT = InOp->getValueType(0);
7572 SDValue Chain = IsStrict ? N->getOperand(0) : DAG.getEntryNode();
7573 if (InVT == MVT::f16) {
7574 if (!IsStrict) {
7575 SDValue InF32 = DAG.getFPExtendOrRound(InOp, DL, MVT::f32);
7576 Results.push_back(DAG.getNode(N->getOpcode(), DL, ResVT, InF32));
7577 } else {
7578 SDValue InF32;
7579 std::tie(InF32, Chain) =
7580 DAG.getStrictFPExtendOrRound(InOp, Chain, DL, MVT::f32);
7581 SDValue OpF32 =
7582 DAG.getNode(N->getOpcode(), DL, DAG.getVTList(ResVT, MVT::Other),
7583 {Chain, InF32});
7584 Results.push_back(OpF32);
7585 Results.push_back(OpF32.getValue(1));
7586 }
7587 }
7588 break;
7589 }
7590 default:
7591 llvm_unreachable("Unexpected node to lower");
7592 }
7593}
7594
7595void
7601
7602// Return true if VT is a vector whose elements are a whole number of bytes
7603// in width. Also check for presence of vector support.
7604bool SystemZTargetLowering::canTreatAsByteVector(EVT VT) const {
7605 if (!Subtarget.hasVector())
7606 return false;
7607
7608 return VT.isVector() && VT.getScalarSizeInBits() % 8 == 0 && VT.isSimple();
7609}
7610
7611// Try to simplify an EXTRACT_VECTOR_ELT from a vector of type VecVT
7612// producing a result of type ResVT. Op is a possibly bitcast version
7613// of the input vector and Index is the index (based on type VecVT) that
7614// should be extracted. Return the new extraction if a simplification
7615// was possible or if Force is true.
7616SDValue SystemZTargetLowering::combineExtract(const SDLoc &DL, EVT ResVT,
7617 EVT VecVT, SDValue Op,
7618 unsigned Index,
7619 DAGCombinerInfo &DCI,
7620 bool Force) const {
7621 SelectionDAG &DAG = DCI.DAG;
7622
7623 // The number of bytes being extracted.
7624 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
7625
7626 for (;;) {
7627 unsigned Opcode = Op.getOpcode();
7628 if (Opcode == ISD::BITCAST)
7629 // Look through bitcasts.
7630 Op = Op.getOperand(0);
7631 else if ((Opcode == ISD::VECTOR_SHUFFLE || Opcode == SystemZISD::SPLAT) &&
7632 canTreatAsByteVector(Op.getValueType())) {
7633 // Get a VPERM-like permute mask and see whether the bytes covered
7634 // by the extracted element are a contiguous sequence from one
7635 // source operand.
7637 if (!getVPermMask(Op, Bytes))
7638 break;
7639 int First;
7640 if (!getShuffleInput(Bytes, Index * BytesPerElement,
7641 BytesPerElement, First))
7642 break;
7643 if (First < 0)
7644 return DAG.getUNDEF(ResVT);
7645 // Make sure the contiguous sequence starts at a multiple of the
7646 // original element size.
7647 unsigned Byte = unsigned(First) % Bytes.size();
7648 if (Byte % BytesPerElement != 0)
7649 break;
7650 // We can get the extracted value directly from an input.
7651 Index = Byte / BytesPerElement;
7652 Op = Op.getOperand(unsigned(First) / Bytes.size());
7653 Force = true;
7654 } else if (Opcode == ISD::BUILD_VECTOR &&
7655 canTreatAsByteVector(Op.getValueType())) {
7656 // We can only optimize this case if the BUILD_VECTOR elements are
7657 // at least as wide as the extracted value.
7658 EVT OpVT = Op.getValueType();
7659 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
7660 if (OpBytesPerElement < BytesPerElement)
7661 break;
7662 // Make sure that the least-significant bit of the extracted value
7663 // is the least significant bit of an input.
7664 unsigned End = (Index + 1) * BytesPerElement;
7665 if (End % OpBytesPerElement != 0)
7666 break;
7667 // We're extracting the low part of one operand of the BUILD_VECTOR.
7668 Op = Op.getOperand(End / OpBytesPerElement - 1);
7669 EVT ResIntVT = MVT::getIntegerVT(ResVT.getSizeInBits());
7670 if (!isTypeLegal(ResIntVT))
7671 break;
7672 if (!Op.getValueType().isInteger()) {
7673 EVT OpIntVT = MVT::getIntegerVT(Op.getValueSizeInBits());
7674 if (!isTypeLegal(OpIntVT))
7675 break;
7676 Op = DAG.getNode(ISD::BITCAST, DL, OpIntVT, Op);
7677 DCI.AddToWorklist(Op.getNode());
7678 }
7679 Op = DAG.getNode(ISD::TRUNCATE, DL, ResIntVT, Op);
7680 if (ResIntVT != ResVT) {
7681 DCI.AddToWorklist(Op.getNode());
7682 Op = DAG.getNode(ISD::BITCAST, DL, ResVT, Op);
7683 }
7684 return Op;
7685 } else if ((Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
7687 Opcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
7688 canTreatAsByteVector(Op.getValueType()) &&
7689 canTreatAsByteVector(Op.getOperand(0).getValueType())) {
7690 // Make sure that only the unextended bits are significant.
7691 EVT ExtVT = Op.getValueType();
7692 EVT OpVT = Op.getOperand(0).getValueType();
7693 unsigned ExtBytesPerElement = ExtVT.getVectorElementType().getStoreSize();
7694 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
7695 unsigned Byte = Index * BytesPerElement;
7696 unsigned SubByte = Byte % ExtBytesPerElement;
7697 unsigned MinSubByte = ExtBytesPerElement - OpBytesPerElement;
7698 if (SubByte < MinSubByte ||
7699 SubByte + BytesPerElement > ExtBytesPerElement)
7700 break;
7701 // Get the byte offset of the unextended element
7702 Byte = Byte / ExtBytesPerElement * OpBytesPerElement;
7703 // ...then add the byte offset relative to that element.
7704 Byte += SubByte - MinSubByte;
7705 if (Byte % BytesPerElement != 0)
7706 break;
7707 Op = Op.getOperand(0);
7708 Index = Byte / BytesPerElement;
7709 Force = true;
7710 } else
7711 break;
7712 }
7713 if (Force) {
7714 if (Op.getValueType() != VecVT) {
7715 Op = DAG.getNode(ISD::BITCAST, DL, VecVT, Op);
7716 DCI.AddToWorklist(Op.getNode());
7717 }
7718 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Op,
7719 DAG.getConstant(Index, DL, MVT::i32));
7720 }
7721 return SDValue();
7722}
7723
7724// Optimize vector operations in scalar value Op on the basis that Op
7725// is truncated to TruncVT.
7726SDValue SystemZTargetLowering::combineTruncateExtract(
7727 const SDLoc &DL, EVT TruncVT, SDValue Op, DAGCombinerInfo &DCI) const {
7728 // If we have (trunc (extract_vector_elt X, Y)), try to turn it into
7729 // (extract_vector_elt (bitcast X), Y'), where (bitcast X) has elements
7730 // of type TruncVT.
7731 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7732 TruncVT.getSizeInBits() % 8 == 0) {
7733 SDValue Vec = Op.getOperand(0);
7734 EVT VecVT = Vec.getValueType();
7735 if (canTreatAsByteVector(VecVT)) {
7736 if (auto *IndexN = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7737 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
7738 unsigned TruncBytes = TruncVT.getStoreSize();
7739 if (BytesPerElement % TruncBytes == 0) {
7740 // Calculate the value of Y' in the above description. We are
7741 // splitting the original elements into Scale equal-sized pieces
7742 // and for truncation purposes want the last (least-significant)
7743 // of these pieces for IndexN. This is easiest to do by calculating
7744 // the start index of the following element and then subtracting 1.
7745 unsigned Scale = BytesPerElement / TruncBytes;
7746 unsigned NewIndex = (IndexN->getZExtValue() + 1) * Scale - 1;
7747
7748 // Defer the creation of the bitcast from X to combineExtract,
7749 // which might be able to optimize the extraction.
7750 VecVT = EVT::getVectorVT(*DCI.DAG.getContext(),
7751 MVT::getIntegerVT(TruncBytes * 8),
7752 VecVT.getStoreSize() / TruncBytes);
7753 EVT ResVT = (TruncBytes < 4 ? MVT::i32 : TruncVT);
7754 return combineExtract(DL, ResVT, VecVT, Vec, NewIndex, DCI, true);
7755 }
7756 }
7757 }
7758 }
7759 return SDValue();
7760}
7761
7762SDValue SystemZTargetLowering::combineZERO_EXTEND(
7763 SDNode *N, DAGCombinerInfo &DCI) const {
7764 // Convert (zext (select_ccmask C1, C2)) into (select_ccmask C1', C2')
7765 SelectionDAG &DAG = DCI.DAG;
7766 SDValue N0 = N->getOperand(0);
7767 EVT VT = N->getValueType(0);
7768 if (N0.getOpcode() == SystemZISD::SELECT_CCMASK) {
7769 auto *TrueOp = dyn_cast<ConstantSDNode>(N0.getOperand(0));
7770 auto *FalseOp = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7771 if (TrueOp && FalseOp) {
7772 SDLoc DL(N0);
7773 SDValue Ops[] = { DAG.getConstant(TrueOp->getZExtValue(), DL, VT),
7774 DAG.getConstant(FalseOp->getZExtValue(), DL, VT),
7775 N0.getOperand(2), N0.getOperand(3), N0.getOperand(4) };
7776 SDValue NewSelect = DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VT, Ops);
7777 // If N0 has multiple uses, change other uses as well.
7778 if (!N0.hasOneUse()) {
7779 SDValue TruncSelect =
7780 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), NewSelect);
7781 DCI.CombineTo(N0.getNode(), TruncSelect);
7782 }
7783 return NewSelect;
7784 }
7785 }
7786 // Convert (zext (xor (trunc X), C)) into (xor (trunc X), C') if the size
7787 // of the result is smaller than the size of X and all the truncated bits
7788 // of X are already zero.
7789 if (N0.getOpcode() == ISD::XOR &&
7790 N0.hasOneUse() && N0.getOperand(0).hasOneUse() &&
7791 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7792 N0.getOperand(1).getOpcode() == ISD::Constant) {
7793 SDValue X = N0.getOperand(0).getOperand(0);
7794 if (VT.isScalarInteger() && VT.getSizeInBits() < X.getValueSizeInBits()) {
7795 KnownBits Known = DAG.computeKnownBits(X);
7796 APInt TruncatedBits = APInt::getBitsSet(X.getValueSizeInBits(),
7797 N0.getValueSizeInBits(),
7798 VT.getSizeInBits());
7799 if (TruncatedBits.isSubsetOf(Known.Zero)) {
7800 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7801 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
7802 return DAG.getNode(ISD::XOR, SDLoc(N0), VT,
7803 X, DAG.getConstant(Mask, SDLoc(N0), VT));
7804 }
7805 }
7806 }
7807 // Recognize patterns for VECTOR SUBTRACT COMPUTE BORROW INDICATION
7808 // and VECTOR ADD COMPUTE CARRY for i128:
7809 // (zext (setcc_uge X Y)) --> (VSCBI X Y)
7810 // (zext (setcc_ule Y X)) --> (VSCBI X Y)
7811 // (zext (setcc_ult (add X Y) X/Y) -> (VACC X Y)
7812 // (zext (setcc_ugt X/Y (add X Y)) -> (VACC X Y)
7813 // For vector types, these patterns are recognized in the .td file.
7814 if (N0.getOpcode() == ISD::SETCC && isTypeLegal(VT) && VT == MVT::i128 &&
7815 N0.getOperand(0).getValueType() == VT) {
7816 SDValue Op0 = N0.getOperand(0);
7817 SDValue Op1 = N0.getOperand(1);
7818 const ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7819 switch (CC) {
7820 case ISD::SETULE:
7821 std::swap(Op0, Op1);
7822 [[fallthrough]];
7823 case ISD::SETUGE:
7824 return DAG.getNode(SystemZISD::VSCBI, SDLoc(N0), VT, Op0, Op1);
7825 case ISD::SETUGT:
7826 std::swap(Op0, Op1);
7827 [[fallthrough]];
7828 case ISD::SETULT:
7829 if (Op0->hasOneUse() && Op0->getOpcode() == ISD::ADD &&
7830 (Op0->getOperand(0) == Op1 || Op0->getOperand(1) == Op1))
7831 return DAG.getNode(SystemZISD::VACC, SDLoc(N0), VT, Op0->getOperand(0),
7832 Op0->getOperand(1));
7833 break;
7834 default:
7835 break;
7836 }
7837 }
7838
7839 return SDValue();
7840}
7841
7842SDValue SystemZTargetLowering::combineSIGN_EXTEND_INREG(
7843 SDNode *N, DAGCombinerInfo &DCI) const {
7844 // Convert (sext_in_reg (setcc LHS, RHS, COND), i1)
7845 // and (sext_in_reg (any_extend (setcc LHS, RHS, COND)), i1)
7846 // into (select_cc LHS, RHS, -1, 0, COND)
7847 SelectionDAG &DAG = DCI.DAG;
7848 SDValue N0 = N->getOperand(0);
7849 EVT VT = N->getValueType(0);
7850 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7851 if (N0.hasOneUse() && N0.getOpcode() == ISD::ANY_EXTEND)
7852 N0 = N0.getOperand(0);
7853 if (EVT == MVT::i1 && N0.hasOneUse() && N0.getOpcode() == ISD::SETCC) {
7854 SDLoc DL(N0);
7855 SDValue Ops[] = { N0.getOperand(0), N0.getOperand(1),
7856 DAG.getAllOnesConstant(DL, VT),
7857 DAG.getConstant(0, DL, VT), N0.getOperand(2) };
7858 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
7859 }
7860 return SDValue();
7861}
7862
7863SDValue SystemZTargetLowering::combineSIGN_EXTEND(
7864 SDNode *N, DAGCombinerInfo &DCI) const {
7865 // Convert (sext (ashr (shl X, C1), C2)) to
7866 // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
7867 // cheap as narrower ones.
7868 SelectionDAG &DAG = DCI.DAG;
7869 SDValue N0 = N->getOperand(0);
7870 EVT VT = N->getValueType(0);
7871 if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
7872 auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7873 SDValue Inner = N0.getOperand(0);
7874 if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
7875 if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
7876 unsigned Extra = (VT.getSizeInBits() - N0.getValueSizeInBits());
7877 unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
7878 unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
7879 EVT ShiftVT = N0.getOperand(1).getValueType();
7880 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
7881 Inner.getOperand(0));
7882 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
7883 DAG.getConstant(NewShlAmt, SDLoc(Inner),
7884 ShiftVT));
7885 return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
7886 DAG.getConstant(NewSraAmt, SDLoc(N0), ShiftVT));
7887 }
7888 }
7889 }
7890
7891 return SDValue();
7892}
7893
7894SDValue SystemZTargetLowering::combineMERGE(
7895 SDNode *N, DAGCombinerInfo &DCI) const {
7896 SelectionDAG &DAG = DCI.DAG;
7897 unsigned Opcode = N->getOpcode();
7898 SDValue Op0 = N->getOperand(0);
7899 SDValue Op1 = N->getOperand(1);
7900 if (Op0.getOpcode() == ISD::BITCAST)
7901 Op0 = Op0.getOperand(0);
7903 // (z_merge_* 0, 0) -> 0. This is mostly useful for using VLLEZF
7904 // for v4f32.
7905 if (Op1 == N->getOperand(0))
7906 return Op1;
7907 // (z_merge_? 0, X) -> (z_unpackl_? 0, X).
7908 EVT VT = Op1.getValueType();
7909 unsigned ElemBytes = VT.getVectorElementType().getStoreSize();
7910 if (ElemBytes <= 4) {
7911 Opcode = (Opcode == SystemZISD::MERGE_HIGH ?
7912 SystemZISD::UNPACKL_HIGH : SystemZISD::UNPACKL_LOW);
7913 EVT InVT = VT.changeVectorElementTypeToInteger();
7914 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(ElemBytes * 16),
7915 SystemZ::VectorBytes / ElemBytes / 2);
7916 if (VT != InVT) {
7917 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), InVT, Op1);
7918 DCI.AddToWorklist(Op1.getNode());
7919 }
7920 SDValue Op = DAG.getNode(Opcode, SDLoc(N), OutVT, Op1);
7921 DCI.AddToWorklist(Op.getNode());
7922 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7923 }
7924 }
7925 return SDValue();
7926}
7927
7928static bool isI128MovedToParts(LoadSDNode *LD, SDNode *&LoPart,
7929 SDNode *&HiPart) {
7930 LoPart = HiPart = nullptr;
7931
7932 // Scan through all users.
7933 for (SDUse &Use : LD->uses()) {
7934 // Skip the uses of the chain.
7935 if (Use.getResNo() != 0)
7936 continue;
7937
7938 // Verify every user is a TRUNCATE to i64 of the low or high half.
7939 SDNode *User = Use.getUser();
7940 bool IsLoPart = true;
7941 if (User->getOpcode() == ISD::SRL &&
7942 User->getOperand(1).getOpcode() == ISD::Constant &&
7943 User->getConstantOperandVal(1) == 64 && User->hasOneUse()) {
7944 User = *User->user_begin();
7945 IsLoPart = false;
7946 }
7947 if (User->getOpcode() != ISD::TRUNCATE || User->getValueType(0) != MVT::i64)
7948 return false;
7949
7950 if (IsLoPart) {
7951 if (LoPart)
7952 return false;
7953 LoPart = User;
7954 } else {
7955 if (HiPart)
7956 return false;
7957 HiPart = User;
7958 }
7959 }
7960 return true;
7961}
7962
7963static bool isF128MovedToParts(LoadSDNode *LD, SDNode *&LoPart,
7964 SDNode *&HiPart) {
7965 LoPart = HiPart = nullptr;
7966
7967 // Scan through all users.
7968 for (SDUse &Use : LD->uses()) {
7969 // Skip the uses of the chain.
7970 if (Use.getResNo() != 0)
7971 continue;
7972
7973 // Verify every user is an EXTRACT_SUBREG of the low or high half.
7974 SDNode *User = Use.getUser();
7975 if (!User->hasOneUse() || !User->isMachineOpcode() ||
7976 User->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
7977 return false;
7978
7979 switch (User->getConstantOperandVal(1)) {
7980 case SystemZ::subreg_l64:
7981 if (LoPart)
7982 return false;
7983 LoPart = User;
7984 break;
7985 case SystemZ::subreg_h64:
7986 if (HiPart)
7987 return false;
7988 HiPart = User;
7989 break;
7990 default:
7991 return false;
7992 }
7993 }
7994 return true;
7995}
7996
7997SDValue SystemZTargetLowering::combineLOAD(
7998 SDNode *N, DAGCombinerInfo &DCI) const {
7999 SelectionDAG &DAG = DCI.DAG;
8000 EVT LdVT = N->getValueType(0);
8001 if (auto *LN = dyn_cast<LoadSDNode>(N)) {
8002 if (LN->getAddressSpace() == SYSTEMZAS::PTR32) {
8003 MVT PtrVT = getPointerTy(DAG.getDataLayout());
8004 MVT LoadNodeVT = LN->getBasePtr().getSimpleValueType();
8005 if (PtrVT != LoadNodeVT) {
8006 SDLoc DL(LN);
8007 SDValue AddrSpaceCast = DAG.getAddrSpaceCast(
8008 DL, PtrVT, LN->getBasePtr(), SYSTEMZAS::PTR32, 0);
8009 return DAG.getExtLoad(LN->getExtensionType(), DL, LN->getValueType(0),
8010 LN->getChain(), AddrSpaceCast, LN->getMemoryVT(),
8011 LN->getMemOperand());
8012 }
8013 }
8014 }
8015 SDLoc DL(N);
8016
8017 // Replace a 128-bit load that is used solely to move its value into GPRs
8018 // by separate loads of both halves.
8019 LoadSDNode *LD = cast<LoadSDNode>(N);
8020 if (LD->isSimple() && ISD::isNormalLoad(LD)) {
8021 SDNode *LoPart, *HiPart;
8022 if ((LdVT == MVT::i128 && isI128MovedToParts(LD, LoPart, HiPart)) ||
8023 (LdVT == MVT::f128 && isF128MovedToParts(LD, LoPart, HiPart))) {
8024 // Rewrite each extraction as an independent load.
8025 SmallVector<SDValue, 2> ArgChains;
8026 if (HiPart) {
8027 SDValue EltLoad = DAG.getLoad(
8028 HiPart->getValueType(0), DL, LD->getChain(), LD->getBasePtr(),
8029 LD->getPointerInfo(), LD->getBaseAlign(),
8030 LD->getMemOperand()->getFlags(), LD->getAAInfo());
8031
8032 DCI.CombineTo(HiPart, EltLoad, true);
8033 ArgChains.push_back(EltLoad.getValue(1));
8034 }
8035 if (LoPart) {
8036 SDValue EltLoad = DAG.getLoad(
8037 LoPart->getValueType(0), DL, LD->getChain(),
8038 DAG.getObjectPtrOffset(DL, LD->getBasePtr(), TypeSize::getFixed(8)),
8039 LD->getPointerInfo().getWithOffset(8), LD->getBaseAlign(),
8040 LD->getMemOperand()->getFlags(), LD->getAAInfo());
8041
8042 DCI.CombineTo(LoPart, EltLoad, true);
8043 ArgChains.push_back(EltLoad.getValue(1));
8044 }
8045
8046 // Collect all chains via TokenFactor.
8047 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, ArgChains);
8048 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8049 DCI.AddToWorklist(Chain.getNode());
8050 return SDValue(N, 0);
8051 }
8052 }
8053
8054 if (LdVT.isVector() || LdVT.isInteger())
8055 return SDValue();
8056 // Transform a scalar load that is REPLICATEd as well as having other
8057 // use(s) to the form where the other use(s) use the first element of the
8058 // REPLICATE instead of the load. Otherwise instruction selection will not
8059 // produce a VLREP. Avoid extracting to a GPR, so only do this for floating
8060 // point loads.
8061
8062 SDValue Replicate;
8063 SmallVector<SDNode*, 8> OtherUses;
8064 for (SDUse &Use : N->uses()) {
8065 if (Use.getUser()->getOpcode() == SystemZISD::REPLICATE) {
8066 if (Replicate)
8067 return SDValue(); // Should never happen
8068 Replicate = SDValue(Use.getUser(), 0);
8069 } else if (Use.getResNo() == 0)
8070 OtherUses.push_back(Use.getUser());
8071 }
8072 if (!Replicate || OtherUses.empty())
8073 return SDValue();
8074
8075 SDValue Extract0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, LdVT,
8076 Replicate, DAG.getConstant(0, DL, MVT::i32));
8077 // Update uses of the loaded Value while preserving old chains.
8078 for (SDNode *U : OtherUses) {
8080 for (SDValue Op : U->ops())
8081 Ops.push_back((Op.getNode() == N && Op.getResNo() == 0) ? Extract0 : Op);
8082 DAG.UpdateNodeOperands(U, Ops);
8083 }
8084 return SDValue(N, 0);
8085}
8086
8087bool SystemZTargetLowering::canLoadStoreByteSwapped(EVT VT) const {
8088 if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)
8089 return true;
8090 if (Subtarget.hasVectorEnhancements2())
8091 if (VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v2i64 || VT == MVT::i128)
8092 return true;
8093 return false;
8094}
8095
8097 if (!VT.isVector() || !VT.isSimple() ||
8098 VT.getSizeInBits() != 128 ||
8099 VT.getScalarSizeInBits() % 8 != 0)
8100 return false;
8101
8102 unsigned NumElts = VT.getVectorNumElements();
8103 for (unsigned i = 0; i < NumElts; ++i) {
8104 if (M[i] < 0) continue; // ignore UNDEF indices
8105 if ((unsigned) M[i] != NumElts - 1 - i)
8106 return false;
8107 }
8108
8109 return true;
8110}
8111
8112static bool isOnlyUsedByStores(SDValue StoredVal, SelectionDAG &DAG) {
8113 for (auto *U : StoredVal->users()) {
8114 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(U)) {
8115 EVT CurrMemVT = ST->getMemoryVT().getScalarType();
8116 if (CurrMemVT.isRound() && CurrMemVT.getStoreSize() <= 16)
8117 continue;
8118 } else if (isa<BuildVectorSDNode>(U)) {
8119 SDValue BuildVector = SDValue(U, 0);
8120 if (DAG.isSplatValue(BuildVector, true/*AllowUndefs*/) &&
8121 isOnlyUsedByStores(BuildVector, DAG))
8122 continue;
8123 }
8124 return false;
8125 }
8126 return true;
8127}
8128
8129static bool isI128MovedFromParts(SDValue Val, SDValue &LoPart,
8130 SDValue &HiPart) {
8131 if (Val.getOpcode() != ISD::OR || !Val.getNode()->hasOneUse())
8132 return false;
8133
8134 SDValue Op0 = Val.getOperand(0);
8135 SDValue Op1 = Val.getOperand(1);
8136
8137 if (Op0.getOpcode() == ISD::SHL)
8138 std::swap(Op0, Op1);
8139 if (Op1.getOpcode() != ISD::SHL || !Op1.getNode()->hasOneUse() ||
8140 Op1.getOperand(1).getOpcode() != ISD::Constant ||
8141 Op1.getConstantOperandVal(1) != 64)
8142 return false;
8143 Op1 = Op1.getOperand(0);
8144
8145 if (Op0.getOpcode() != ISD::ZERO_EXTEND || !Op0.getNode()->hasOneUse() ||
8146 Op0.getOperand(0).getValueType() != MVT::i64)
8147 return false;
8148 if (Op1.getOpcode() != ISD::ANY_EXTEND || !Op1.getNode()->hasOneUse() ||
8149 Op1.getOperand(0).getValueType() != MVT::i64)
8150 return false;
8151
8152 LoPart = Op0.getOperand(0);
8153 HiPart = Op1.getOperand(0);
8154 return true;
8155}
8156
8157static bool isF128MovedFromParts(SDValue Val, SDValue &LoPart,
8158 SDValue &HiPart) {
8159 if (!Val.getNode()->hasOneUse() || !Val.isMachineOpcode() ||
8160 Val.getMachineOpcode() != TargetOpcode::REG_SEQUENCE)
8161 return false;
8162
8163 if (Val->getNumOperands() != 5 ||
8164 Val->getOperand(0)->getAsZExtVal() != SystemZ::FP128BitRegClassID ||
8165 Val->getOperand(2)->getAsZExtVal() != SystemZ::subreg_l64 ||
8166 Val->getOperand(4)->getAsZExtVal() != SystemZ::subreg_h64)
8167 return false;
8168
8169 LoPart = Val->getOperand(1);
8170 HiPart = Val->getOperand(3);
8171 return true;
8172}
8173
8174SDValue SystemZTargetLowering::combineSTORE(
8175 SDNode *N, DAGCombinerInfo &DCI) const {
8176 SelectionDAG &DAG = DCI.DAG;
8177 auto *SN = cast<StoreSDNode>(N);
8178 auto &Op1 = N->getOperand(1);
8179 EVT MemVT = SN->getMemoryVT();
8180
8181 if (SN->getAddressSpace() == SYSTEMZAS::PTR32) {
8182 MVT PtrVT = getPointerTy(DAG.getDataLayout());
8183 MVT StoreNodeVT = SN->getBasePtr().getSimpleValueType();
8184 if (PtrVT != StoreNodeVT) {
8185 SDLoc DL(SN);
8186 SDValue AddrSpaceCast = DAG.getAddrSpaceCast(DL, PtrVT, SN->getBasePtr(),
8187 SYSTEMZAS::PTR32, 0);
8188 return DAG.getStore(SN->getChain(), DL, SN->getValue(), AddrSpaceCast,
8189 SN->getPointerInfo(), SN->getBaseAlign(),
8190 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8191 }
8192 }
8193
8194 // If we have (truncstoreiN (extract_vector_elt X, Y), Z) then it is better
8195 // for the extraction to be done on a vMiN value, so that we can use VSTE.
8196 // If X has wider elements then convert it to:
8197 // (truncstoreiN (extract_vector_elt (bitcast X), Y2), Z).
8198 if (MemVT.isInteger() && SN->isTruncatingStore()) {
8199 if (SDValue Value =
8200 combineTruncateExtract(SDLoc(N), MemVT, SN->getValue(), DCI)) {
8201 DCI.AddToWorklist(Value.getNode());
8202
8203 // Rewrite the store with the new form of stored value.
8204 return DAG.getTruncStore(SN->getChain(), SDLoc(SN), Value,
8205 SN->getBasePtr(), SN->getMemoryVT(),
8206 SN->getMemOperand());
8207 }
8208 }
8209
8210 // combine STORE (LOAD_STACK_GUARD) into MOV_STACKGUARD_DAG
8211 if (Op1->isMachineOpcode() &&
8212 (Op1->getMachineOpcode() == SystemZ::LOAD_STACK_GUARD)) {
8213 // Obtain the frame index the store was targeting.
8214 int FI = cast<FrameIndexSDNode>(SN->getOperand(2))->getIndex();
8215 // Prepare operands of the MOV_STACKGUARD ISD Node - Chain and FrameIndex.
8216 SDValue Ops[] = {SN->getChain(), DAG.getTargetFrameIndex(FI, MVT::i64)};
8217 return DAG.getNode(SystemZISD::MOV_STACKGUARD, SDLoc(SN), MVT::Other, Ops);
8218 }
8219
8220 // Combine STORE (BSWAP) into STRVH/STRV/STRVG/VSTBR
8221 if (!SN->isTruncatingStore() &&
8222 Op1.getOpcode() == ISD::BSWAP &&
8223 Op1.getNode()->hasOneUse() &&
8224 canLoadStoreByteSwapped(Op1.getValueType())) {
8225
8226 SDValue BSwapOp = Op1.getOperand(0);
8227
8228 if (BSwapOp.getValueType() == MVT::i16)
8229 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), MVT::i32, BSwapOp);
8230
8231 SDValue Ops[] = {
8232 N->getOperand(0), BSwapOp, N->getOperand(2)
8233 };
8234
8235 return
8236 DAG.getMemIntrinsicNode(SystemZISD::STRV, SDLoc(N), DAG.getVTList(MVT::Other),
8237 Ops, MemVT, SN->getMemOperand());
8238 }
8239 // Combine STORE (element-swap) into VSTER
8240 if (!SN->isTruncatingStore() &&
8241 Op1.getOpcode() == ISD::VECTOR_SHUFFLE &&
8242 Op1.getNode()->hasOneUse() &&
8243 Subtarget.hasVectorEnhancements2()) {
8244 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op1.getNode());
8245 ArrayRef<int> ShuffleMask = SVN->getMask();
8246 if (isVectorElementSwap(ShuffleMask, Op1.getValueType())) {
8247 SDValue Ops[] = {
8248 N->getOperand(0), Op1.getOperand(0), N->getOperand(2)
8249 };
8250
8251 return DAG.getMemIntrinsicNode(SystemZISD::VSTER, SDLoc(N),
8252 DAG.getVTList(MVT::Other),
8253 Ops, MemVT, SN->getMemOperand());
8254 }
8255 }
8256
8257 // Combine STORE (READCYCLECOUNTER) into STCKF.
8258 if (!SN->isTruncatingStore() &&
8260 Op1.hasOneUse() &&
8261 N->getOperand(0).reachesChainWithoutSideEffects(SDValue(Op1.getNode(), 1))) {
8262 SDValue Ops[] = { Op1.getOperand(0), N->getOperand(2) };
8263 return DAG.getMemIntrinsicNode(SystemZISD::STCKF, SDLoc(N),
8264 DAG.getVTList(MVT::Other),
8265 Ops, MemVT, SN->getMemOperand());
8266 }
8267
8268 // Transform a store of a 128-bit value moved from parts into two stores.
8269 if (SN->isSimple() && ISD::isNormalStore(SN)) {
8270 SDValue LoPart, HiPart;
8271 if ((MemVT == MVT::i128 && isI128MovedFromParts(Op1, LoPart, HiPart)) ||
8272 (MemVT == MVT::f128 && isF128MovedFromParts(Op1, LoPart, HiPart))) {
8273 SDLoc DL(SN);
8274 SDValue Chain0 = DAG.getStore(
8275 SN->getChain(), DL, HiPart, SN->getBasePtr(), SN->getPointerInfo(),
8276 SN->getBaseAlign(), SN->getMemOperand()->getFlags(), SN->getAAInfo());
8277 SDValue Chain1 = DAG.getStore(
8278 SN->getChain(), DL, LoPart,
8279 DAG.getObjectPtrOffset(DL, SN->getBasePtr(), TypeSize::getFixed(8)),
8280 SN->getPointerInfo().getWithOffset(8), SN->getBaseAlign(),
8281 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8282
8283 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chain0, Chain1);
8284 }
8285 }
8286
8287 // Replicate a reg or immediate with VREP instead of scalar multiply or
8288 // immediate load. It seems best to do this during the first DAGCombine as
8289 // it is straight-forward to handle the zero-extend node in the initial
8290 // DAG, and also not worry about the keeping the new MemVT legal (e.g. when
8291 // extracting an i16 element from a v16i8 vector).
8292 if (Subtarget.hasVector() && DCI.Level == BeforeLegalizeTypes &&
8293 isOnlyUsedByStores(Op1, DAG)) {
8294 SDValue Word = SDValue();
8295 EVT WordVT;
8296
8297 // Find a replicated immediate and return it if found in Word and its
8298 // type in WordVT.
8299 auto FindReplicatedImm = [&](ConstantSDNode *C, unsigned TotBytes) {
8300 // Some constants are better handled with a scalar store.
8301 if (C->getAPIntValue().getBitWidth() > 64 || C->isAllOnes() ||
8302 isInt<16>(C->getSExtValue()) || MemVT.getStoreSize() <= 2)
8303 return;
8304
8305 APInt Val = C->getAPIntValue();
8306 // Truncate Val in case of a truncating store.
8307 if (!llvm::isUIntN(TotBytes * 8, Val.getZExtValue())) {
8308 assert(SN->isTruncatingStore() &&
8309 "Non-truncating store and immediate value does not fit?");
8310 Val = Val.trunc(TotBytes * 8);
8311 }
8312
8313 SystemZVectorConstantInfo VCI(APInt(TotBytes * 8, Val.getZExtValue()));
8314 if (VCI.isVectorConstantLegal(Subtarget) &&
8315 VCI.Opcode == SystemZISD::REPLICATE) {
8316 Word = DAG.getConstant(VCI.OpVals[0], SDLoc(SN), MVT::i32);
8317 WordVT = VCI.VecVT.getScalarType();
8318 }
8319 };
8320
8321 // Find a replicated register and return it if found in Word and its type
8322 // in WordVT.
8323 auto FindReplicatedReg = [&](SDValue MulOp) {
8324 EVT MulVT = MulOp.getValueType();
8325 if (MulOp->getOpcode() == ISD::MUL &&
8326 (MulVT == MVT::i16 || MulVT == MVT::i32 || MulVT == MVT::i64)) {
8327 // Find a zero extended value and its type.
8328 SDValue LHS = MulOp->getOperand(0);
8329 if (LHS->getOpcode() == ISD::ZERO_EXTEND)
8330 WordVT = LHS->getOperand(0).getValueType();
8331 else if (LHS->getOpcode() == ISD::AssertZext)
8332 WordVT = cast<VTSDNode>(LHS->getOperand(1))->getVT();
8333 else
8334 return;
8335 // Find a replicating constant, e.g. 0x00010001.
8336 if (auto *C = dyn_cast<ConstantSDNode>(MulOp->getOperand(1))) {
8337 SystemZVectorConstantInfo VCI(
8338 APInt(MulVT.getSizeInBits(), C->getZExtValue()));
8339 if (VCI.isVectorConstantLegal(Subtarget) &&
8340 VCI.Opcode == SystemZISD::REPLICATE && VCI.OpVals[0] == 1 &&
8341 WordVT == VCI.VecVT.getScalarType())
8342 Word = DAG.getZExtOrTrunc(LHS->getOperand(0), SDLoc(SN), WordVT);
8343 }
8344 }
8345 };
8346
8347 if (isa<BuildVectorSDNode>(Op1) &&
8348 DAG.isSplatValue(Op1, true/*AllowUndefs*/)) {
8349 SDValue SplatVal = Op1->getOperand(0);
8350 if (auto *C = dyn_cast<ConstantSDNode>(SplatVal))
8351 FindReplicatedImm(C, SplatVal.getValueType().getStoreSize());
8352 else
8353 FindReplicatedReg(SplatVal);
8354 } else {
8355 if (auto *C = dyn_cast<ConstantSDNode>(Op1))
8356 FindReplicatedImm(C, MemVT.getStoreSize());
8357 else
8358 FindReplicatedReg(Op1);
8359 }
8360
8361 if (Word != SDValue()) {
8362 assert(MemVT.getSizeInBits() % WordVT.getSizeInBits() == 0 &&
8363 "Bad type handling");
8364 unsigned NumElts = MemVT.getSizeInBits() / WordVT.getSizeInBits();
8365 EVT SplatVT = EVT::getVectorVT(*DAG.getContext(), WordVT, NumElts);
8366 SDValue SplatVal = DAG.getSplatVector(SplatVT, SDLoc(SN), Word);
8367 return DAG.getStore(SN->getChain(), SDLoc(SN), SplatVal,
8368 SN->getBasePtr(), SN->getMemOperand());
8369 }
8370 }
8371
8372 return SDValue();
8373}
8374
8375SDValue SystemZTargetLowering::combineVECTOR_SHUFFLE(
8376 SDNode *N, DAGCombinerInfo &DCI) const {
8377 SelectionDAG &DAG = DCI.DAG;
8378 // Combine element-swap (LOAD) into VLER
8379 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8380 N->getOperand(0).hasOneUse() &&
8381 Subtarget.hasVectorEnhancements2()) {
8382 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8383 ArrayRef<int> ShuffleMask = SVN->getMask();
8384 if (isVectorElementSwap(ShuffleMask, N->getValueType(0))) {
8385 SDValue Load = N->getOperand(0);
8386 LoadSDNode *LD = cast<LoadSDNode>(Load);
8387
8388 // Create the element-swapping load.
8389 SDValue Ops[] = {
8390 LD->getChain(), // Chain
8391 LD->getBasePtr() // Ptr
8392 };
8393 SDValue ESLoad =
8394 DAG.getMemIntrinsicNode(SystemZISD::VLER, SDLoc(N),
8395 DAG.getVTList(LD->getValueType(0), MVT::Other),
8396 Ops, LD->getMemoryVT(), LD->getMemOperand());
8397
8398 // First, combine the VECTOR_SHUFFLE away. This makes the value produced
8399 // by the load dead.
8400 DCI.CombineTo(N, ESLoad);
8401
8402 // Next, combine the load away, we give it a bogus result value but a real
8403 // chain result. The result value is dead because the shuffle is dead.
8404 DCI.CombineTo(Load.getNode(), ESLoad, ESLoad.getValue(1));
8405
8406 // Return N so it doesn't get rechecked!
8407 return SDValue(N, 0);
8408 }
8409 }
8410
8411 return SDValue();
8412}
8413
8414SDValue SystemZTargetLowering::combineEXTRACT_VECTOR_ELT(
8415 SDNode *N, DAGCombinerInfo &DCI) const {
8416 SelectionDAG &DAG = DCI.DAG;
8417
8418 if (!Subtarget.hasVector())
8419 return SDValue();
8420
8421 // Look through bitcasts that retain the number of vector elements.
8422 SDValue Op = N->getOperand(0);
8423 if (Op.getOpcode() == ISD::BITCAST &&
8424 Op.getValueType().isVector() &&
8425 Op.getOperand(0).getValueType().isVector() &&
8426 Op.getValueType().getVectorNumElements() ==
8427 Op.getOperand(0).getValueType().getVectorNumElements())
8428 Op = Op.getOperand(0);
8429
8430 // Pull BSWAP out of a vector extraction.
8431 if (Op.getOpcode() == ISD::BSWAP && Op.hasOneUse()) {
8432 EVT VecVT = Op.getValueType();
8433 EVT EltVT = VecVT.getVectorElementType();
8434 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), EltVT,
8435 Op.getOperand(0), N->getOperand(1));
8436 DCI.AddToWorklist(Op.getNode());
8437 Op = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Op);
8438 if (EltVT != N->getValueType(0)) {
8439 DCI.AddToWorklist(Op.getNode());
8440 Op = DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Op);
8441 }
8442 return Op;
8443 }
8444
8445 // Try to simplify a vector extraction.
8446 if (auto *IndexN = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8447 SDValue Op0 = N->getOperand(0);
8448 EVT VecVT = Op0.getValueType();
8449 if (canTreatAsByteVector(VecVT))
8450 return combineExtract(SDLoc(N), N->getValueType(0), VecVT, Op0,
8451 IndexN->getZExtValue(), DCI, false);
8452 }
8453 return SDValue();
8454}
8455
8456SDValue SystemZTargetLowering::combineJOIN_DWORDS(
8457 SDNode *N, DAGCombinerInfo &DCI) const {
8458 SelectionDAG &DAG = DCI.DAG;
8459 // (join_dwords X, X) == (replicate X)
8460 if (N->getOperand(0) == N->getOperand(1))
8461 return DAG.getNode(SystemZISD::REPLICATE, SDLoc(N), N->getValueType(0),
8462 N->getOperand(0));
8463 return SDValue();
8464}
8465
8467 SDValue Chain1 = N1->getOperand(0);
8468 SDValue Chain2 = N2->getOperand(0);
8469
8470 // Trivial case: both nodes take the same chain.
8471 if (Chain1 == Chain2)
8472 return Chain1;
8473
8474 // FIXME - we could handle more complex cases via TokenFactor,
8475 // assuming we can verify that this would not create a cycle.
8476 return SDValue();
8477}
8478
8479SDValue SystemZTargetLowering::combineFP_ROUND(
8480 SDNode *N, DAGCombinerInfo &DCI) const {
8481
8482 if (!Subtarget.hasVector())
8483 return SDValue();
8484
8485 // (fpround (extract_vector_elt X 0))
8486 // (fpround (extract_vector_elt X 1)) ->
8487 // (extract_vector_elt (VROUND X) 0)
8488 // (extract_vector_elt (VROUND X) 2)
8489 //
8490 // This is a special case since the target doesn't really support v2f32s.
8491 unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0;
8492 SelectionDAG &DAG = DCI.DAG;
8493 SDValue Op0 = N->getOperand(OpNo);
8494 if (N->getValueType(0) == MVT::f32 && Op0.hasOneUse() &&
8496 Op0.getOperand(0).getValueType() == MVT::v2f64 &&
8497 Op0.getOperand(1).getOpcode() == ISD::Constant &&
8498 Op0.getConstantOperandVal(1) == 0) {
8499 SDValue Vec = Op0.getOperand(0);
8500 for (auto *U : Vec->users()) {
8501 if (U != Op0.getNode() && U->hasOneUse() &&
8502 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8503 U->getOperand(0) == Vec &&
8504 U->getOperand(1).getOpcode() == ISD::Constant &&
8505 U->getConstantOperandVal(1) == 1) {
8506 SDValue OtherRound = SDValue(*U->user_begin(), 0);
8507 if (OtherRound.getOpcode() == N->getOpcode() &&
8508 OtherRound.getOperand(OpNo) == SDValue(U, 0) &&
8509 OtherRound.getValueType() == MVT::f32) {
8510 SDValue VRound, Chain;
8511 if (N->isStrictFPOpcode()) {
8512 Chain = MergeInputChains(N, OtherRound.getNode());
8513 if (!Chain)
8514 continue;
8515 VRound = DAG.getNode(SystemZISD::STRICT_VROUND, SDLoc(N),
8516 {MVT::v4f32, MVT::Other}, {Chain, Vec});
8517 Chain = VRound.getValue(1);
8518 } else
8519 VRound = DAG.getNode(SystemZISD::VROUND, SDLoc(N),
8520 MVT::v4f32, Vec);
8521 DCI.AddToWorklist(VRound.getNode());
8522 SDValue Extract1 =
8523 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f32,
8524 VRound, DAG.getConstant(2, SDLoc(U), MVT::i32));
8525 DCI.AddToWorklist(Extract1.getNode());
8526 DAG.ReplaceAllUsesOfValueWith(OtherRound, Extract1);
8527 if (Chain)
8528 DAG.ReplaceAllUsesOfValueWith(OtherRound.getValue(1), Chain);
8529 SDValue Extract0 =
8530 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f32,
8531 VRound, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
8532 if (Chain)
8533 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0),
8534 N->getVTList(), Extract0, Chain);
8535 return Extract0;
8536 }
8537 }
8538 }
8539 }
8540 return SDValue();
8541}
8542
8543SDValue SystemZTargetLowering::combineFP_EXTEND(
8544 SDNode *N, DAGCombinerInfo &DCI) const {
8545
8546 if (!Subtarget.hasVector())
8547 return SDValue();
8548
8549 // (fpextend (extract_vector_elt X 0))
8550 // (fpextend (extract_vector_elt X 2)) ->
8551 // (extract_vector_elt (VEXTEND X) 0)
8552 // (extract_vector_elt (VEXTEND X) 1)
8553 //
8554 // This is a special case since the target doesn't really support v2f32s.
8555 unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0;
8556 SelectionDAG &DAG = DCI.DAG;
8557 SDValue Op0 = N->getOperand(OpNo);
8558 if (N->getValueType(0) == MVT::f64 && Op0.hasOneUse() &&
8560 Op0.getOperand(0).getValueType() == MVT::v4f32 &&
8561 Op0.getOperand(1).getOpcode() == ISD::Constant &&
8562 Op0.getConstantOperandVal(1) == 0) {
8563 SDValue Vec = Op0.getOperand(0);
8564 for (auto *U : Vec->users()) {
8565 if (U != Op0.getNode() && U->hasOneUse() &&
8566 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8567 U->getOperand(0) == Vec &&
8568 U->getOperand(1).getOpcode() == ISD::Constant &&
8569 U->getConstantOperandVal(1) == 2) {
8570 SDValue OtherExtend = SDValue(*U->user_begin(), 0);
8571 if (OtherExtend.getOpcode() == N->getOpcode() &&
8572 OtherExtend.getOperand(OpNo) == SDValue(U, 0) &&
8573 OtherExtend.getValueType() == MVT::f64) {
8574 SDValue VExtend, Chain;
8575 if (N->isStrictFPOpcode()) {
8576 Chain = MergeInputChains(N, OtherExtend.getNode());
8577 if (!Chain)
8578 continue;
8579 VExtend = DAG.getNode(SystemZISD::STRICT_VEXTEND, SDLoc(N),
8580 {MVT::v2f64, MVT::Other}, {Chain, Vec});
8581 Chain = VExtend.getValue(1);
8582 } else
8583 VExtend = DAG.getNode(SystemZISD::VEXTEND, SDLoc(N),
8584 MVT::v2f64, Vec);
8585 DCI.AddToWorklist(VExtend.getNode());
8586 SDValue Extract1 =
8587 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f64,
8588 VExtend, DAG.getConstant(1, SDLoc(U), MVT::i32));
8589 DCI.AddToWorklist(Extract1.getNode());
8590 DAG.ReplaceAllUsesOfValueWith(OtherExtend, Extract1);
8591 if (Chain)
8592 DAG.ReplaceAllUsesOfValueWith(OtherExtend.getValue(1), Chain);
8593 SDValue Extract0 =
8594 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f64,
8595 VExtend, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
8596 if (Chain)
8597 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0),
8598 N->getVTList(), Extract0, Chain);
8599 return Extract0;
8600 }
8601 }
8602 }
8603 }
8604 return SDValue();
8605}
8606
8607SDValue SystemZTargetLowering::combineINT_TO_FP(
8608 SDNode *N, DAGCombinerInfo &DCI) const {
8609 if (DCI.Level != BeforeLegalizeTypes)
8610 return SDValue();
8611 SelectionDAG &DAG = DCI.DAG;
8612 LLVMContext &Ctx = *DAG.getContext();
8613 unsigned Opcode = N->getOpcode();
8614 EVT OutVT = N->getValueType(0);
8615 Type *OutLLVMTy = OutVT.getTypeForEVT(Ctx);
8616 SDValue Op = N->getOperand(0);
8617 unsigned OutScalarBits = OutLLVMTy->getScalarSizeInBits();
8618 unsigned InScalarBits = Op->getValueType(0).getScalarSizeInBits();
8619
8620 // Insert an extension before type-legalization to avoid scalarization, e.g.:
8621 // v2f64 = uint_to_fp v2i16
8622 // =>
8623 // v2f64 = uint_to_fp (v2i64 zero_extend v2i16)
8624 if (OutLLVMTy->isVectorTy() && OutScalarBits > InScalarBits &&
8625 OutScalarBits <= 64) {
8626 unsigned NumElts = cast<FixedVectorType>(OutLLVMTy)->getNumElements();
8627 EVT ExtVT = EVT::getVectorVT(
8628 Ctx, EVT::getIntegerVT(Ctx, OutLLVMTy->getScalarSizeInBits()), NumElts);
8629 unsigned ExtOpcode =
8631 SDValue ExtOp = DAG.getNode(ExtOpcode, SDLoc(N), ExtVT, Op);
8632 return DAG.getNode(Opcode, SDLoc(N), OutVT, ExtOp);
8633 }
8634 return SDValue();
8635}
8636
8637SDValue SystemZTargetLowering::combineFCOPYSIGN(
8638 SDNode *N, DAGCombinerInfo &DCI) const {
8639 SelectionDAG &DAG = DCI.DAG;
8640 EVT VT = N->getValueType(0);
8641 SDValue ValOp = N->getOperand(0);
8642 SDValue SignOp = N->getOperand(1);
8643
8644 // Remove the rounding which is not needed.
8645 if (SignOp.getOpcode() == ISD::FP_ROUND) {
8646 SDValue WideOp = SignOp.getOperand(0);
8647 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, ValOp, WideOp);
8648 }
8649
8650 return SDValue();
8651}
8652
8653SDValue SystemZTargetLowering::combineBSWAP(
8654 SDNode *N, DAGCombinerInfo &DCI) const {
8655 SelectionDAG &DAG = DCI.DAG;
8656 // Combine BSWAP (LOAD) into LRVH/LRV/LRVG/VLBR
8657 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8658 N->getOperand(0).hasOneUse() &&
8659 canLoadStoreByteSwapped(N->getValueType(0))) {
8660 SDValue Load = N->getOperand(0);
8661 LoadSDNode *LD = cast<LoadSDNode>(Load);
8662
8663 // Create the byte-swapping load.
8664 SDValue Ops[] = {
8665 LD->getChain(), // Chain
8666 LD->getBasePtr() // Ptr
8667 };
8668 EVT LoadVT = N->getValueType(0);
8669 if (LoadVT == MVT::i16)
8670 LoadVT = MVT::i32;
8671 SDValue BSLoad =
8672 DAG.getMemIntrinsicNode(SystemZISD::LRV, SDLoc(N),
8673 DAG.getVTList(LoadVT, MVT::Other),
8674 Ops, LD->getMemoryVT(), LD->getMemOperand());
8675
8676 // If this is an i16 load, insert the truncate.
8677 SDValue ResVal = BSLoad;
8678 if (N->getValueType(0) == MVT::i16)
8679 ResVal = DAG.getNode(ISD::TRUNCATE, SDLoc(N), MVT::i16, BSLoad);
8680
8681 // First, combine the bswap away. This makes the value produced by the
8682 // load dead.
8683 DCI.CombineTo(N, ResVal);
8684
8685 // Next, combine the load away, we give it a bogus result value but a real
8686 // chain result. The result value is dead because the bswap is dead.
8687 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8688
8689 // Return N so it doesn't get rechecked!
8690 return SDValue(N, 0);
8691 }
8692
8693 // Look through bitcasts that retain the number of vector elements.
8694 SDValue Op = N->getOperand(0);
8695 if (Op.getOpcode() == ISD::BITCAST &&
8696 Op.getValueType().isVector() &&
8697 Op.getOperand(0).getValueType().isVector() &&
8698 Op.getValueType().getVectorNumElements() ==
8699 Op.getOperand(0).getValueType().getVectorNumElements())
8700 Op = Op.getOperand(0);
8701
8702 // Push BSWAP into a vector insertion if at least one side then simplifies.
8703 if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT && Op.hasOneUse()) {
8704 SDValue Vec = Op.getOperand(0);
8705 SDValue Elt = Op.getOperand(1);
8706 SDValue Idx = Op.getOperand(2);
8707
8709 Vec.getOpcode() == ISD::BSWAP || Vec.isUndef() ||
8711 Elt.getOpcode() == ISD::BSWAP || Elt.isUndef() ||
8712 (canLoadStoreByteSwapped(N->getValueType(0)) &&
8713 ISD::isNON_EXTLoad(Elt.getNode()) && Elt.hasOneUse())) {
8714 EVT VecVT = N->getValueType(0);
8715 EVT EltVT = N->getValueType(0).getVectorElementType();
8716 if (VecVT != Vec.getValueType()) {
8717 Vec = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Vec);
8718 DCI.AddToWorklist(Vec.getNode());
8719 }
8720 if (EltVT != Elt.getValueType()) {
8721 Elt = DAG.getNode(ISD::BITCAST, SDLoc(N), EltVT, Elt);
8722 DCI.AddToWorklist(Elt.getNode());
8723 }
8724 Vec = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Vec);
8725 DCI.AddToWorklist(Vec.getNode());
8726 Elt = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Elt);
8727 DCI.AddToWorklist(Elt.getNode());
8728 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VecVT,
8729 Vec, Elt, Idx);
8730 }
8731 }
8732
8733 // Push BSWAP into a vector shuffle if at least one side then simplifies.
8734 ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(Op);
8735 if (SV && Op.hasOneUse()) {
8736 SDValue Op0 = Op.getOperand(0);
8737 SDValue Op1 = Op.getOperand(1);
8738
8740 Op0.getOpcode() == ISD::BSWAP || Op0.isUndef() ||
8742 Op1.getOpcode() == ISD::BSWAP || Op1.isUndef()) {
8743 EVT VecVT = N->getValueType(0);
8744 if (VecVT != Op0.getValueType()) {
8745 Op0 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op0);
8746 DCI.AddToWorklist(Op0.getNode());
8747 }
8748 if (VecVT != Op1.getValueType()) {
8749 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op1);
8750 DCI.AddToWorklist(Op1.getNode());
8751 }
8752 Op0 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op0);
8753 DCI.AddToWorklist(Op0.getNode());
8754 Op1 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op1);
8755 DCI.AddToWorklist(Op1.getNode());
8756 return DAG.getVectorShuffle(VecVT, SDLoc(N), Op0, Op1, SV->getMask());
8757 }
8758 }
8759
8760 return SDValue();
8761}
8762
8763SDValue SystemZTargetLowering::combineSETCC(
8764 SDNode *N, DAGCombinerInfo &DCI) const {
8765 SelectionDAG &DAG = DCI.DAG;
8766 const ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
8767 const SDValue LHS = N->getOperand(0);
8768 const SDValue RHS = N->getOperand(1);
8769 bool CmpNull = isNullConstant(RHS);
8770 bool CmpAllOnes = isAllOnesConstant(RHS);
8771 EVT VT = N->getValueType(0);
8772 SDLoc DL(N);
8773
8774 // Match icmp_eq/ne(bitcast(icmp(X,Y)),0/-1) reduction patterns, and
8775 // change the outer compare to a i128 compare. This will normally
8776 // allow the reduction to be recognized in adjustICmp128, and even if
8777 // not, the i128 compare will still generate better code.
8778 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && (CmpNull || CmpAllOnes)) {
8779 SDValue Src = peekThroughBitcasts(LHS);
8780 if (Src.getOpcode() == ISD::SETCC &&
8781 Src.getValueType().isFixedLengthVector() &&
8782 Src.getValueType().getScalarType() == MVT::i1) {
8783 EVT CmpVT = Src.getOperand(0).getValueType();
8784 if (CmpVT.getSizeInBits() == 128) {
8785 EVT IntVT = CmpVT.changeVectorElementTypeToInteger();
8786 SDValue LHS =
8787 DAG.getBitcast(MVT::i128, DAG.getSExtOrTrunc(Src, DL, IntVT));
8788 SDValue RHS = CmpNull ? DAG.getConstant(0, DL, MVT::i128)
8789 : DAG.getAllOnesConstant(DL, MVT::i128);
8790 return DAG.getNode(ISD::SETCC, DL, VT, LHS, RHS, N->getOperand(2),
8791 N->getFlags());
8792 }
8793 }
8794 }
8795
8796 return SDValue();
8797}
8798
8799static std::pair<SDValue, int> findCCUse(const SDValue &Val,
8800 unsigned Depth = 0) {
8801 // Limit depth of potentially exponential walk.
8802 if (Depth > 5)
8803 return std::make_pair(SDValue(), SystemZ::CCMASK_NONE);
8804
8805 switch (Val.getOpcode()) {
8806 default:
8807 return std::make_pair(SDValue(), SystemZ::CCMASK_NONE);
8808 case SystemZISD::IPM:
8809 if (Val.getOperand(0).getOpcode() == SystemZISD::CLC ||
8810 Val.getOperand(0).getOpcode() == SystemZISD::STRCMP)
8811 return std::make_pair(Val.getOperand(0), SystemZ::CCMASK_ICMP);
8812 return std::make_pair(Val.getOperand(0), SystemZ::CCMASK_ANY);
8813 case SystemZISD::SELECT_CCMASK: {
8814 SDValue Op4CCReg = Val.getOperand(4);
8815 if (Op4CCReg.getOpcode() == SystemZISD::ICMP ||
8816 Op4CCReg.getOpcode() == SystemZISD::TM) {
8817 auto [OpCC, OpCCValid] = findCCUse(Op4CCReg.getOperand(0), Depth + 1);
8818 if (OpCC != SDValue())
8819 return std::make_pair(OpCC, OpCCValid);
8820 }
8821 auto *CCValid = dyn_cast<ConstantSDNode>(Val.getOperand(2));
8822 if (!CCValid)
8823 return std::make_pair(SDValue(), SystemZ::CCMASK_NONE);
8824 int CCValidVal = CCValid->getZExtValue();
8825 return std::make_pair(Op4CCReg, CCValidVal);
8826 }
8827 case ISD::ADD:
8828 case ISD::AND:
8829 case ISD::OR:
8830 case ISD::XOR:
8831 case ISD::SHL:
8832 case ISD::SRA:
8833 case ISD::SRL:
8834 auto [Op0CC, Op0CCValid] = findCCUse(Val.getOperand(0), Depth + 1);
8835 if (Op0CC != SDValue())
8836 return std::make_pair(Op0CC, Op0CCValid);
8837 return findCCUse(Val.getOperand(1), Depth + 1);
8838 }
8839}
8840
8841static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask,
8842 SelectionDAG &DAG);
8843
8845 SelectionDAG &DAG) {
8846 SDLoc DL(Val);
8847 auto Opcode = Val.getOpcode();
8848 switch (Opcode) {
8849 default:
8850 return {};
8851 case ISD::Constant:
8852 return {Val, Val, Val, Val};
8853 case SystemZISD::IPM: {
8854 SDValue IPMOp0 = Val.getOperand(0);
8855 if (IPMOp0 != CC)
8856 return {};
8857 SmallVector<SDValue, 4> ShiftedCCVals;
8858 for (auto CC : {0, 1, 2, 3})
8859 ShiftedCCVals.emplace_back(
8860 DAG.getConstant((CC << SystemZ::IPM_CC), DL, MVT::i32));
8861 return ShiftedCCVals;
8862 }
8863 case SystemZISD::SELECT_CCMASK: {
8864 SDValue TrueVal = Val.getOperand(0), FalseVal = Val.getOperand(1);
8865 auto *CCValid = dyn_cast<ConstantSDNode>(Val.getOperand(2));
8866 auto *CCMask = dyn_cast<ConstantSDNode>(Val.getOperand(3));
8867 if (!CCValid || !CCMask)
8868 return {};
8869
8870 int CCValidVal = CCValid->getZExtValue();
8871 int CCMaskVal = CCMask->getZExtValue();
8872 // Pruning search tree early - Moving CC test and combineCCMask ahead of
8873 // recursive call to simplifyAssumingCCVal.
8874 SDValue Op4CCReg = Val.getOperand(4);
8875 if (Op4CCReg != CC)
8876 combineCCMask(Op4CCReg, CCValidVal, CCMaskVal, DAG);
8877 if (Op4CCReg != CC)
8878 return {};
8879 const auto &&TrueSDVals = simplifyAssumingCCVal(TrueVal, CC, DAG);
8880 const auto &&FalseSDVals = simplifyAssumingCCVal(FalseVal, CC, DAG);
8881 if (TrueSDVals.empty() || FalseSDVals.empty())
8882 return {};
8883 SmallVector<SDValue, 4> MergedSDVals;
8884 for (auto &CCVal : {0, 1, 2, 3})
8885 MergedSDVals.emplace_back(((CCMaskVal & (1 << (3 - CCVal))) != 0)
8886 ? TrueSDVals[CCVal]
8887 : FalseSDVals[CCVal]);
8888 return MergedSDVals;
8889 }
8890 case ISD::ADD:
8891 case ISD::AND:
8892 case ISD::OR:
8893 case ISD::XOR:
8894 case ISD::SRA:
8895 // Avoid introducing CC spills (because ADD/AND/OR/XOR/SRA
8896 // would clobber CC).
8897 if (!Val.hasOneUse())
8898 return {};
8899 [[fallthrough]];
8900 case ISD::SHL:
8901 case ISD::SRL:
8902 SDValue Op0 = Val.getOperand(0), Op1 = Val.getOperand(1);
8903 const auto &&Op0SDVals = simplifyAssumingCCVal(Op0, CC, DAG);
8904 const auto &&Op1SDVals = simplifyAssumingCCVal(Op1, CC, DAG);
8905 if (Op0SDVals.empty() || Op1SDVals.empty())
8906 return {};
8907 SmallVector<SDValue, 4> BinaryOpSDVals;
8908 for (auto CCVal : {0, 1, 2, 3})
8909 BinaryOpSDVals.emplace_back(DAG.getNode(
8910 Opcode, DL, Val.getValueType(), Op0SDVals[CCVal], Op1SDVals[CCVal]));
8911 return BinaryOpSDVals;
8912 }
8913}
8914
8915static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask,
8916 SelectionDAG &DAG) {
8917 // We have a SELECT_CCMASK or BR_CCMASK comparing the condition code
8918 // set by the CCReg instruction using the CCValid / CCMask masks,
8919 // If the CCReg instruction is itself a ICMP / TM testing the condition
8920 // code set by some other instruction, see whether we can directly
8921 // use that condition code.
8922 auto *CCNode = CCReg.getNode();
8923 if (!CCNode)
8924 return false;
8925
8926 if (CCNode->getOpcode() == SystemZISD::TM) {
8927 if (CCValid != SystemZ::CCMASK_TM)
8928 return false;
8929 auto emulateTMCCMask = [](const SDValue &Op0Val, const SDValue &Op1Val) {
8930 auto *Op0Node = dyn_cast<ConstantSDNode>(Op0Val.getNode());
8931 auto *Op1Node = dyn_cast<ConstantSDNode>(Op1Val.getNode());
8932 if (!Op0Node || !Op1Node)
8933 return -1;
8934 auto Op0APVal = Op0Node->getAPIntValue();
8935 auto Op1APVal = Op1Node->getAPIntValue();
8936 auto Result = Op0APVal & Op1APVal;
8937 bool AllOnes = Result == Op1APVal;
8938 bool AllZeros = Result == 0;
8939 bool IsLeftMostBitSet = Result[Op1APVal.getActiveBits() - 1] != 0;
8940 return AllZeros ? 0 : AllOnes ? 3 : IsLeftMostBitSet ? 2 : 1;
8941 };
8942 SDValue Op0 = CCNode->getOperand(0);
8943 SDValue Op1 = CCNode->getOperand(1);
8944 auto [Op0CC, Op0CCValid] = findCCUse(Op0);
8945 if (Op0CC == SDValue())
8946 return false;
8947 const auto &&Op0SDVals = simplifyAssumingCCVal(Op0, Op0CC, DAG);
8948 const auto &&Op1SDVals = simplifyAssumingCCVal(Op1, Op0CC, DAG);
8949 if (Op0SDVals.empty() || Op1SDVals.empty())
8950 return false;
8951 int NewCCMask = 0;
8952 for (auto CC : {0, 1, 2, 3}) {
8953 auto CCVal = emulateTMCCMask(Op0SDVals[CC], Op1SDVals[CC]);
8954 if (CCVal < 0)
8955 return false;
8956 NewCCMask <<= 1;
8957 NewCCMask |= (CCMask & (1 << (3 - CCVal))) != 0;
8958 }
8959 NewCCMask &= Op0CCValid;
8960 CCReg = Op0CC;
8961 CCMask = NewCCMask;
8962 CCValid = Op0CCValid;
8963 return true;
8964 }
8965 if (CCNode->getOpcode() != SystemZISD::ICMP ||
8966 CCValid != SystemZ::CCMASK_ICMP)
8967 return false;
8968
8969 SDValue CmpOp0 = CCNode->getOperand(0);
8970 SDValue CmpOp1 = CCNode->getOperand(1);
8971 SDValue CmpOp2 = CCNode->getOperand(2);
8972 auto [Op0CC, Op0CCValid] = findCCUse(CmpOp0);
8973 if (Op0CC != SDValue()) {
8974 const auto &&Op0SDVals = simplifyAssumingCCVal(CmpOp0, Op0CC, DAG);
8975 const auto &&Op1SDVals = simplifyAssumingCCVal(CmpOp1, Op0CC, DAG);
8976 if (Op0SDVals.empty() || Op1SDVals.empty())
8977 return false;
8978
8979 auto *CmpType = dyn_cast<ConstantSDNode>(CmpOp2);
8980 auto CmpTypeVal = CmpType->getZExtValue();
8981 const auto compareCCSigned = [&CmpTypeVal](const SDValue &Op0Val,
8982 const SDValue &Op1Val) {
8983 auto *Op0Node = dyn_cast<ConstantSDNode>(Op0Val.getNode());
8984 auto *Op1Node = dyn_cast<ConstantSDNode>(Op1Val.getNode());
8985 if (!Op0Node || !Op1Node)
8986 return -1;
8987 auto Op0APVal = Op0Node->getAPIntValue();
8988 auto Op1APVal = Op1Node->getAPIntValue();
8989 if (CmpTypeVal == SystemZICMP::SignedOnly)
8990 return Op0APVal == Op1APVal ? 0 : Op0APVal.slt(Op1APVal) ? 1 : 2;
8991 return Op0APVal == Op1APVal ? 0 : Op0APVal.ult(Op1APVal) ? 1 : 2;
8992 };
8993 int NewCCMask = 0;
8994 for (auto CC : {0, 1, 2, 3}) {
8995 auto CCVal = compareCCSigned(Op0SDVals[CC], Op1SDVals[CC]);
8996 if (CCVal < 0)
8997 return false;
8998 NewCCMask <<= 1;
8999 NewCCMask |= (CCMask & (1 << (3 - CCVal))) != 0;
9000 }
9001 NewCCMask &= Op0CCValid;
9002 CCMask = NewCCMask;
9003 CCReg = Op0CC;
9004 CCValid = Op0CCValid;
9005 return true;
9006 }
9007
9008 return false;
9009}
9010
9011// Merging versus split in multiple branches cost.
9014 const Value *Lhs,
9015 const Value *Rhs,
9016 const Function *) const {
9017 const auto isFlagOutOpCC = [](const Value *V) {
9018 using namespace llvm::PatternMatch;
9019 const Value *RHSVal;
9020 const APInt *RHSC;
9021 if (const auto *I = dyn_cast<Instruction>(V)) {
9022 // PatternMatch.h provides concise tree-based pattern match of llvm IR.
9023 if (match(I->getOperand(0), m_And(m_Value(RHSVal), m_APInt(RHSC))) ||
9024 match(I, m_Cmp(m_Value(RHSVal), m_APInt(RHSC)))) {
9025 if (const auto *CB = dyn_cast<CallBase>(RHSVal)) {
9026 if (CB->isInlineAsm()) {
9027 const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
9028 return IA && IA->getConstraintString().contains("{@cc}");
9029 }
9030 }
9031 }
9032 }
9033 return false;
9034 };
9035 // Pattern (ICmp %asm) or (ICmp (And %asm)).
9036 // Cost of longest dependency chain (ICmp, And) is 2. CostThreshold or
9037 // BaseCost can be set >=2. If cost of instruction <= CostThreshold
9038 // conditionals will be merged or else conditionals will be split.
9039 if (isFlagOutOpCC(Lhs) && isFlagOutOpCC(Rhs))
9040 return {3, 0, -1};
9041 // Default.
9042 return {-1, -1, -1};
9043}
9044
9045SDValue SystemZTargetLowering::combineBR_CCMASK(SDNode *N,
9046 DAGCombinerInfo &DCI) const {
9047 SelectionDAG &DAG = DCI.DAG;
9048
9049 // Combine BR_CCMASK (ICMP (SELECT_CCMASK)) into a single BR_CCMASK.
9050 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1));
9051 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2));
9052 if (!CCValid || !CCMask)
9053 return SDValue();
9054
9055 int CCValidVal = CCValid->getZExtValue();
9056 int CCMaskVal = CCMask->getZExtValue();
9057 SDValue Chain = N->getOperand(0);
9058 SDValue CCReg = N->getOperand(4);
9059 // If combineCMask was able to merge or simplify ccvalid or ccmask, re-emit
9060 // the modified BR_CCMASK with the new values.
9061 // In order to avoid conditional branches with full or empty cc masks, do not
9062 // do this if ccmask is 0 or equal to ccvalid.
9063 if (combineCCMask(CCReg, CCValidVal, CCMaskVal, DAG) && CCMaskVal != 0 &&
9064 CCMaskVal != CCValidVal)
9065 return DAG.getNode(SystemZISD::BR_CCMASK, SDLoc(N), N->getValueType(0),
9066 Chain,
9067 DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32),
9068 DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32),
9069 N->getOperand(3), CCReg);
9070 return SDValue();
9071}
9072
9073SDValue SystemZTargetLowering::combineSELECT_CCMASK(
9074 SDNode *N, DAGCombinerInfo &DCI) const {
9075 SelectionDAG &DAG = DCI.DAG;
9076
9077 // Combine SELECT_CCMASK (ICMP (SELECT_CCMASK)) into a single SELECT_CCMASK.
9078 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(2));
9079 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(3));
9080 if (!CCValid || !CCMask)
9081 return SDValue();
9082
9083 int CCValidVal = CCValid->getZExtValue();
9084 int CCMaskVal = CCMask->getZExtValue();
9085 SDValue CCReg = N->getOperand(4);
9086
9087 bool IsCombinedCCReg = combineCCMask(CCReg, CCValidVal, CCMaskVal, DAG);
9088
9089 // Populate SDVals vector for each condition code ccval for given Val, which
9090 // can again be another nested select_ccmask with the same CC.
9091 const auto constructCCSDValsFromSELECT = [&CCReg](SDValue &Val) {
9092 if (Val.getOpcode() == SystemZISD::SELECT_CCMASK) {
9094 if (Val.getOperand(4) != CCReg)
9095 return SmallVector<SDValue, 4>{};
9096 SDValue TrueVal = Val.getOperand(0), FalseVal = Val.getOperand(1);
9097 auto *CCMask = dyn_cast<ConstantSDNode>(Val.getOperand(3));
9098 if (!CCMask)
9099 return SmallVector<SDValue, 4>{};
9100
9101 int CCMaskVal = CCMask->getZExtValue();
9102 for (auto &CC : {0, 1, 2, 3})
9103 Res.emplace_back(((CCMaskVal & (1 << (3 - CC))) != 0) ? TrueVal
9104 : FalseVal);
9105 return Res;
9106 }
9107 return SmallVector<SDValue, 4>{Val, Val, Val, Val};
9108 };
9109 // Attempting to optimize TrueVal/FalseVal in outermost select_ccmask either
9110 // with CCReg found by combineCCMask or original CCReg.
9111 SDValue TrueVal = N->getOperand(0);
9112 SDValue FalseVal = N->getOperand(1);
9113 auto &&TrueSDVals = simplifyAssumingCCVal(TrueVal, CCReg, DAG);
9114 auto &&FalseSDVals = simplifyAssumingCCVal(FalseVal, CCReg, DAG);
9115 // TrueSDVals/FalseSDVals might be empty in case of non-constant
9116 // TrueVal/FalseVal for select_ccmask, which can not be optimized further.
9117 if (TrueSDVals.empty())
9118 TrueSDVals = constructCCSDValsFromSELECT(TrueVal);
9119 if (FalseSDVals.empty())
9120 FalseSDVals = constructCCSDValsFromSELECT(FalseVal);
9121 if (!TrueSDVals.empty() && !FalseSDVals.empty()) {
9122 SmallSet<SDValue, 4> MergedSDValsSet;
9123 // Ignoring CC values outside CCValiid.
9124 for (auto CC : {0, 1, 2, 3}) {
9125 if ((CCValidVal & ((1 << (3 - CC)))) != 0)
9126 MergedSDValsSet.insert(((CCMaskVal & (1 << (3 - CC))) != 0)
9127 ? TrueSDVals[CC]
9128 : FalseSDVals[CC]);
9129 }
9130 if (MergedSDValsSet.size() == 1)
9131 return *MergedSDValsSet.begin();
9132 if (MergedSDValsSet.size() == 2) {
9133 auto BeginIt = MergedSDValsSet.begin();
9134 SDValue NewTrueVal = *BeginIt, NewFalseVal = *next(BeginIt);
9135 if (NewTrueVal == FalseVal || NewFalseVal == TrueVal)
9136 std::swap(NewTrueVal, NewFalseVal);
9137 int NewCCMask = 0;
9138 for (auto CC : {0, 1, 2, 3}) {
9139 NewCCMask <<= 1;
9140 NewCCMask |= ((CCMaskVal & (1 << (3 - CC))) != 0)
9141 ? (TrueSDVals[CC] == NewTrueVal)
9142 : (FalseSDVals[CC] == NewTrueVal);
9143 }
9144 CCMaskVal = NewCCMask;
9145 CCMaskVal &= CCValidVal;
9146 TrueVal = NewTrueVal;
9147 FalseVal = NewFalseVal;
9148 IsCombinedCCReg = true;
9149 }
9150 }
9151 // If the condition is trivially false or trivially true after
9152 // combineCCMask, just collapse this SELECT_CCMASK to the indicated value
9153 // (possibly modified by constructCCSDValsFromSELECT).
9154 if (CCMaskVal == 0)
9155 return FalseVal;
9156 if (CCMaskVal == CCValidVal)
9157 return TrueVal;
9158
9159 if (IsCombinedCCReg)
9160 return DAG.getNode(
9161 SystemZISD::SELECT_CCMASK, SDLoc(N), N->getValueType(0), TrueVal,
9162 FalseVal, DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32),
9163 DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32), CCReg);
9164
9165 return SDValue();
9166}
9167
9168SDValue SystemZTargetLowering::combineGET_CCMASK(
9169 SDNode *N, DAGCombinerInfo &DCI) const {
9170
9171 // Optimize away GET_CCMASK (SELECT_CCMASK) if the CC masks are compatible
9172 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1));
9173 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2));
9174 if (!CCValid || !CCMask)
9175 return SDValue();
9176 int CCValidVal = CCValid->getZExtValue();
9177 int CCMaskVal = CCMask->getZExtValue();
9178
9179 SDValue Select = N->getOperand(0);
9180 if (Select->getOpcode() == ISD::TRUNCATE)
9181 Select = Select->getOperand(0);
9182 if (Select->getOpcode() != SystemZISD::SELECT_CCMASK)
9183 return SDValue();
9184
9185 auto *SelectCCValid = dyn_cast<ConstantSDNode>(Select->getOperand(2));
9186 auto *SelectCCMask = dyn_cast<ConstantSDNode>(Select->getOperand(3));
9187 if (!SelectCCValid || !SelectCCMask)
9188 return SDValue();
9189 int SelectCCValidVal = SelectCCValid->getZExtValue();
9190 int SelectCCMaskVal = SelectCCMask->getZExtValue();
9191
9192 auto *TrueVal = dyn_cast<ConstantSDNode>(Select->getOperand(0));
9193 auto *FalseVal = dyn_cast<ConstantSDNode>(Select->getOperand(1));
9194 if (!TrueVal || !FalseVal)
9195 return SDValue();
9196 if (TrueVal->getZExtValue() == 1 && FalseVal->getZExtValue() == 0)
9197 ;
9198 else if (TrueVal->getZExtValue() == 0 && FalseVal->getZExtValue() == 1)
9199 SelectCCMaskVal ^= SelectCCValidVal;
9200 else
9201 return SDValue();
9202
9203 if (SelectCCValidVal & ~CCValidVal)
9204 return SDValue();
9205 if (SelectCCMaskVal != (CCMaskVal & SelectCCValidVal))
9206 return SDValue();
9207
9208 return Select->getOperand(4);
9209}
9210
9211SDValue SystemZTargetLowering::combineIntDIVREM(
9212 SDNode *N, DAGCombinerInfo &DCI) const {
9213 SelectionDAG &DAG = DCI.DAG;
9214 EVT VT = N->getValueType(0);
9215 // In the case where the divisor is a vector of constants a cheaper
9216 // sequence of instructions can replace the divide. BuildSDIV is called to
9217 // do this during DAG combining, but it only succeeds when it can build a
9218 // multiplication node. The only option for SystemZ is ISD::SMUL_LOHI, and
9219 // since it is not Legal but Custom it can only happen before
9220 // legalization. Therefore we must scalarize this early before Combine
9221 // 1. For widened vectors, this is already the result of type legalization.
9222 if (DCI.Level == BeforeLegalizeTypes && VT.isVector() && isTypeLegal(VT) &&
9223 DAG.isConstantIntBuildVectorOrConstantInt(N->getOperand(1)))
9224 return DAG.UnrollVectorOp(N);
9225 return SDValue();
9226}
9227
9228
9229// Transform a right shift of a multiply-and-add into a multiply-and-add-high.
9230// This is closely modeled after the common-code combineShiftToMULH.
9231SDValue SystemZTargetLowering::combineShiftToMulAddHigh(
9232 SDNode *N, DAGCombinerInfo &DCI) const {
9233 SelectionDAG &DAG = DCI.DAG;
9234 SDLoc DL(N);
9235
9236 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
9237 "SRL or SRA node is required here!");
9238
9239 if (!Subtarget.hasVector())
9240 return SDValue();
9241
9242 // Check the shift amount. Proceed with the transformation if the shift
9243 // amount is constant.
9244 ConstantSDNode *ShiftAmtSrc = isConstOrConstSplat(N->getOperand(1));
9245 if (!ShiftAmtSrc)
9246 return SDValue();
9247
9248 // The operation feeding into the shift must be an add.
9249 SDValue ShiftOperand = N->getOperand(0);
9250 if (ShiftOperand.getOpcode() != ISD::ADD)
9251 return SDValue();
9252
9253 // One operand of the add must be a multiply.
9254 SDValue MulOp = ShiftOperand.getOperand(0);
9255 SDValue AddOp = ShiftOperand.getOperand(1);
9256 if (MulOp.getOpcode() != ISD::MUL) {
9257 if (AddOp.getOpcode() != ISD::MUL)
9258 return SDValue();
9259 std::swap(MulOp, AddOp);
9260 }
9261
9262 // All operands must be equivalent extend nodes.
9263 SDValue LeftOp = MulOp.getOperand(0);
9264 SDValue RightOp = MulOp.getOperand(1);
9265
9266 bool IsSignExt = LeftOp.getOpcode() == ISD::SIGN_EXTEND;
9267 bool IsZeroExt = LeftOp.getOpcode() == ISD::ZERO_EXTEND;
9268
9269 if (!IsSignExt && !IsZeroExt)
9270 return SDValue();
9271
9272 EVT NarrowVT = LeftOp.getOperand(0).getValueType();
9273 unsigned NarrowVTSize = NarrowVT.getScalarSizeInBits();
9274
9275 SDValue MulhRightOp;
9276 if (ConstantSDNode *Constant = isConstOrConstSplat(RightOp)) {
9277 unsigned ActiveBits = IsSignExt
9278 ? Constant->getAPIntValue().getSignificantBits()
9279 : Constant->getAPIntValue().getActiveBits();
9280 if (ActiveBits > NarrowVTSize)
9281 return SDValue();
9282 MulhRightOp = DAG.getConstant(
9283 Constant->getAPIntValue().trunc(NarrowVT.getScalarSizeInBits()), DL,
9284 NarrowVT);
9285 } else {
9286 if (LeftOp.getOpcode() != RightOp.getOpcode())
9287 return SDValue();
9288 // Check that the two extend nodes are the same type.
9289 if (NarrowVT != RightOp.getOperand(0).getValueType())
9290 return SDValue();
9291 MulhRightOp = RightOp.getOperand(0);
9292 }
9293
9294 SDValue MulhAddOp;
9295 if (ConstantSDNode *Constant = isConstOrConstSplat(AddOp)) {
9296 unsigned ActiveBits = IsSignExt
9297 ? Constant->getAPIntValue().getSignificantBits()
9298 : Constant->getAPIntValue().getActiveBits();
9299 if (ActiveBits > NarrowVTSize)
9300 return SDValue();
9301 MulhAddOp = DAG.getConstant(
9302 Constant->getAPIntValue().trunc(NarrowVT.getScalarSizeInBits()), DL,
9303 NarrowVT);
9304 } else {
9305 if (LeftOp.getOpcode() != AddOp.getOpcode())
9306 return SDValue();
9307 // Check that the two extend nodes are the same type.
9308 if (NarrowVT != AddOp.getOperand(0).getValueType())
9309 return SDValue();
9310 MulhAddOp = AddOp.getOperand(0);
9311 }
9312
9313 EVT WideVT = LeftOp.getValueType();
9314 // Proceed with the transformation if the wide types match.
9315 assert((WideVT == RightOp.getValueType()) &&
9316 "Cannot have a multiply node with two different operand types.");
9317 assert((WideVT == AddOp.getValueType()) &&
9318 "Cannot have an add node with two different operand types.");
9319
9320 // Proceed with the transformation if the wide type is twice as large
9321 // as the narrow type.
9322 if (WideVT.getScalarSizeInBits() != 2 * NarrowVTSize)
9323 return SDValue();
9324
9325 // Check the shift amount with the narrow type size.
9326 // Proceed with the transformation if the shift amount is the width
9327 // of the narrow type.
9328 unsigned ShiftAmt = ShiftAmtSrc->getZExtValue();
9329 if (ShiftAmt != NarrowVTSize)
9330 return SDValue();
9331
9332 // Proceed if we support the multiply-and-add-high operation.
9333 if (!(NarrowVT == MVT::v16i8 || NarrowVT == MVT::v8i16 ||
9334 NarrowVT == MVT::v4i32 ||
9335 (Subtarget.hasVectorEnhancements3() &&
9336 (NarrowVT == MVT::v2i64 || NarrowVT == MVT::i128))))
9337 return SDValue();
9338
9339 // Emit the VMAH (signed) or VMALH (unsigned) operation.
9340 SDValue Result = DAG.getNode(IsSignExt ? SystemZISD::VMAH : SystemZISD::VMALH,
9341 DL, NarrowVT, LeftOp.getOperand(0),
9342 MulhRightOp, MulhAddOp);
9343 bool IsSigned = N->getOpcode() == ISD::SRA;
9344 return DAG.getExtOrTrunc(IsSigned, Result, DL, WideVT);
9345}
9346
9347// Op is an operand of a multiplication. Check whether this can be folded
9348// into an even/odd widening operation; if so, return the opcode to be used
9349// and update Op to the appropriate sub-operand. Note that the caller must
9350// verify that *both* operands of the multiplication support the operation.
9352 const SystemZSubtarget &Subtarget,
9353 SDValue &Op) {
9354 EVT VT = Op.getValueType();
9355
9356 // Check for (sign/zero_extend_vector_inreg (vector_shuffle)) corresponding
9357 // to selecting the even or odd vector elements.
9358 if (VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
9359 (Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
9360 Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG)) {
9361 bool IsSigned = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
9362 unsigned NumElts = VT.getVectorNumElements();
9363 Op = Op.getOperand(0);
9364 if (Op.getValueType().getVectorNumElements() == 2 * NumElts &&
9365 Op.getOpcode() == ISD::VECTOR_SHUFFLE) {
9367 ArrayRef<int> ShuffleMask = SVN->getMask();
9368 bool CanUseEven = true, CanUseOdd = true;
9369 for (unsigned Elt = 0; Elt < NumElts; Elt++) {
9370 if (ShuffleMask[Elt] == -1)
9371 continue;
9372 if (unsigned(ShuffleMask[Elt]) != 2 * Elt)
9373 CanUseEven = false;
9374 if (unsigned(ShuffleMask[Elt]) != 2 * Elt + 1)
9375 CanUseOdd = false;
9376 }
9377 Op = Op.getOperand(0);
9378 if (CanUseEven)
9379 return IsSigned ? SystemZISD::VME : SystemZISD::VMLE;
9380 if (CanUseOdd)
9381 return IsSigned ? SystemZISD::VMO : SystemZISD::VMLO;
9382 }
9383 }
9384
9385 // For z17, we can also support the v2i64->i128 case, which looks like
9386 // (sign/zero_extend (extract_vector_elt X 0/1))
9387 if (VT == MVT::i128 && Subtarget.hasVectorEnhancements3() &&
9388 (Op.getOpcode() == ISD::SIGN_EXTEND ||
9389 Op.getOpcode() == ISD::ZERO_EXTEND)) {
9390 bool IsSigned = Op.getOpcode() == ISD::SIGN_EXTEND;
9391 Op = Op.getOperand(0);
9392 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9393 Op.getOperand(0).getValueType() == MVT::v2i64 &&
9394 Op.getOperand(1).getOpcode() == ISD::Constant) {
9395 unsigned Elem = Op.getConstantOperandVal(1);
9396 Op = Op.getOperand(0);
9397 if (Elem == 0)
9398 return IsSigned ? SystemZISD::VME : SystemZISD::VMLE;
9399 if (Elem == 1)
9400 return IsSigned ? SystemZISD::VMO : SystemZISD::VMLO;
9401 }
9402 }
9403
9404 return 0;
9405}
9406
9407SDValue SystemZTargetLowering::combineMUL(
9408 SDNode *N, DAGCombinerInfo &DCI) const {
9409 SelectionDAG &DAG = DCI.DAG;
9410
9411 // Detect even/odd widening multiplication.
9412 SDValue Op0 = N->getOperand(0);
9413 SDValue Op1 = N->getOperand(1);
9414 unsigned OpcodeCand0 = detectEvenOddMultiplyOperand(DAG, Subtarget, Op0);
9415 unsigned OpcodeCand1 = detectEvenOddMultiplyOperand(DAG, Subtarget, Op1);
9416 if (OpcodeCand0 && OpcodeCand0 == OpcodeCand1)
9417 return DAG.getNode(OpcodeCand0, SDLoc(N), N->getValueType(0), Op0, Op1);
9418
9419 return SDValue();
9420}
9421
9422SDValue SystemZTargetLowering::combineINTRINSIC(
9423 SDNode *N, DAGCombinerInfo &DCI) const {
9424 SelectionDAG &DAG = DCI.DAG;
9425
9426 unsigned Id = N->getConstantOperandVal(1);
9427 switch (Id) {
9428 // VECTOR LOAD (RIGHTMOST) WITH LENGTH with a length operand of 15
9429 // or larger is simply a vector load.
9430 case Intrinsic::s390_vll:
9431 case Intrinsic::s390_vlrl:
9432 if (auto *C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
9433 if (C->getZExtValue() >= 15)
9434 return DAG.getLoad(N->getValueType(0), SDLoc(N), N->getOperand(0),
9435 N->getOperand(3), MachinePointerInfo());
9436 break;
9437 // Likewise for VECTOR STORE (RIGHTMOST) WITH LENGTH.
9438 case Intrinsic::s390_vstl:
9439 case Intrinsic::s390_vstrl:
9440 if (auto *C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
9441 if (C->getZExtValue() >= 15)
9442 return DAG.getStore(N->getOperand(0), SDLoc(N), N->getOperand(2),
9443 N->getOperand(4), MachinePointerInfo());
9444 break;
9445 }
9446
9447 return SDValue();
9448}
9449
9450SDValue SystemZTargetLowering::unwrapAddress(SDValue N) const {
9451 if (N->getOpcode() == SystemZISD::PCREL_WRAPPER)
9452 return N->getOperand(0);
9453 return N;
9454}
9455
9457 DAGCombinerInfo &DCI) const {
9458 switch(N->getOpcode()) {
9459 default: break;
9460 case ISD::ZERO_EXTEND: return combineZERO_EXTEND(N, DCI);
9461 case ISD::SIGN_EXTEND: return combineSIGN_EXTEND(N, DCI);
9462 case ISD::SIGN_EXTEND_INREG: return combineSIGN_EXTEND_INREG(N, DCI);
9463 case SystemZISD::MERGE_HIGH:
9464 case SystemZISD::MERGE_LOW: return combineMERGE(N, DCI);
9465 case ISD::LOAD: return combineLOAD(N, DCI);
9466 case ISD::STORE: return combineSTORE(N, DCI);
9467 case ISD::VECTOR_SHUFFLE: return combineVECTOR_SHUFFLE(N, DCI);
9468 case ISD::EXTRACT_VECTOR_ELT: return combineEXTRACT_VECTOR_ELT(N, DCI);
9469 case SystemZISD::JOIN_DWORDS: return combineJOIN_DWORDS(N, DCI);
9471 case ISD::FP_ROUND: return combineFP_ROUND(N, DCI);
9473 case ISD::FP_EXTEND: return combineFP_EXTEND(N, DCI);
9474 case ISD::SINT_TO_FP:
9475 case ISD::UINT_TO_FP: return combineINT_TO_FP(N, DCI);
9476 case ISD::FCOPYSIGN: return combineFCOPYSIGN(N, DCI);
9477 case ISD::BSWAP: return combineBSWAP(N, DCI);
9478 case ISD::SETCC: return combineSETCC(N, DCI);
9479 case SystemZISD::BR_CCMASK: return combineBR_CCMASK(N, DCI);
9480 case SystemZISD::SELECT_CCMASK: return combineSELECT_CCMASK(N, DCI);
9481 case SystemZISD::GET_CCMASK: return combineGET_CCMASK(N, DCI);
9482 case ISD::SRL:
9483 case ISD::SRA: return combineShiftToMulAddHigh(N, DCI);
9484 case ISD::MUL: return combineMUL(N, DCI);
9485 case ISD::SDIV:
9486 case ISD::UDIV:
9487 case ISD::SREM:
9488 case ISD::UREM: return combineIntDIVREM(N, DCI);
9490 case ISD::INTRINSIC_VOID: return combineINTRINSIC(N, DCI);
9491 }
9492
9493 return SDValue();
9494}
9495
9496// Return the demanded elements for the OpNo source operand of Op. DemandedElts
9497// are for Op.
9498static APInt getDemandedSrcElements(SDValue Op, const APInt &DemandedElts,
9499 unsigned OpNo) {
9500 EVT VT = Op.getValueType();
9501 unsigned NumElts = (VT.isVector() ? VT.getVectorNumElements() : 1);
9502 APInt SrcDemE;
9503 unsigned Opcode = Op.getOpcode();
9504 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
9505 unsigned Id = Op.getConstantOperandVal(0);
9506 switch (Id) {
9507 case Intrinsic::s390_vpksh: // PACKS
9508 case Intrinsic::s390_vpksf:
9509 case Intrinsic::s390_vpksg:
9510 case Intrinsic::s390_vpkshs: // PACKS_CC
9511 case Intrinsic::s390_vpksfs:
9512 case Intrinsic::s390_vpksgs:
9513 case Intrinsic::s390_vpklsh: // PACKLS
9514 case Intrinsic::s390_vpklsf:
9515 case Intrinsic::s390_vpklsg:
9516 case Intrinsic::s390_vpklshs: // PACKLS_CC
9517 case Intrinsic::s390_vpklsfs:
9518 case Intrinsic::s390_vpklsgs:
9519 // VECTOR PACK truncates the elements of two source vectors into one.
9520 SrcDemE = DemandedElts;
9521 if (OpNo == 2)
9522 SrcDemE.lshrInPlace(NumElts / 2);
9523 SrcDemE = SrcDemE.trunc(NumElts / 2);
9524 break;
9525 // VECTOR UNPACK extends half the elements of the source vector.
9526 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
9527 case Intrinsic::s390_vuphh:
9528 case Intrinsic::s390_vuphf:
9529 case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH
9530 case Intrinsic::s390_vuplhh:
9531 case Intrinsic::s390_vuplhf:
9532 SrcDemE = APInt(NumElts * 2, 0);
9533 SrcDemE.insertBits(DemandedElts, 0);
9534 break;
9535 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
9536 case Intrinsic::s390_vuplhw:
9537 case Intrinsic::s390_vuplf:
9538 case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW
9539 case Intrinsic::s390_vupllh:
9540 case Intrinsic::s390_vupllf:
9541 SrcDemE = APInt(NumElts * 2, 0);
9542 SrcDemE.insertBits(DemandedElts, NumElts);
9543 break;
9544 case Intrinsic::s390_vpdi: {
9545 // VECTOR PERMUTE DWORD IMMEDIATE selects one element from each source.
9546 SrcDemE = APInt(NumElts, 0);
9547 if (!DemandedElts[OpNo - 1])
9548 break;
9549 unsigned Mask = Op.getConstantOperandVal(3);
9550 unsigned MaskBit = ((OpNo - 1) ? 1 : 4);
9551 // Demand input element 0 or 1, given by the mask bit value.
9552 SrcDemE.setBit((Mask & MaskBit)? 1 : 0);
9553 break;
9554 }
9555 case Intrinsic::s390_vsldb: {
9556 // VECTOR SHIFT LEFT DOUBLE BY BYTE
9557 assert(VT == MVT::v16i8 && "Unexpected type.");
9558 unsigned FirstIdx = Op.getConstantOperandVal(3);
9559 assert (FirstIdx > 0 && FirstIdx < 16 && "Unused operand.");
9560 unsigned NumSrc0Els = 16 - FirstIdx;
9561 SrcDemE = APInt(NumElts, 0);
9562 if (OpNo == 1) {
9563 APInt DemEls = DemandedElts.trunc(NumSrc0Els);
9564 SrcDemE.insertBits(DemEls, FirstIdx);
9565 } else {
9566 APInt DemEls = DemandedElts.lshr(NumSrc0Els);
9567 SrcDemE.insertBits(DemEls, 0);
9568 }
9569 break;
9570 }
9571 case Intrinsic::s390_vperm:
9572 SrcDemE = APInt::getAllOnes(NumElts);
9573 break;
9574 default:
9575 llvm_unreachable("Unhandled intrinsic.");
9576 break;
9577 }
9578 } else {
9579 switch (Opcode) {
9580 case SystemZISD::JOIN_DWORDS:
9581 // Scalar operand.
9582 SrcDemE = APInt(1, 1);
9583 break;
9584 case SystemZISD::SELECT_CCMASK:
9585 SrcDemE = DemandedElts;
9586 break;
9587 default:
9588 llvm_unreachable("Unhandled opcode.");
9589 break;
9590 }
9591 }
9592 return SrcDemE;
9593}
9594
9596 const APInt &DemandedElts,
9597 const SelectionDAG &DAG, unsigned Depth,
9598 unsigned OpNo) {
9599 APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo);
9600 APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1);
9601 KnownBits LHSKnown =
9602 DAG.computeKnownBits(Op.getOperand(OpNo), Src0DemE, Depth + 1);
9603 KnownBits RHSKnown =
9604 DAG.computeKnownBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1);
9605 Known = LHSKnown.intersectWith(RHSKnown);
9606}
9607
9608void
9611 const APInt &DemandedElts,
9612 const SelectionDAG &DAG,
9613 unsigned Depth) const {
9614 Known.resetAll();
9615
9616 // Intrinsic CC result is returned in the two low bits.
9617 unsigned Tmp0, Tmp1; // not used
9618 if (Op.getResNo() == 1 && isIntrinsicWithCC(Op, Tmp0, Tmp1)) {
9619 Known.Zero.setBitsFrom(2);
9620 return;
9621 }
9622 EVT VT = Op.getValueType();
9623 if (Op.getResNo() != 0 || VT == MVT::Untyped)
9624 return;
9625 assert (Known.getBitWidth() == VT.getScalarSizeInBits() &&
9626 "KnownBits does not match VT in bitwidth");
9627 assert ((!VT.isVector() ||
9628 (DemandedElts.getBitWidth() == VT.getVectorNumElements())) &&
9629 "DemandedElts does not match VT number of elements");
9630 unsigned BitWidth = Known.getBitWidth();
9631 unsigned Opcode = Op.getOpcode();
9632 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
9633 bool IsLogical = false;
9634 unsigned Id = Op.getConstantOperandVal(0);
9635 switch (Id) {
9636 case Intrinsic::s390_vpksh: // PACKS
9637 case Intrinsic::s390_vpksf:
9638 case Intrinsic::s390_vpksg:
9639 case Intrinsic::s390_vpkshs: // PACKS_CC
9640 case Intrinsic::s390_vpksfs:
9641 case Intrinsic::s390_vpksgs:
9642 case Intrinsic::s390_vpklsh: // PACKLS
9643 case Intrinsic::s390_vpklsf:
9644 case Intrinsic::s390_vpklsg:
9645 case Intrinsic::s390_vpklshs: // PACKLS_CC
9646 case Intrinsic::s390_vpklsfs:
9647 case Intrinsic::s390_vpklsgs:
9648 case Intrinsic::s390_vpdi:
9649 case Intrinsic::s390_vsldb:
9650 case Intrinsic::s390_vperm:
9651 computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 1);
9652 break;
9653 case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH
9654 case Intrinsic::s390_vuplhh:
9655 case Intrinsic::s390_vuplhf:
9656 case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW
9657 case Intrinsic::s390_vupllh:
9658 case Intrinsic::s390_vupllf:
9659 IsLogical = true;
9660 [[fallthrough]];
9661 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
9662 case Intrinsic::s390_vuphh:
9663 case Intrinsic::s390_vuphf:
9664 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
9665 case Intrinsic::s390_vuplhw:
9666 case Intrinsic::s390_vuplf: {
9667 SDValue SrcOp = Op.getOperand(1);
9668 APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 0);
9669 Known = DAG.computeKnownBits(SrcOp, SrcDemE, Depth + 1);
9670 if (IsLogical) {
9671 Known = Known.zext(BitWidth);
9672 } else
9673 Known = Known.sext(BitWidth);
9674 break;
9675 }
9676 default:
9677 break;
9678 }
9679 } else {
9680 switch (Opcode) {
9681 case SystemZISD::JOIN_DWORDS:
9682 case SystemZISD::SELECT_CCMASK:
9683 computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 0);
9684 break;
9685 case SystemZISD::REPLICATE: {
9686 SDValue SrcOp = Op.getOperand(0);
9687 Known = DAG.computeKnownBits(SrcOp, Depth + 1);
9688 if (Known.getBitWidth() < BitWidth && isa<ConstantSDNode>(SrcOp))
9689 Known = Known.sext(BitWidth); // VREPI sign extends the immedate.
9690 break;
9691 }
9692 default:
9693 break;
9694 }
9695 }
9696
9697 // Known has the width of the source operand(s). Adjust if needed to match
9698 // the passed bitwidth.
9699 if (Known.getBitWidth() != BitWidth)
9700 Known = Known.anyextOrTrunc(BitWidth);
9701}
9702
9703static unsigned computeNumSignBitsBinOp(SDValue Op, const APInt &DemandedElts,
9704 const SelectionDAG &DAG, unsigned Depth,
9705 unsigned OpNo) {
9706 APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo);
9707 unsigned LHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo), Src0DemE, Depth + 1);
9708 if (LHS == 1) return 1; // Early out.
9709 APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1);
9710 unsigned RHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1);
9711 if (RHS == 1) return 1; // Early out.
9712 unsigned Common = std::min(LHS, RHS);
9713 unsigned SrcBitWidth = Op.getOperand(OpNo).getScalarValueSizeInBits();
9714 EVT VT = Op.getValueType();
9715 unsigned VTBits = VT.getScalarSizeInBits();
9716 if (SrcBitWidth > VTBits) { // PACK
9717 unsigned SrcExtraBits = SrcBitWidth - VTBits;
9718 if (Common > SrcExtraBits)
9719 return (Common - SrcExtraBits);
9720 return 1;
9721 }
9722 assert (SrcBitWidth == VTBits && "Expected operands of same bitwidth.");
9723 return Common;
9724}
9725
9726unsigned
9728 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9729 unsigned Depth) const {
9730 if (Op.getResNo() != 0)
9731 return 1;
9732 unsigned Opcode = Op.getOpcode();
9733 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
9734 unsigned Id = Op.getConstantOperandVal(0);
9735 switch (Id) {
9736 case Intrinsic::s390_vpksh: // PACKS
9737 case Intrinsic::s390_vpksf:
9738 case Intrinsic::s390_vpksg:
9739 case Intrinsic::s390_vpkshs: // PACKS_CC
9740 case Intrinsic::s390_vpksfs:
9741 case Intrinsic::s390_vpksgs:
9742 case Intrinsic::s390_vpklsh: // PACKLS
9743 case Intrinsic::s390_vpklsf:
9744 case Intrinsic::s390_vpklsg:
9745 case Intrinsic::s390_vpklshs: // PACKLS_CC
9746 case Intrinsic::s390_vpklsfs:
9747 case Intrinsic::s390_vpklsgs:
9748 case Intrinsic::s390_vpdi:
9749 case Intrinsic::s390_vsldb:
9750 case Intrinsic::s390_vperm:
9751 return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 1);
9752 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
9753 case Intrinsic::s390_vuphh:
9754 case Intrinsic::s390_vuphf:
9755 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
9756 case Intrinsic::s390_vuplhw:
9757 case Intrinsic::s390_vuplf: {
9758 SDValue PackedOp = Op.getOperand(1);
9759 APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 1);
9760 unsigned Tmp = DAG.ComputeNumSignBits(PackedOp, SrcDemE, Depth + 1);
9761 EVT VT = Op.getValueType();
9762 unsigned VTBits = VT.getScalarSizeInBits();
9763 Tmp += VTBits - PackedOp.getScalarValueSizeInBits();
9764 return Tmp;
9765 }
9766 default:
9767 break;
9768 }
9769 } else {
9770 switch (Opcode) {
9771 case SystemZISD::SELECT_CCMASK:
9772 return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 0);
9773 default:
9774 break;
9775 }
9776 }
9777
9778 return 1;
9779}
9780
9782 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9783 UndefPoisonKind Kind, unsigned Depth) const {
9784 switch (Op->getOpcode()) {
9785 case SystemZISD::PCREL_WRAPPER:
9786 case SystemZISD::PCREL_OFFSET:
9787 return true;
9788 }
9789 return false;
9790}
9791
9792unsigned
9794 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
9795 unsigned StackAlign = TFI->getStackAlignment();
9796 assert(StackAlign >=1 && isPowerOf2_32(StackAlign) &&
9797 "Unexpected stack alignment");
9798 // The default stack probe size is 4096 if the function has no
9799 // stack-probe-size attribute.
9800 unsigned StackProbeSize =
9801 MF.getFunction().getFnAttributeAsParsedInteger("stack-probe-size", 4096);
9802 // Round down to the stack alignment.
9803 StackProbeSize &= ~(StackAlign - 1);
9804 return StackProbeSize ? StackProbeSize : StackAlign;
9805}
9806
9807//===----------------------------------------------------------------------===//
9808// Custom insertion
9809//===----------------------------------------------------------------------===//
9810
9811// Force base value Base into a register before MI. Return the register.
9813 const SystemZInstrInfo *TII) {
9814 MachineBasicBlock *MBB = MI.getParent();
9815 MachineFunction &MF = *MBB->getParent();
9816 MachineRegisterInfo &MRI = MF.getRegInfo();
9817
9818 if (Base.isReg()) {
9819 // Copy Base into a new virtual register to help register coalescing in
9820 // cases with multiple uses.
9821 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
9822 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::COPY), Reg)
9823 .add(Base);
9824 return Reg;
9825 }
9826
9827 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
9828 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LA), Reg)
9829 .add(Base)
9830 .addImm(0)
9831 .addReg(0);
9832 return Reg;
9833}
9834
9835// The CC operand of MI might be missing a kill marker because there
9836// were multiple uses of CC, and ISel didn't know which to mark.
9837// Figure out whether MI should have had a kill marker.
9839 // Scan forward through BB for a use/def of CC.
9841 for (MachineBasicBlock::iterator miE = MBB->end(); miI != miE; ++miI) {
9842 const MachineInstr &MI = *miI;
9843 if (MI.readsRegister(SystemZ::CC, /*TRI=*/nullptr))
9844 return false;
9845 if (MI.definesRegister(SystemZ::CC, /*TRI=*/nullptr))
9846 break; // Should have kill-flag - update below.
9847 }
9848
9849 // If we hit the end of the block, check whether CC is live into a
9850 // successor.
9851 if (miI == MBB->end()) {
9852 for (const MachineBasicBlock *Succ : MBB->successors())
9853 if (Succ->isLiveIn(SystemZ::CC))
9854 return false;
9855 }
9856
9857 return true;
9858}
9859
9860// Return true if it is OK for this Select pseudo-opcode to be cascaded
9861// together with other Select pseudo-opcodes into a single basic-block with
9862// a conditional jump around it.
9864 switch (MI.getOpcode()) {
9865 case SystemZ::Select32:
9866 case SystemZ::Select64:
9867 case SystemZ::Select128:
9868 case SystemZ::SelectF32:
9869 case SystemZ::SelectF64:
9870 case SystemZ::SelectF128:
9871 case SystemZ::SelectVR32:
9872 case SystemZ::SelectVR64:
9873 case SystemZ::SelectVR128:
9874 return true;
9875
9876 default:
9877 return false;
9878 }
9879}
9880
9881// Helper function, which inserts PHI functions into SinkMBB:
9882// %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ],
9883// where %FalseValue(i) and %TrueValue(i) are taken from Selects.
9885 MachineBasicBlock *TrueMBB,
9886 MachineBasicBlock *FalseMBB,
9887 MachineBasicBlock *SinkMBB) {
9888 MachineFunction *MF = TrueMBB->getParent();
9890
9891 MachineInstr *FirstMI = Selects.front();
9892 unsigned CCValid = FirstMI->getOperand(3).getImm();
9893 unsigned CCMask = FirstMI->getOperand(4).getImm();
9894
9895 MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
9896
9897 // As we are creating the PHIs, we have to be careful if there is more than
9898 // one. Later Selects may reference the results of earlier Selects, but later
9899 // PHIs have to reference the individual true/false inputs from earlier PHIs.
9900 // That also means that PHI construction must work forward from earlier to
9901 // later, and that the code must maintain a mapping from earlier PHI's
9902 // destination registers, and the registers that went into the PHI.
9904
9905 for (auto *MI : Selects) {
9906 Register DestReg = MI->getOperand(0).getReg();
9907 Register TrueReg = MI->getOperand(1).getReg();
9908 Register FalseReg = MI->getOperand(2).getReg();
9909
9910 // If this Select we are generating is the opposite condition from
9911 // the jump we generated, then we have to swap the operands for the
9912 // PHI that is going to be generated.
9913 if (MI->getOperand(4).getImm() == (CCValid ^ CCMask))
9914 std::swap(TrueReg, FalseReg);
9915
9916 if (auto It = RegRewriteTable.find(TrueReg); It != RegRewriteTable.end())
9917 TrueReg = It->second.first;
9918
9919 if (auto It = RegRewriteTable.find(FalseReg); It != RegRewriteTable.end())
9920 FalseReg = It->second.second;
9921
9922 DebugLoc DL = MI->getDebugLoc();
9923 BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(SystemZ::PHI), DestReg)
9924 .addReg(TrueReg).addMBB(TrueMBB)
9925 .addReg(FalseReg).addMBB(FalseMBB);
9926
9927 // Add this PHI to the rewrite table.
9928 RegRewriteTable[DestReg] = std::make_pair(TrueReg, FalseReg);
9929 }
9930
9931 MF->getProperties().resetNoPHIs();
9932}
9933
9935SystemZTargetLowering::emitAdjCallStack(MachineInstr &MI,
9936 MachineBasicBlock *BB) const {
9937 MachineFunction &MF = *BB->getParent();
9938 MachineFrameInfo &MFI = MF.getFrameInfo();
9939 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
9940 assert(TFL->hasReservedCallFrame(MF) &&
9941 "ADJSTACKDOWN and ADJSTACKUP should be no-ops");
9942 (void)TFL;
9943 // Get the MaxCallFrameSize value and erase MI since it serves no further
9944 // purpose as the call frame is statically reserved in the prolog. Set
9945 // AdjustsStack as MI is *not* mapped as a frame instruction.
9946 uint32_t NumBytes = MI.getOperand(0).getImm();
9947 if (NumBytes > MFI.getMaxCallFrameSize())
9948 MFI.setMaxCallFrameSize(NumBytes);
9949 MFI.setAdjustsStack(true);
9950
9951 MI.eraseFromParent();
9952 return BB;
9953}
9954
9955// Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
9957SystemZTargetLowering::emitSelect(MachineInstr &MI,
9958 MachineBasicBlock *MBB) const {
9959 assert(isSelectPseudo(MI) && "Bad call to emitSelect()");
9960 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
9961
9962 unsigned CCValid = MI.getOperand(3).getImm();
9963 unsigned CCMask = MI.getOperand(4).getImm();
9964
9965 // If we have a sequence of Select* pseudo instructions using the
9966 // same condition code value, we want to expand all of them into
9967 // a single pair of basic blocks using the same condition.
9968 SmallVector<MachineInstr*, 8> Selects;
9969 SmallVector<MachineInstr*, 8> DbgValues;
9970 Selects.push_back(&MI);
9971 unsigned Count = 0;
9972 for (MachineInstr &NextMI : llvm::make_range(
9973 std::next(MachineBasicBlock::iterator(MI)), MBB->end())) {
9974 if (isSelectPseudo(NextMI)) {
9975 assert(NextMI.getOperand(3).getImm() == CCValid &&
9976 "Bad CCValid operands since CC was not redefined.");
9977 if (NextMI.getOperand(4).getImm() == CCMask ||
9978 NextMI.getOperand(4).getImm() == (CCValid ^ CCMask)) {
9979 Selects.push_back(&NextMI);
9980 continue;
9981 }
9982 break;
9983 }
9984 if (NextMI.definesRegister(SystemZ::CC, /*TRI=*/nullptr) ||
9985 NextMI.usesCustomInsertionHook())
9986 break;
9987 bool User = false;
9988 for (auto *SelMI : Selects)
9989 if (NextMI.readsVirtualRegister(SelMI->getOperand(0).getReg())) {
9990 User = true;
9991 break;
9992 }
9993 if (NextMI.isDebugInstr()) {
9994 if (User) {
9995 assert(NextMI.isDebugValue() && "Unhandled debug opcode.");
9996 DbgValues.push_back(&NextMI);
9997 }
9998 } else if (User || ++Count > 20)
9999 break;
10000 }
10001
10002 MachineInstr *LastMI = Selects.back();
10003 bool CCKilled = (LastMI->killsRegister(SystemZ::CC, /*TRI=*/nullptr) ||
10004 checkCCKill(*LastMI, MBB));
10005 MachineBasicBlock *StartMBB = MBB;
10006 MachineBasicBlock *JoinMBB = SystemZ::splitBlockAfter(LastMI, MBB);
10007 MachineBasicBlock *FalseMBB = SystemZ::emitBlockAfter(StartMBB);
10008
10009 // Unless CC was killed in the last Select instruction, mark it as
10010 // live-in to both FalseMBB and JoinMBB.
10011 if (!CCKilled) {
10012 FalseMBB->addLiveIn(SystemZ::CC);
10013 JoinMBB->addLiveIn(SystemZ::CC);
10014 }
10015
10016 // StartMBB:
10017 // BRC CCMask, JoinMBB
10018 // # fallthrough to FalseMBB
10019 MBB = StartMBB;
10020 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::BRC))
10021 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
10022 MBB->addSuccessor(JoinMBB);
10023 MBB->addSuccessor(FalseMBB);
10024
10025 // FalseMBB:
10026 // # fallthrough to JoinMBB
10027 MBB = FalseMBB;
10028 MBB->addSuccessor(JoinMBB);
10029
10030 // JoinMBB:
10031 // %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
10032 // ...
10033 MBB = JoinMBB;
10034 createPHIsForSelects(Selects, StartMBB, FalseMBB, MBB);
10035 for (auto *SelMI : Selects)
10036 SelMI->eraseFromParent();
10037
10039 for (auto *DbgMI : DbgValues)
10040 MBB->splice(InsertPos, StartMBB, DbgMI);
10041
10042 return JoinMBB;
10043}
10044
10045// Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
10046// StoreOpcode is the store to use and Invert says whether the store should
10047// happen when the condition is false rather than true. If a STORE ON
10048// CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
10049MachineBasicBlock *SystemZTargetLowering::emitCondStore(MachineInstr &MI,
10051 unsigned StoreOpcode,
10052 unsigned STOCOpcode,
10053 bool Invert) const {
10054 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10055
10056 Register SrcReg = MI.getOperand(0).getReg();
10057 MachineOperand Base = MI.getOperand(1);
10058 int64_t Disp = MI.getOperand(2).getImm();
10059 Register IndexReg = MI.getOperand(3).getReg();
10060 unsigned CCValid = MI.getOperand(4).getImm();
10061 unsigned CCMask = MI.getOperand(5).getImm();
10062 DebugLoc DL = MI.getDebugLoc();
10063
10064 StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
10065
10066 // ISel pattern matching also adds a load memory operand of the same
10067 // address, so take special care to find the storing memory operand.
10068 MachineMemOperand *MMO = nullptr;
10069 for (auto *I : MI.memoperands())
10070 if (I->isStore()) {
10071 MMO = I;
10072 break;
10073 }
10074
10075 // Use STOCOpcode if possible. We could use different store patterns in
10076 // order to avoid matching the index register, but the performance trade-offs
10077 // might be more complicated in that case.
10078 if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) {
10079 if (Invert)
10080 CCMask ^= CCValid;
10081
10082 BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
10083 .addReg(SrcReg)
10084 .add(Base)
10085 .addImm(Disp)
10086 .addImm(CCValid)
10087 .addImm(CCMask)
10088 .addMemOperand(MMO);
10089
10090 MI.eraseFromParent();
10091 return MBB;
10092 }
10093
10094 // Get the condition needed to branch around the store.
10095 if (!Invert)
10096 CCMask ^= CCValid;
10097
10098 MachineBasicBlock *StartMBB = MBB;
10099 MachineBasicBlock *JoinMBB = SystemZ::splitBlockBefore(MI, MBB);
10100 MachineBasicBlock *FalseMBB = SystemZ::emitBlockAfter(StartMBB);
10101
10102 // Unless CC was killed in the CondStore instruction, mark it as
10103 // live-in to both FalseMBB and JoinMBB.
10104 if (!MI.killsRegister(SystemZ::CC, /*TRI=*/nullptr) &&
10105 !checkCCKill(MI, JoinMBB)) {
10106 FalseMBB->addLiveIn(SystemZ::CC);
10107 JoinMBB->addLiveIn(SystemZ::CC);
10108 }
10109
10110 // StartMBB:
10111 // BRC CCMask, JoinMBB
10112 // # fallthrough to FalseMBB
10113 MBB = StartMBB;
10114 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10115 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
10116 MBB->addSuccessor(JoinMBB);
10117 MBB->addSuccessor(FalseMBB);
10118
10119 // FalseMBB:
10120 // store %SrcReg, %Disp(%Index,%Base)
10121 // # fallthrough to JoinMBB
10122 MBB = FalseMBB;
10123 BuildMI(MBB, DL, TII->get(StoreOpcode))
10124 .addReg(SrcReg)
10125 .add(Base)
10126 .addImm(Disp)
10127 .addReg(IndexReg)
10128 .addMemOperand(MMO);
10129 MBB->addSuccessor(JoinMBB);
10130
10131 MI.eraseFromParent();
10132 return JoinMBB;
10133}
10134
10135// Implement EmitInstrWithCustomInserter for pseudo [SU]Cmp128Hi instruction MI.
10137SystemZTargetLowering::emitICmp128Hi(MachineInstr &MI,
10139 bool Unsigned) const {
10140 MachineFunction &MF = *MBB->getParent();
10141 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10142 MachineRegisterInfo &MRI = MF.getRegInfo();
10143
10144 // Synthetic instruction to compare 128-bit values.
10145 // Sets CC 1 if Op0 > Op1, sets a different CC otherwise.
10146 Register Op0 = MI.getOperand(0).getReg();
10147 Register Op1 = MI.getOperand(1).getReg();
10148
10149 MachineBasicBlock *StartMBB = MBB;
10150 MachineBasicBlock *JoinMBB = SystemZ::splitBlockAfter(MI, MBB);
10151 MachineBasicBlock *HiEqMBB = SystemZ::emitBlockAfter(StartMBB);
10152
10153 // StartMBB:
10154 //
10155 // Use VECTOR ELEMENT COMPARE [LOGICAL] to compare the high parts.
10156 // Swap the inputs to get:
10157 // CC 1 if high(Op0) > high(Op1)
10158 // CC 2 if high(Op0) < high(Op1)
10159 // CC 0 if high(Op0) == high(Op1)
10160 //
10161 // If CC != 0, we'd done, so jump over the next instruction.
10162 //
10163 // VEC[L]G Op1, Op0
10164 // JNE JoinMBB
10165 // # fallthrough to HiEqMBB
10166 MBB = StartMBB;
10167 int HiOpcode = Unsigned? SystemZ::VECLG : SystemZ::VECG;
10168 BuildMI(MBB, MI.getDebugLoc(), TII->get(HiOpcode))
10169 .addReg(Op1).addReg(Op0);
10170 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::BRC))
10172 MBB->addSuccessor(JoinMBB);
10173 MBB->addSuccessor(HiEqMBB);
10174
10175 // HiEqMBB:
10176 //
10177 // Otherwise, use VECTOR COMPARE HIGH LOGICAL.
10178 // Since we already know the high parts are equal, the CC
10179 // result will only depend on the low parts:
10180 // CC 1 if low(Op0) > low(Op1)
10181 // CC 3 if low(Op0) <= low(Op1)
10182 //
10183 // VCHLGS Tmp, Op0, Op1
10184 // # fallthrough to JoinMBB
10185 MBB = HiEqMBB;
10186 Register Temp = MRI.createVirtualRegister(&SystemZ::VR128BitRegClass);
10187 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::VCHLGS), Temp)
10188 .addReg(Op0).addReg(Op1);
10189 MBB->addSuccessor(JoinMBB);
10190
10191 // Mark CC as live-in to JoinMBB.
10192 JoinMBB->addLiveIn(SystemZ::CC);
10193
10194 MI.eraseFromParent();
10195 return JoinMBB;
10196}
10197
10198// Implement EmitInstrWithCustomInserter for subword pseudo ATOMIC_LOADW_* or
10199// ATOMIC_SWAPW instruction MI. BinOpcode is the instruction that performs
10200// the binary operation elided by "*", or 0 for ATOMIC_SWAPW. Invert says
10201// whether the field should be inverted after performing BinOpcode (e.g. for
10202// NAND).
10203MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadBinary(
10204 MachineInstr &MI, MachineBasicBlock *MBB, unsigned BinOpcode,
10205 bool Invert) const {
10206 MachineFunction &MF = *MBB->getParent();
10207 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10208 MachineRegisterInfo &MRI = MF.getRegInfo();
10209
10210 // Extract the operands. Base can be a register or a frame index.
10211 // Src2 can be a register or immediate.
10212 Register Dest = MI.getOperand(0).getReg();
10213 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
10214 int64_t Disp = MI.getOperand(2).getImm();
10215 MachineOperand Src2 = earlyUseOperand(MI.getOperand(3));
10216 Register BitShift = MI.getOperand(4).getReg();
10217 Register NegBitShift = MI.getOperand(5).getReg();
10218 unsigned BitSize = MI.getOperand(6).getImm();
10219 DebugLoc DL = MI.getDebugLoc();
10220
10221 // Get the right opcodes for the displacement.
10222 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
10223 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
10224 assert(LOpcode && CSOpcode && "Displacement out of range");
10225
10226 // Create virtual registers for temporary results.
10227 Register OrigVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10228 Register OldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10229 Register NewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10230 Register RotatedOldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10231 Register RotatedNewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10232
10233 // Insert a basic block for the main loop.
10234 MachineBasicBlock *StartMBB = MBB;
10235 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10236 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10237
10238 // StartMBB:
10239 // ...
10240 // %OrigVal = L Disp(%Base)
10241 // # fall through to LoopMBB
10242 MBB = StartMBB;
10243 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
10244 MBB->addSuccessor(LoopMBB);
10245
10246 // LoopMBB:
10247 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
10248 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
10249 // %RotatedNewVal = OP %RotatedOldVal, %Src2
10250 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
10251 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
10252 // JNE LoopMBB
10253 // # fall through to DoneMBB
10254 MBB = LoopMBB;
10255 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
10256 .addReg(OrigVal).addMBB(StartMBB)
10257 .addReg(Dest).addMBB(LoopMBB);
10258 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
10259 .addReg(OldVal).addReg(BitShift).addImm(0);
10260 if (Invert) {
10261 // Perform the operation normally and then invert every bit of the field.
10262 Register Tmp = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10263 BuildMI(MBB, DL, TII->get(BinOpcode), Tmp)
10264 .addReg(RotatedOldVal)
10265 .add(Src2)
10266 .setOperandDead(3);
10267 // XILF with the upper BitSize bits set.
10268 BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
10269 .addReg(Tmp)
10270 .addImm(-1U << (32 - BitSize))
10271 .setOperandDead(3);
10272 } else if (BinOpcode)
10273 // A simply binary operation.
10274 BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
10275 .addReg(RotatedOldVal)
10276 .add(Src2)
10277 .setOperandDead(3);
10278 else
10279 // Use RISBG to rotate Src2 into position and use it to replace the
10280 // field in RotatedOldVal.
10281 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
10282 .addReg(RotatedOldVal)
10283 .addReg(Src2.getReg())
10284 .addImm(32)
10285 .addImm(31 + BitSize)
10286 .addImm(32 - BitSize)
10287 .setOperandDead(6);
10288 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
10289 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
10290 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
10291 .addReg(OldVal)
10292 .addReg(NewVal)
10293 .add(Base)
10294 .addImm(Disp);
10295 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10297 MBB->addSuccessor(LoopMBB);
10298 MBB->addSuccessor(DoneMBB);
10299
10300 MI.eraseFromParent();
10301 return DoneMBB;
10302}
10303
10304// Implement EmitInstrWithCustomInserter for subword pseudo
10305// ATOMIC_LOADW_{,U}{MIN,MAX} instruction MI. CompareOpcode is the
10306// instruction that should be used to compare the current field with the
10307// minimum or maximum value. KeepOldMask is the BRC condition-code mask
10308// for when the current field should be kept.
10309MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadMinMax(
10310 MachineInstr &MI, MachineBasicBlock *MBB, unsigned CompareOpcode,
10311 unsigned KeepOldMask) const {
10312 MachineFunction &MF = *MBB->getParent();
10313 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10314 MachineRegisterInfo &MRI = MF.getRegInfo();
10315
10316 // Extract the operands. Base can be a register or a frame index.
10317 Register Dest = MI.getOperand(0).getReg();
10318 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
10319 int64_t Disp = MI.getOperand(2).getImm();
10320 Register Src2 = MI.getOperand(3).getReg();
10321 Register BitShift = MI.getOperand(4).getReg();
10322 Register NegBitShift = MI.getOperand(5).getReg();
10323 unsigned BitSize = MI.getOperand(6).getImm();
10324 DebugLoc DL = MI.getDebugLoc();
10325
10326 // Get the right opcodes for the displacement.
10327 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
10328 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
10329 assert(LOpcode && CSOpcode && "Displacement out of range");
10330
10331 // Create virtual registers for temporary results.
10332 Register OrigVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10333 Register OldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10334 Register NewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10335 Register RotatedOldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10336 Register RotatedAltVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10337 Register RotatedNewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10338
10339 // Insert 3 basic blocks for the loop.
10340 MachineBasicBlock *StartMBB = MBB;
10341 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10342 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10343 MachineBasicBlock *UseAltMBB = SystemZ::emitBlockAfter(LoopMBB);
10344 MachineBasicBlock *UpdateMBB = SystemZ::emitBlockAfter(UseAltMBB);
10345
10346 // StartMBB:
10347 // ...
10348 // %OrigVal = L Disp(%Base)
10349 // # fall through to LoopMBB
10350 MBB = StartMBB;
10351 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
10352 MBB->addSuccessor(LoopMBB);
10353
10354 // LoopMBB:
10355 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
10356 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
10357 // CompareOpcode %RotatedOldVal, %Src2
10358 // BRC KeepOldMask, UpdateMBB
10359 MBB = LoopMBB;
10360 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
10361 .addReg(OrigVal).addMBB(StartMBB)
10362 .addReg(Dest).addMBB(UpdateMBB);
10363 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
10364 .addReg(OldVal).addReg(BitShift).addImm(0);
10365 BuildMI(MBB, DL, TII->get(CompareOpcode))
10366 .addReg(RotatedOldVal).addReg(Src2);
10367 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10368 .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
10369 MBB->addSuccessor(UpdateMBB);
10370 MBB->addSuccessor(UseAltMBB);
10371
10372 // UseAltMBB:
10373 // %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
10374 // # fall through to UpdateMBB
10375 MBB = UseAltMBB;
10376 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
10377 .addReg(RotatedOldVal)
10378 .addReg(Src2)
10379 .addImm(32)
10380 .addImm(31 + BitSize)
10381 .addImm(0)
10382 .setOperandDead(6);
10383 MBB->addSuccessor(UpdateMBB);
10384
10385 // UpdateMBB:
10386 // %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
10387 // [ %RotatedAltVal, UseAltMBB ]
10388 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
10389 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
10390 // JNE LoopMBB
10391 // # fall through to DoneMBB
10392 MBB = UpdateMBB;
10393 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
10394 .addReg(RotatedOldVal).addMBB(LoopMBB)
10395 .addReg(RotatedAltVal).addMBB(UseAltMBB);
10396 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
10397 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
10398 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
10399 .addReg(OldVal)
10400 .addReg(NewVal)
10401 .add(Base)
10402 .addImm(Disp);
10403 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10405 MBB->addSuccessor(LoopMBB);
10406 MBB->addSuccessor(DoneMBB);
10407
10408 MI.eraseFromParent();
10409 return DoneMBB;
10410}
10411
10412// Implement EmitInstrWithCustomInserter for subword pseudo ATOMIC_CMP_SWAPW
10413// instruction MI.
10415SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr &MI,
10416 MachineBasicBlock *MBB) const {
10417 MachineFunction &MF = *MBB->getParent();
10418 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10419 MachineRegisterInfo &MRI = MF.getRegInfo();
10420
10421 // Extract the operands. Base can be a register or a frame index.
10422 Register Dest = MI.getOperand(0).getReg();
10423 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
10424 int64_t Disp = MI.getOperand(2).getImm();
10425 Register CmpVal = MI.getOperand(3).getReg();
10426 Register OrigSwapVal = MI.getOperand(4).getReg();
10427 Register BitShift = MI.getOperand(5).getReg();
10428 Register NegBitShift = MI.getOperand(6).getReg();
10429 int64_t BitSize = MI.getOperand(7).getImm();
10430 DebugLoc DL = MI.getDebugLoc();
10431
10432 const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
10433
10434 // Get the right opcodes for the displacement and zero-extension.
10435 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
10436 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
10437 unsigned ZExtOpcode = BitSize == 8 ? SystemZ::LLCR : SystemZ::LLHR;
10438 assert(LOpcode && CSOpcode && "Displacement out of range");
10439
10440 // Create virtual registers for temporary results.
10441 Register OrigOldVal = MRI.createVirtualRegister(RC);
10442 Register OldVal = MRI.createVirtualRegister(RC);
10443 Register SwapVal = MRI.createVirtualRegister(RC);
10444 Register StoreVal = MRI.createVirtualRegister(RC);
10445 Register OldValRot = MRI.createVirtualRegister(RC);
10446 Register RetryOldVal = MRI.createVirtualRegister(RC);
10447 Register RetrySwapVal = MRI.createVirtualRegister(RC);
10448
10449 // Insert 2 basic blocks for the loop.
10450 MachineBasicBlock *StartMBB = MBB;
10451 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10452 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10453 MachineBasicBlock *SetMBB = SystemZ::emitBlockAfter(LoopMBB);
10454
10455 // StartMBB:
10456 // ...
10457 // %OrigOldVal = L Disp(%Base)
10458 // # fall through to LoopMBB
10459 MBB = StartMBB;
10460 BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
10461 .add(Base)
10462 .addImm(Disp)
10463 .addReg(0);
10464 MBB->addSuccessor(LoopMBB);
10465
10466 // LoopMBB:
10467 // %OldVal = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
10468 // %SwapVal = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
10469 // %OldValRot = RLL %OldVal, BitSize(%BitShift)
10470 // ^^ The low BitSize bits contain the field
10471 // of interest.
10472 // %RetrySwapVal = RISBG32 %SwapVal, %OldValRot, 32, 63-BitSize, 0
10473 // ^^ Replace the upper 32-BitSize bits of the
10474 // swap value with those that we loaded and rotated.
10475 // %Dest = LL[CH] %OldValRot
10476 // CR %Dest, %CmpVal
10477 // JNE DoneMBB
10478 // # Fall through to SetMBB
10479 MBB = LoopMBB;
10480 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
10481 .addReg(OrigOldVal).addMBB(StartMBB)
10482 .addReg(RetryOldVal).addMBB(SetMBB);
10483 BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
10484 .addReg(OrigSwapVal).addMBB(StartMBB)
10485 .addReg(RetrySwapVal).addMBB(SetMBB);
10486 BuildMI(MBB, DL, TII->get(SystemZ::RLL), OldValRot)
10487 .addReg(OldVal).addReg(BitShift).addImm(BitSize);
10488 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
10489 .addReg(SwapVal)
10490 .addReg(OldValRot)
10491 .addImm(32)
10492 .addImm(63 - BitSize)
10493 .addImm(0)
10494 .setOperandDead(6);
10495 BuildMI(MBB, DL, TII->get(ZExtOpcode), Dest)
10496 .addReg(OldValRot);
10497 BuildMI(MBB, DL, TII->get(SystemZ::CR))
10498 .addReg(Dest).addReg(CmpVal);
10499 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10502 MBB->addSuccessor(DoneMBB);
10503 MBB->addSuccessor(SetMBB);
10504
10505 // SetMBB:
10506 // %StoreVal = RLL %RetrySwapVal, -BitSize(%NegBitShift)
10507 // ^^ Rotate the new field to its proper position.
10508 // %RetryOldVal = CS %OldVal, %StoreVal, Disp(%Base)
10509 // JNE LoopMBB
10510 // # fall through to ExitMBB
10511 MBB = SetMBB;
10512 BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
10513 .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
10514 BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
10515 .addReg(OldVal)
10516 .addReg(StoreVal)
10517 .add(Base)
10518 .addImm(Disp);
10519 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10521 MBB->addSuccessor(LoopMBB);
10522 MBB->addSuccessor(DoneMBB);
10523
10524 // If the CC def wasn't dead in the ATOMIC_CMP_SWAPW, mark CC as live-in
10525 // to the block after the loop. At this point, CC may have been defined
10526 // either by the CR in LoopMBB or by the CS in SetMBB.
10527 if (!MI.registerDefIsDead(SystemZ::CC, /*TRI=*/nullptr))
10528 DoneMBB->addLiveIn(SystemZ::CC);
10529
10530 MI.eraseFromParent();
10531 return DoneMBB;
10532}
10533
10534// Emit a move from two GR64s to a GR128.
10536SystemZTargetLowering::emitPair128(MachineInstr &MI,
10537 MachineBasicBlock *MBB) const {
10538 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10539 const DebugLoc &DL = MI.getDebugLoc();
10540
10541 Register Dest = MI.getOperand(0).getReg();
10542 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest)
10543 .add(MI.getOperand(1))
10544 .addImm(SystemZ::subreg_h64)
10545 .add(MI.getOperand(2))
10546 .addImm(SystemZ::subreg_l64);
10547 MI.eraseFromParent();
10548 return MBB;
10549}
10550
10551// Emit an extension from a GR64 to a GR128. ClearEven is true
10552// if the high register of the GR128 value must be cleared or false if
10553// it's "don't care".
10554MachineBasicBlock *SystemZTargetLowering::emitExt128(MachineInstr &MI,
10556 bool ClearEven) const {
10557 MachineFunction &MF = *MBB->getParent();
10558 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10559 MachineRegisterInfo &MRI = MF.getRegInfo();
10560 DebugLoc DL = MI.getDebugLoc();
10561
10562 Register Dest = MI.getOperand(0).getReg();
10563 Register Src = MI.getOperand(1).getReg();
10564 Register In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
10565
10566 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128);
10567 if (ClearEven) {
10568 Register NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
10569 Register Zero64 = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
10570
10571 BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64)
10572 .addImm(0);
10573 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128)
10574 .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_h64);
10575 In128 = NewIn128;
10576 }
10577 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
10578 .addReg(In128).addReg(Src).addImm(SystemZ::subreg_l64);
10579
10580 MI.eraseFromParent();
10581 return MBB;
10582}
10583
10585SystemZTargetLowering::emitMemMemWrapper(MachineInstr &MI,
10587 unsigned Opcode, bool IsMemset) const {
10588 MachineFunction &MF = *MBB->getParent();
10589 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10590 MachineRegisterInfo &MRI = MF.getRegInfo();
10591 DebugLoc DL = MI.getDebugLoc();
10592
10593 MachineOperand DestBase = earlyUseOperand(MI.getOperand(0));
10594 uint64_t DestDisp = MI.getOperand(1).getImm();
10595 MachineOperand SrcBase = MachineOperand::CreateReg(0U, false);
10596 uint64_t SrcDisp;
10597
10598 // Fold the displacement Disp if it is out of range.
10599 auto foldDisplIfNeeded = [&](MachineOperand &Base, uint64_t &Disp) -> void {
10600 if (!isUInt<12>(Disp)) {
10601 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10602 unsigned Opcode = TII->getOpcodeForOffset(SystemZ::LA, Disp);
10603 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII->get(Opcode), Reg)
10604 .add(Base).addImm(Disp).addReg(0);
10606 Disp = 0;
10607 }
10608 };
10609
10610 if (!IsMemset) {
10611 SrcBase = earlyUseOperand(MI.getOperand(2));
10612 SrcDisp = MI.getOperand(3).getImm();
10613 } else {
10614 SrcBase = DestBase;
10615 SrcDisp = DestDisp++;
10616 foldDisplIfNeeded(DestBase, DestDisp);
10617 }
10618
10619 MachineOperand &LengthMO = MI.getOperand(IsMemset ? 2 : 4);
10620 bool IsImmForm = LengthMO.isImm();
10621 bool IsRegForm = !IsImmForm;
10622
10623 // Build and insert one Opcode of Length, with special treatment for memset.
10624 auto insertMemMemOp = [&](MachineBasicBlock *InsMBB,
10626 MachineOperand DBase, uint64_t DDisp,
10627 MachineOperand SBase, uint64_t SDisp,
10628 unsigned Length) -> void {
10629 assert(Length > 0 && Length <= 256 && "Building memory op with bad length.");
10630 if (IsMemset) {
10631 MachineOperand ByteMO = earlyUseOperand(MI.getOperand(3));
10632 if (ByteMO.isImm())
10633 BuildMI(*InsMBB, InsPos, DL, TII->get(SystemZ::MVI))
10634 .add(SBase).addImm(SDisp).add(ByteMO);
10635 else
10636 BuildMI(*InsMBB, InsPos, DL, TII->get(SystemZ::STC))
10637 .add(ByteMO).add(SBase).addImm(SDisp).addReg(0);
10638 if (--Length == 0)
10639 return;
10640 }
10641 BuildMI(*MBB, InsPos, DL, TII->get(Opcode))
10642 .add(DBase).addImm(DDisp).addImm(Length)
10643 .add(SBase).addImm(SDisp)
10644 .setMemRefs(MI.memoperands());
10645 };
10646
10647 bool NeedsLoop = false;
10648 uint64_t ImmLength = 0;
10649 Register LenAdjReg = SystemZ::NoRegister;
10650 if (IsImmForm) {
10651 ImmLength = LengthMO.getImm();
10652 ImmLength += IsMemset ? 2 : 1; // Add back the subtracted adjustment.
10653 if (ImmLength == 0) {
10654 MI.eraseFromParent();
10655 return MBB;
10656 }
10657 if (Opcode == SystemZ::CLC) {
10658 if (ImmLength > 3 * 256)
10659 // A two-CLC sequence is a clear win over a loop, not least because
10660 // it needs only one branch. A three-CLC sequence needs the same
10661 // number of branches as a loop (i.e. 2), but is shorter. That
10662 // brings us to lengths greater than 768 bytes. It seems relatively
10663 // likely that a difference will be found within the first 768 bytes,
10664 // so we just optimize for the smallest number of branch
10665 // instructions, in order to avoid polluting the prediction buffer
10666 // too much.
10667 NeedsLoop = true;
10668 } else if (ImmLength > 6 * 256)
10669 // The heuristic we use is to prefer loops for anything that would
10670 // require 7 or more MVCs. With these kinds of sizes there isn't much
10671 // to choose between straight-line code and looping code, since the
10672 // time will be dominated by the MVCs themselves.
10673 NeedsLoop = true;
10674 } else {
10675 NeedsLoop = true;
10676 LenAdjReg = LengthMO.getReg();
10677 }
10678
10679 // When generating more than one CLC, all but the last will need to
10680 // branch to the end when a difference is found.
10681 MachineBasicBlock *EndMBB =
10682 (Opcode == SystemZ::CLC && (ImmLength > 256 || NeedsLoop)
10684 : nullptr);
10685
10686 if (NeedsLoop) {
10687 Register StartCountReg =
10688 MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
10689 if (IsImmForm) {
10690 TII->loadImmediate(*MBB, MI, StartCountReg, ImmLength / 256);
10691 ImmLength &= 255;
10692 } else {
10693 BuildMI(*MBB, MI, DL, TII->get(SystemZ::SRLG), StartCountReg)
10694 .addReg(LenAdjReg)
10695 .addReg(0)
10696 .addImm(8);
10697 }
10698
10699 bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
10700 auto loadZeroAddress = [&]() -> MachineOperand {
10701 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10702 BuildMI(*MBB, MI, DL, TII->get(SystemZ::LGHI), Reg).addImm(0);
10703 return MachineOperand::CreateReg(Reg, false);
10704 };
10705 if (DestBase.isReg() && DestBase.getReg() == SystemZ::NoRegister)
10706 DestBase = loadZeroAddress();
10707 if (SrcBase.isReg() && SrcBase.getReg() == SystemZ::NoRegister)
10708 SrcBase = HaveSingleBase ? DestBase : loadZeroAddress();
10709
10710 MachineBasicBlock *StartMBB = nullptr;
10711 MachineBasicBlock *LoopMBB = nullptr;
10712 MachineBasicBlock *NextMBB = nullptr;
10713 MachineBasicBlock *DoneMBB = nullptr;
10714 MachineBasicBlock *AllDoneMBB = nullptr;
10715
10716 Register StartSrcReg = forceReg(MI, SrcBase, TII);
10717 Register StartDestReg =
10718 (HaveSingleBase ? StartSrcReg : forceReg(MI, DestBase, TII));
10719
10720 const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
10721 Register ThisSrcReg = MRI.createVirtualRegister(RC);
10722 Register ThisDestReg =
10723 (HaveSingleBase ? ThisSrcReg : MRI.createVirtualRegister(RC));
10724 Register NextSrcReg = MRI.createVirtualRegister(RC);
10725 Register NextDestReg =
10726 (HaveSingleBase ? NextSrcReg : MRI.createVirtualRegister(RC));
10727 RC = &SystemZ::GR64BitRegClass;
10728 Register ThisCountReg = MRI.createVirtualRegister(RC);
10729 Register NextCountReg = MRI.createVirtualRegister(RC);
10730
10731 if (IsRegForm) {
10732 AllDoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10733 StartMBB = SystemZ::emitBlockAfter(MBB);
10734 LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10735 NextMBB = (EndMBB ? SystemZ::emitBlockAfter(LoopMBB) : LoopMBB);
10736 DoneMBB = SystemZ::emitBlockAfter(NextMBB);
10737
10738 // MBB:
10739 // # Jump to AllDoneMBB if LenAdjReg means 0, or fall thru to StartMBB.
10740 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10741 .addReg(LenAdjReg).addImm(IsMemset ? -2 : -1);
10742 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10744 .addMBB(AllDoneMBB);
10745 MBB->addSuccessor(AllDoneMBB);
10746 if (!IsMemset)
10747 MBB->addSuccessor(StartMBB);
10748 else {
10749 // MemsetOneCheckMBB:
10750 // # Jump to MemsetOneMBB for a memset of length 1, or
10751 // # fall thru to StartMBB.
10752 MachineBasicBlock *MemsetOneCheckMBB = SystemZ::emitBlockAfter(MBB);
10753 MachineBasicBlock *MemsetOneMBB = SystemZ::emitBlockAfter(&*MF.rbegin());
10754 MBB->addSuccessor(MemsetOneCheckMBB);
10755 MBB = MemsetOneCheckMBB;
10756 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10757 .addReg(LenAdjReg).addImm(-1);
10758 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10760 .addMBB(MemsetOneMBB);
10761 MBB->addSuccessor(MemsetOneMBB, {10, 100});
10762 MBB->addSuccessor(StartMBB, {90, 100});
10763
10764 // MemsetOneMBB:
10765 // # Jump back to AllDoneMBB after a single MVI or STC.
10766 MBB = MemsetOneMBB;
10767 insertMemMemOp(MBB, MBB->end(),
10768 MachineOperand::CreateReg(StartDestReg, false), DestDisp,
10769 MachineOperand::CreateReg(StartSrcReg, false), SrcDisp,
10770 1);
10771 BuildMI(MBB, DL, TII->get(SystemZ::J)).addMBB(AllDoneMBB);
10772 MBB->addSuccessor(AllDoneMBB);
10773 }
10774
10775 // StartMBB:
10776 // # Jump to DoneMBB if %StartCountReg is zero, or fall through to LoopMBB.
10777 MBB = StartMBB;
10778 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10779 .addReg(StartCountReg).addImm(0);
10780 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10782 .addMBB(DoneMBB);
10783 MBB->addSuccessor(DoneMBB);
10784 MBB->addSuccessor(LoopMBB);
10785 }
10786 else {
10787 StartMBB = MBB;
10788 DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10789 LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10790 NextMBB = (EndMBB ? SystemZ::emitBlockAfter(LoopMBB) : LoopMBB);
10791
10792 // StartMBB:
10793 // # fall through to LoopMBB
10794 MBB->addSuccessor(LoopMBB);
10795
10796 DestBase = MachineOperand::CreateReg(NextDestReg, false);
10797 SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
10798 if (EndMBB && !ImmLength)
10799 // If the loop handled the whole CLC range, DoneMBB will be empty with
10800 // CC live-through into EndMBB, so add it as live-in.
10801 DoneMBB->addLiveIn(SystemZ::CC);
10802 }
10803
10804 // LoopMBB:
10805 // %ThisDestReg = phi [ %StartDestReg, StartMBB ],
10806 // [ %NextDestReg, NextMBB ]
10807 // %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
10808 // [ %NextSrcReg, NextMBB ]
10809 // %ThisCountReg = phi [ %StartCountReg, StartMBB ],
10810 // [ %NextCountReg, NextMBB ]
10811 // ( PFD 2, 768+DestDisp(%ThisDestReg) )
10812 // Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
10813 // ( JLH EndMBB )
10814 //
10815 // The prefetch is used only for MVC. The JLH is used only for CLC.
10816 MBB = LoopMBB;
10817 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
10818 .addReg(StartDestReg).addMBB(StartMBB)
10819 .addReg(NextDestReg).addMBB(NextMBB);
10820 if (!HaveSingleBase)
10821 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
10822 .addReg(StartSrcReg).addMBB(StartMBB)
10823 .addReg(NextSrcReg).addMBB(NextMBB);
10824 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
10825 .addReg(StartCountReg).addMBB(StartMBB)
10826 .addReg(NextCountReg).addMBB(NextMBB);
10827 if (Opcode == SystemZ::MVC)
10828 BuildMI(MBB, DL, TII->get(SystemZ::PFD))
10830 .addReg(ThisDestReg).addImm(DestDisp - IsMemset + 768).addReg(0);
10831 insertMemMemOp(MBB, MBB->end(),
10832 MachineOperand::CreateReg(ThisDestReg, false), DestDisp,
10833 MachineOperand::CreateReg(ThisSrcReg, false), SrcDisp, 256);
10834 if (EndMBB) {
10835 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10837 .addMBB(EndMBB);
10838 MBB->addSuccessor(EndMBB);
10839 MBB->addSuccessor(NextMBB);
10840 }
10841
10842 // NextMBB:
10843 // %NextDestReg = LA 256(%ThisDestReg)
10844 // %NextSrcReg = LA 256(%ThisSrcReg)
10845 // %NextCountReg = AGHI %ThisCountReg, -1
10846 // CGHI %NextCountReg, 0
10847 // JLH LoopMBB
10848 // # fall through to DoneMBB
10849 //
10850 // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
10851 MBB = NextMBB;
10852 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
10853 .addReg(ThisDestReg).addImm(256).addReg(0);
10854 if (!HaveSingleBase)
10855 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
10856 .addReg(ThisSrcReg).addImm(256).addReg(0);
10857 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
10858 .addReg(ThisCountReg)
10859 .addImm(-1)
10860 .setOperandDead(3);
10861 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10862 .addReg(NextCountReg).addImm(0);
10863 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10865 .addMBB(LoopMBB);
10866 MBB->addSuccessor(LoopMBB);
10867 MBB->addSuccessor(DoneMBB);
10868
10869 MBB = DoneMBB;
10870 if (IsRegForm) {
10871 // DoneMBB:
10872 // # Make PHIs for RemDestReg/RemSrcReg as the loop may or may not run.
10873 // # Use EXecute Relative Long for the remainder of the bytes. The target
10874 // instruction of the EXRL will have a length field of 1 since 0 is an
10875 // illegal value. The number of bytes processed becomes (%LenAdjReg &
10876 // 0xff) + 1.
10877 // # Fall through to AllDoneMBB.
10878 Register RemSrcReg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10879 Register RemDestReg = HaveSingleBase ? RemSrcReg
10880 : MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10881 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RemDestReg)
10882 .addReg(StartDestReg).addMBB(StartMBB)
10883 .addReg(NextDestReg).addMBB(NextMBB);
10884 if (!HaveSingleBase)
10885 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RemSrcReg)
10886 .addReg(StartSrcReg).addMBB(StartMBB)
10887 .addReg(NextSrcReg).addMBB(NextMBB);
10888 if (IsMemset)
10889 insertMemMemOp(MBB, MBB->end(),
10890 MachineOperand::CreateReg(RemDestReg, false), DestDisp,
10891 MachineOperand::CreateReg(RemSrcReg, false), SrcDisp, 1);
10892 MachineInstrBuilder EXRL_MIB =
10893 BuildMI(MBB, DL, TII->get(SystemZ::EXRL_Pseudo))
10894 .addImm(Opcode)
10895 .addReg(LenAdjReg)
10896 .addReg(RemDestReg).addImm(DestDisp)
10897 .addReg(RemSrcReg).addImm(SrcDisp);
10898 MBB->addSuccessor(AllDoneMBB);
10899 MBB = AllDoneMBB;
10900 if (Opcode != SystemZ::MVC) {
10901 EXRL_MIB.addReg(SystemZ::CC, RegState::ImplicitDefine);
10902 if (EndMBB)
10903 MBB->addLiveIn(SystemZ::CC);
10904 }
10905 }
10906 MF.getProperties().resetNoPHIs();
10907 }
10908
10909 // Handle any remaining bytes with straight-line code.
10910 while (ImmLength > 0) {
10911 uint64_t ThisLength = std::min(ImmLength, uint64_t(256));
10912 // The previous iteration might have created out-of-range displacements.
10913 // Apply them using LA/LAY if so.
10914 foldDisplIfNeeded(DestBase, DestDisp);
10915 foldDisplIfNeeded(SrcBase, SrcDisp);
10916 insertMemMemOp(MBB, MI, DestBase, DestDisp, SrcBase, SrcDisp, ThisLength);
10917 DestDisp += ThisLength;
10918 SrcDisp += ThisLength;
10919 ImmLength -= ThisLength;
10920 // If there's another CLC to go, branch to the end if a difference
10921 // was found.
10922 if (EndMBB && ImmLength > 0) {
10923 MachineBasicBlock *NextMBB = SystemZ::splitBlockBefore(MI, MBB);
10924 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10926 .addMBB(EndMBB);
10927 MBB->addSuccessor(EndMBB);
10928 MBB->addSuccessor(NextMBB);
10929 MBB = NextMBB;
10930 }
10931 }
10932 if (EndMBB) {
10933 MBB->addSuccessor(EndMBB);
10934 MBB = EndMBB;
10935 MBB->addLiveIn(SystemZ::CC);
10936 }
10937
10938 MI.eraseFromParent();
10939 return MBB;
10940}
10941
10943SystemZTargetLowering::emitMemmoveImm(MachineInstr &MI,
10944 MachineBasicBlock *MBB) const {
10945 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10946
10947 DebugLoc DL = MI.getDebugLoc();
10948 MachineOperand DstAddr = earlyUseOperand(MI.getOperand(0));
10949 MachineOperand SrcAddr = earlyUseOperand(MI.getOperand(1));
10950 uint64_t Len = MI.getOperand(2).getImm();
10951 assert(Len > 0 && Len <= 256 && "Memmove of of unsupported constant length.");
10952
10953 // Use MVC or MVCRL after comparing the addresses.
10954 MachineBasicBlock *DoneMBB = SystemZ::splitBlockAfter(MI, MBB);
10955 MachineBasicBlock *MvcMBB = SystemZ::emitBlockAfter(MBB);
10956 MachineBasicBlock *MvcrlMBB = SystemZ::emitBlockAfter(MvcMBB);
10957 MBB->addSuccessor(MvcMBB);
10958 MBB->addSuccessor(MvcrlMBB);
10959 MvcMBB->addSuccessor(DoneMBB);
10960 MvcrlMBB->addSuccessor(DoneMBB);
10961
10962 BuildMI(MBB, DL, TII->get(SystemZ::CLGR)).add(SrcAddr).add(DstAddr);
10963 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10965 .addMBB(MvcrlMBB);
10966
10967 BuildMI(MvcMBB, DL, TII->get(SystemZ::MVC))
10968 .add(DstAddr).addImm(0)
10969 .addImm(Len)
10970 .add(SrcAddr).addImm(0)
10971 .setMemRefs(MI.memoperands());
10972 BuildMI(MvcMBB, DL, TII->get(SystemZ::J)).addMBB(DoneMBB);
10973
10974 BuildMI(MvcrlMBB, DL, TII->get(SystemZ::LHI), SystemZ::R0L).addImm(Len - 1);
10975 BuildMI(MvcrlMBB, DL, TII->get(SystemZ::MVCRL))
10976 .add(DstAddr).addImm(0)
10977 .add(SrcAddr).addImm(0)
10978 .setMemRefs(MI.memoperands());
10979
10980 MI.eraseFromParent();
10981 return DoneMBB;
10982}
10983
10984// Decompose string pseudo-instruction MI into a loop that continually performs
10985// Opcode until CC != 3.
10986MachineBasicBlock *SystemZTargetLowering::emitStringWrapper(
10987 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
10988 MachineFunction &MF = *MBB->getParent();
10989 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10990 MachineRegisterInfo &MRI = MF.getRegInfo();
10991 DebugLoc DL = MI.getDebugLoc();
10992
10993 uint64_t End1Reg = MI.getOperand(0).getReg();
10994 uint64_t Start1Reg = MI.getOperand(1).getReg();
10995 uint64_t Start2Reg = MI.getOperand(2).getReg();
10996 uint64_t CharReg = MI.getOperand(3).getReg();
10997
10998 const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
10999 uint64_t This1Reg = MRI.createVirtualRegister(RC);
11000 uint64_t This2Reg = MRI.createVirtualRegister(RC);
11001 uint64_t End2Reg = MRI.createVirtualRegister(RC);
11002
11003 MachineBasicBlock *StartMBB = MBB;
11004 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
11005 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
11006
11007 // StartMBB:
11008 // # fall through to LoopMBB
11009 MBB->addSuccessor(LoopMBB);
11010
11011 // LoopMBB:
11012 // %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
11013 // %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
11014 // R0L = %CharReg
11015 // %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
11016 // JO LoopMBB
11017 // # fall through to DoneMBB
11018 //
11019 // The load of R0L can be hoisted by post-RA LICM.
11020 MBB = LoopMBB;
11021
11022 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
11023 .addReg(Start1Reg).addMBB(StartMBB)
11024 .addReg(End1Reg).addMBB(LoopMBB);
11025 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
11026 .addReg(Start2Reg).addMBB(StartMBB)
11027 .addReg(End2Reg).addMBB(LoopMBB);
11028 BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
11029 BuildMI(MBB, DL, TII->get(Opcode))
11030 .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
11031 .addReg(This1Reg).addReg(This2Reg);
11032 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11034 MBB->addSuccessor(LoopMBB);
11035 MBB->addSuccessor(DoneMBB);
11036
11037 DoneMBB->addLiveIn(SystemZ::CC);
11038
11039 MI.eraseFromParent();
11040 return DoneMBB;
11041}
11042
11043// Update TBEGIN instruction with final opcode and register clobbers.
11044MachineBasicBlock *SystemZTargetLowering::emitTransactionBegin(
11045 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode,
11046 bool NoFloat) const {
11047 MachineFunction &MF = *MBB->getParent();
11048 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11049 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11050
11051 // Update opcode.
11052 MI.setDesc(TII->get(Opcode));
11053
11054 // We cannot handle a TBEGIN that clobbers the stack or frame pointer.
11055 // Make sure to add the corresponding GRSM bits if they are missing.
11056 uint64_t Control = MI.getOperand(2).getImm();
11057 static const unsigned GPRControlBit[16] = {
11058 0x8000, 0x8000, 0x4000, 0x4000, 0x2000, 0x2000, 0x1000, 0x1000,
11059 0x0800, 0x0800, 0x0400, 0x0400, 0x0200, 0x0200, 0x0100, 0x0100
11060 };
11061 Control |= GPRControlBit[15];
11062 if (TFI->hasFP(MF))
11063 Control |= GPRControlBit[11];
11064 MI.getOperand(2).setImm(Control);
11065
11066 // Add GPR clobbers.
11067 for (int I = 0; I < 16; I++) {
11068 if ((Control & GPRControlBit[I]) == 0) {
11069 unsigned Reg = SystemZMC::GR64Regs[I];
11070 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
11071 }
11072 }
11073
11074 // Add FPR/VR clobbers.
11075 if (!NoFloat && (Control & 4) != 0) {
11076 if (Subtarget.hasVector()) {
11077 for (unsigned Reg : SystemZMC::VR128Regs) {
11078 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
11079 }
11080 } else {
11081 for (unsigned Reg : SystemZMC::FP64Regs) {
11082 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
11083 }
11084 }
11085 }
11086
11087 return MBB;
11088}
11089
11090MachineBasicBlock *SystemZTargetLowering::emitLoadAndTestCmp0(
11091 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
11092 MachineFunction &MF = *MBB->getParent();
11093 MachineRegisterInfo *MRI = &MF.getRegInfo();
11094 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11095 DebugLoc DL = MI.getDebugLoc();
11096
11097 Register SrcReg = MI.getOperand(0).getReg();
11098
11099 // Create new virtual register of the same class as source.
11100 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
11101 Register DstReg = MRI->createVirtualRegister(RC);
11102
11103 // Replace pseudo with a normal load-and-test that models the def as
11104 // well.
11105 BuildMI(*MBB, MI, DL, TII->get(Opcode), DstReg)
11106 .addReg(SrcReg)
11107 .setMIFlags(MI.getFlags());
11108 MI.eraseFromParent();
11109
11110 return MBB;
11111}
11112
11113MachineBasicBlock *SystemZTargetLowering::emitProbedAlloca(
11115 MachineFunction &MF = *MBB->getParent();
11116 MachineRegisterInfo *MRI = &MF.getRegInfo();
11117 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11118 DebugLoc DL = MI.getDebugLoc();
11119 const unsigned ProbeSize = getStackProbeSize(MF);
11120 Register DstReg = MI.getOperand(0).getReg();
11121 Register SizeReg = MI.getOperand(2).getReg();
11122
11123 MachineBasicBlock *StartMBB = MBB;
11124 MachineBasicBlock *DoneMBB = SystemZ::splitBlockAfter(MI, MBB);
11125 MachineBasicBlock *LoopTestMBB = SystemZ::emitBlockAfter(StartMBB);
11126 MachineBasicBlock *LoopBodyMBB = SystemZ::emitBlockAfter(LoopTestMBB);
11127 MachineBasicBlock *TailTestMBB = SystemZ::emitBlockAfter(LoopBodyMBB);
11128 MachineBasicBlock *TailMBB = SystemZ::emitBlockAfter(TailTestMBB);
11129
11130 MachineMemOperand *VolLdMMO = MF.getMachineMemOperand(MachinePointerInfo(),
11132
11133 Register PHIReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11134 Register IncReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11135
11136 // LoopTestMBB
11137 // BRC TailTestMBB
11138 // # fallthrough to LoopBodyMBB
11139 StartMBB->addSuccessor(LoopTestMBB);
11140 MBB = LoopTestMBB;
11141 BuildMI(MBB, DL, TII->get(SystemZ::PHI), PHIReg)
11142 .addReg(SizeReg)
11143 .addMBB(StartMBB)
11144 .addReg(IncReg)
11145 .addMBB(LoopBodyMBB);
11146 BuildMI(MBB, DL, TII->get(SystemZ::CLGFI))
11147 .addReg(PHIReg)
11148 .addImm(ProbeSize);
11149 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11151 .addMBB(TailTestMBB);
11152 MBB->addSuccessor(LoopBodyMBB);
11153 MBB->addSuccessor(TailTestMBB);
11154
11155 // LoopBodyMBB: Allocate and probe by means of a volatile compare.
11156 // J LoopTestMBB
11157 MBB = LoopBodyMBB;
11158 BuildMI(MBB, DL, TII->get(SystemZ::SLGFI), IncReg)
11159 .addReg(PHIReg)
11160 .addImm(ProbeSize)
11161 .setOperandDead(3);
11162 BuildMI(MBB, DL, TII->get(SystemZ::SLGFI), SystemZ::R15D)
11163 .addReg(SystemZ::R15D)
11164 .addImm(ProbeSize)
11165 .setOperandDead(3);
11166 BuildMI(MBB, DL, TII->get(SystemZ::CG))
11167 .addReg(SystemZ::R15D)
11168 .addReg(SystemZ::R15D)
11169 .addImm(ProbeSize - 8)
11170 .addReg(0)
11171 .setOperandDead(4)
11172 .setMemRefs(VolLdMMO);
11173 BuildMI(MBB, DL, TII->get(SystemZ::J)).addMBB(LoopTestMBB);
11174 MBB->addSuccessor(LoopTestMBB);
11175
11176 // TailTestMBB
11177 // BRC DoneMBB
11178 // # fallthrough to TailMBB
11179 MBB = TailTestMBB;
11180 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
11181 .addReg(PHIReg)
11182 .addImm(0);
11183 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11185 .addMBB(DoneMBB);
11186 MBB->addSuccessor(TailMBB);
11187 MBB->addSuccessor(DoneMBB);
11188
11189 // TailMBB
11190 // # fallthrough to DoneMBB
11191 MBB = TailMBB;
11192 BuildMI(MBB, DL, TII->get(SystemZ::SLGR), SystemZ::R15D)
11193 .addReg(SystemZ::R15D)
11194 .addReg(PHIReg)
11195 .setOperandDead(3);
11196 BuildMI(MBB, DL, TII->get(SystemZ::CG))
11197 .addReg(SystemZ::R15D)
11198 .addReg(SystemZ::R15D)
11199 .addImm(-8)
11200 .addReg(PHIReg)
11201 .setOperandDead(4)
11202 .setMemRefs(VolLdMMO);
11203 MBB->addSuccessor(DoneMBB);
11204
11205 // DoneMBB
11206 MBB = DoneMBB;
11207 BuildMI(*MBB, MBB->begin(), DL, TII->get(TargetOpcode::COPY), DstReg)
11208 .addReg(SystemZ::R15D);
11209
11210 MI.eraseFromParent();
11211 return DoneMBB;
11212}
11213
11214SDValue SystemZTargetLowering::
11215getBackchainAddress(SDValue SP, SelectionDAG &DAG) const {
11217 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>();
11218 SDLoc DL(SP);
11219 return DAG.getNode(ISD::ADD, DL, MVT::i64, SP,
11220 DAG.getIntPtrConstant(TFL->getBackchainOffset(MF), DL));
11221}
11222
11223// Replace a _STACKGUARD_DAG pseudo with a _STACKGUARD pseudo, adding
11224// a dead early-clobber def reg that will be used as a scratch register
11225// when the pseudo is expanded.
11226MachineBasicBlock *SystemZTargetLowering::emitStackGuardPseudo(
11227 MachineInstr &MI, MachineBasicBlock *MBB, unsigned PseudoOp) const {
11228 MachineRegisterInfo *MRI = &MBB->getParent()->getRegInfo();
11229 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11230 DebugLoc DL = MI.getDebugLoc();
11231 Register AddrReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11232 BuildMI(*MBB, MI, DL, TII->get(PseudoOp), AddrReg)
11233 .addFrameIndex(MI.getOperand(0).getIndex())
11234 .addImm(MI.getOperand(1).getImm());
11235 MI.eraseFromParent();
11236 return MBB;
11237}
11238
11241 switch (MI.getOpcode()) {
11242 case SystemZ::ADJCALLSTACKDOWN:
11243 case SystemZ::ADJCALLSTACKUP:
11244 return emitAdjCallStack(MI, MBB);
11245
11246 case SystemZ::Select32:
11247 case SystemZ::Select64:
11248 case SystemZ::Select128:
11249 case SystemZ::SelectF32:
11250 case SystemZ::SelectF64:
11251 case SystemZ::SelectF128:
11252 case SystemZ::SelectVR32:
11253 case SystemZ::SelectVR64:
11254 case SystemZ::SelectVR128:
11255 return emitSelect(MI, MBB);
11256
11257 case SystemZ::CondStore8Mux:
11258 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
11259 case SystemZ::CondStore8MuxInv:
11260 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
11261 case SystemZ::CondStore16Mux:
11262 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
11263 case SystemZ::CondStore16MuxInv:
11264 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
11265 case SystemZ::CondStore32Mux:
11266 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, false);
11267 case SystemZ::CondStore32MuxInv:
11268 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, true);
11269 case SystemZ::CondStore8:
11270 return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
11271 case SystemZ::CondStore8Inv:
11272 return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
11273 case SystemZ::CondStore16:
11274 return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
11275 case SystemZ::CondStore16Inv:
11276 return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
11277 case SystemZ::CondStore32:
11278 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
11279 case SystemZ::CondStore32Inv:
11280 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
11281 case SystemZ::CondStore64:
11282 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
11283 case SystemZ::CondStore64Inv:
11284 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
11285 case SystemZ::CondStoreF32:
11286 return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
11287 case SystemZ::CondStoreF32Inv:
11288 return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
11289 case SystemZ::CondStoreF64:
11290 return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
11291 case SystemZ::CondStoreF64Inv:
11292 return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
11293
11294 case SystemZ::SCmp128Hi:
11295 return emitICmp128Hi(MI, MBB, false);
11296 case SystemZ::UCmp128Hi:
11297 return emitICmp128Hi(MI, MBB, true);
11298
11299 case SystemZ::PAIR128:
11300 return emitPair128(MI, MBB);
11301 case SystemZ::AEXT128:
11302 return emitExt128(MI, MBB, false);
11303 case SystemZ::ZEXT128:
11304 return emitExt128(MI, MBB, true);
11305
11306 case SystemZ::ATOMIC_SWAPW:
11307 return emitAtomicLoadBinary(MI, MBB, 0);
11308
11309 case SystemZ::ATOMIC_LOADW_AR:
11310 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR);
11311 case SystemZ::ATOMIC_LOADW_AFI:
11312 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI);
11313
11314 case SystemZ::ATOMIC_LOADW_SR:
11315 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR);
11316
11317 case SystemZ::ATOMIC_LOADW_NR:
11318 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR);
11319 case SystemZ::ATOMIC_LOADW_NILH:
11320 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH);
11321
11322 case SystemZ::ATOMIC_LOADW_OR:
11323 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR);
11324 case SystemZ::ATOMIC_LOADW_OILH:
11325 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH);
11326
11327 case SystemZ::ATOMIC_LOADW_XR:
11328 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR);
11329 case SystemZ::ATOMIC_LOADW_XILF:
11330 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF);
11331
11332 case SystemZ::ATOMIC_LOADW_NRi:
11333 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, true);
11334 case SystemZ::ATOMIC_LOADW_NILHi:
11335 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, true);
11336
11337 case SystemZ::ATOMIC_LOADW_MIN:
11338 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR, SystemZ::CCMASK_CMP_LE);
11339 case SystemZ::ATOMIC_LOADW_MAX:
11340 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR, SystemZ::CCMASK_CMP_GE);
11341 case SystemZ::ATOMIC_LOADW_UMIN:
11342 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR, SystemZ::CCMASK_CMP_LE);
11343 case SystemZ::ATOMIC_LOADW_UMAX:
11344 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR, SystemZ::CCMASK_CMP_GE);
11345
11346 case SystemZ::ATOMIC_CMP_SWAPW:
11347 return emitAtomicCmpSwapW(MI, MBB);
11348 case SystemZ::MVCImm:
11349 case SystemZ::MVCReg:
11350 return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
11351 case SystemZ::NCImm:
11352 return emitMemMemWrapper(MI, MBB, SystemZ::NC);
11353 case SystemZ::OCImm:
11354 return emitMemMemWrapper(MI, MBB, SystemZ::OC);
11355 case SystemZ::XCImm:
11356 case SystemZ::XCReg:
11357 return emitMemMemWrapper(MI, MBB, SystemZ::XC);
11358 case SystemZ::CLCImm:
11359 case SystemZ::CLCReg:
11360 return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
11361 case SystemZ::MemsetImmImm:
11362 case SystemZ::MemsetImmReg:
11363 case SystemZ::MemsetRegImm:
11364 case SystemZ::MemsetRegReg:
11365 return emitMemMemWrapper(MI, MBB, SystemZ::MVC, true/*IsMemset*/);
11366 case SystemZ::MemmoveImm:
11367 return emitMemmoveImm(MI, MBB);
11368 case SystemZ::CLSTLoop:
11369 return emitStringWrapper(MI, MBB, SystemZ::CLST);
11370 case SystemZ::MVSTLoop:
11371 return emitStringWrapper(MI, MBB, SystemZ::MVST);
11372 case SystemZ::SRSTLoop:
11373 return emitStringWrapper(MI, MBB, SystemZ::SRST);
11374 case SystemZ::TBEGIN:
11375 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, false);
11376 case SystemZ::TBEGIN_nofloat:
11377 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, true);
11378 case SystemZ::TBEGINC:
11379 return emitTransactionBegin(MI, MBB, SystemZ::TBEGINC, true);
11380 case SystemZ::LTEBRCompare_Pseudo:
11381 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTEBR);
11382 case SystemZ::LTDBRCompare_Pseudo:
11383 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTDBR);
11384 case SystemZ::LTXBRCompare_Pseudo:
11385 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTXBR);
11386
11387 case SystemZ::PROBED_ALLOCA:
11388 return emitProbedAlloca(MI, MBB);
11389 case SystemZ::EH_SjLj_SetJmp:
11390 return emitEHSjLjSetJmp(MI, MBB);
11391 case SystemZ::EH_SjLj_LongJmp:
11392 return emitEHSjLjLongJmp(MI, MBB);
11393
11394 case TargetOpcode::STACKMAP:
11395 case TargetOpcode::PATCHPOINT:
11396 return emitPatchPoint(MI, MBB);
11397
11398 case SystemZ::MOV_STACKGUARD_DAG:
11399 return emitStackGuardPseudo(MI, MBB, SystemZ::MOV_STACKGUARD);
11400
11401 case SystemZ::CMP_STACKGUARD_DAG:
11402 return emitStackGuardPseudo(MI, MBB, SystemZ::CMP_STACKGUARD);
11403
11404 default:
11405 llvm_unreachable("Unexpected instr type to insert");
11406 }
11407}
11408
11409// This is only used by the isel schedulers, and is needed only to prevent
11410// compiler from crashing when list-ilp is used.
11411const TargetRegisterClass *
11412SystemZTargetLowering::getRepRegClassFor(MVT VT) const {
11413 if (VT == MVT::Untyped)
11414 return &SystemZ::ADDR128BitRegClass;
11416}
11417
11418SDValue SystemZTargetLowering::lowerGET_ROUNDING(SDValue Op,
11419 SelectionDAG &DAG) const {
11420 SDLoc dl(Op);
11421 /*
11422 The rounding method is in FPC Byte 3 bits 6-7, and has the following
11423 settings:
11424 00 Round to nearest
11425 01 Round to 0
11426 10 Round to +inf
11427 11 Round to -inf
11428
11429 FLT_ROUNDS, on the other hand, expects the following:
11430 -1 Undefined
11431 0 Round to 0
11432 1 Round to nearest
11433 2 Round to +inf
11434 3 Round to -inf
11435 */
11436
11437 // Save FPC to register.
11438 SDValue Chain = Op.getOperand(0);
11439 SDValue EFPC(
11440 DAG.getMachineNode(SystemZ::EFPC, dl, {MVT::i32, MVT::Other}, Chain), 0);
11441 Chain = EFPC.getValue(1);
11442
11443 // Transform as necessary
11444 SDValue CWD1 = DAG.getNode(ISD::AND, dl, MVT::i32, EFPC,
11445 DAG.getConstant(3, dl, MVT::i32));
11446 // RetVal = (CWD1 ^ (CWD1 >> 1)) ^ 1
11447 SDValue CWD2 = DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1,
11448 DAG.getNode(ISD::SRL, dl, MVT::i32, CWD1,
11449 DAG.getConstant(1, dl, MVT::i32)));
11450
11451 SDValue RetVal = DAG.getNode(ISD::XOR, dl, MVT::i32, CWD2,
11452 DAG.getConstant(1, dl, MVT::i32));
11453 RetVal = DAG.getZExtOrTrunc(RetVal, dl, Op.getValueType());
11454
11455 return DAG.getMergeValues({RetVal, Chain}, dl);
11456}
11457
11458SDValue SystemZTargetLowering::lowerVECREDUCE_ADD(SDValue Op,
11459 SelectionDAG &DAG) const {
11460 EVT VT = Op.getValueType();
11461 Op = Op.getOperand(0);
11462 EVT OpVT = Op.getValueType();
11463
11464 assert(OpVT.isVector() && "Operand type for VECREDUCE_ADD is not a vector.");
11465
11466 SDLoc DL(Op);
11467
11468 // load a 0 vector for the third operand of VSUM.
11469 SDValue Zero = DAG.getSplatBuildVector(OpVT, DL, DAG.getConstant(0, DL, VT));
11470
11471 // execute VSUM.
11472 switch (OpVT.getScalarSizeInBits()) {
11473 case 8:
11474 case 16:
11475 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Zero);
11476 [[fallthrough]];
11477 case 32:
11478 case 64:
11479 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::i128, Op,
11480 DAG.getBitcast(Op.getValueType(), Zero));
11481 break;
11482 case 128:
11483 break; // VSUM over v1i128 should not happen and would be a noop
11484 default:
11485 llvm_unreachable("Unexpected scalar size.");
11486 }
11487 // Cast to original vector type, retrieve last element.
11488 return DAG.getNode(
11489 ISD::EXTRACT_VECTOR_ELT, DL, VT, DAG.getBitcast(OpVT, Op),
11490 DAG.getConstant(OpVT.getVectorNumElements() - 1, DL, MVT::i32));
11491}
11492
11494 FunctionType *FT = F->getFunctionType();
11495 const AttributeList &Attrs = F->getAttributes();
11496 if (Attrs.hasRetAttrs())
11497 OS << Attrs.getAsString(AttributeList::ReturnIndex) << " ";
11498 OS << *F->getReturnType() << " @" << F->getName() << "(";
11499 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
11500 if (I)
11501 OS << ", ";
11502 OS << *FT->getParamType(I);
11503 AttributeSet ArgAttrs = Attrs.getParamAttrs(I);
11504 for (auto A : {Attribute::SExt, Attribute::ZExt, Attribute::NoExt})
11505 if (ArgAttrs.hasAttribute(A))
11506 OS << " " << Attribute::getNameFromAttrKind(A);
11507 }
11508 OS << ")\n";
11509}
11510
11511bool SystemZTargetLowering::isInternal(const Function *Fn) const {
11512 std::map<const Function *, bool>::iterator Itr = IsInternalCache.find(Fn);
11513 if (Itr == IsInternalCache.end())
11514 Itr = IsInternalCache
11515 .insert(std::pair<const Function *, bool>(
11516 Fn, (Fn->hasLocalLinkage() && !Fn->hasAddressTaken())))
11517 .first;
11518 return Itr->second;
11519}
11520
11521void SystemZTargetLowering::
11522verifyNarrowIntegerArgs_Call(const SmallVectorImpl<ISD::OutputArg> &Outs,
11523 const Function *F, SDValue Callee) const {
11524 // Temporarily only do the check when explicitly requested, until it can be
11525 // enabled by default.
11527 return;
11528
11529 bool IsInternal = false;
11530 const Function *CalleeFn = nullptr;
11531 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
11532 if ((CalleeFn = dyn_cast<Function>(G->getGlobal())))
11533 IsInternal = isInternal(CalleeFn);
11534 if (!IsInternal && !verifyNarrowIntegerArgs(Outs)) {
11535 errs() << "ERROR: Missing extension attribute of passed "
11536 << "value in call to function:\n" << "Callee: ";
11537 if (CalleeFn != nullptr)
11538 printFunctionArgExts(CalleeFn, errs());
11539 else
11540 errs() << "-\n";
11541 errs() << "Caller: ";
11543 llvm_unreachable("");
11544 }
11545}
11546
11547void SystemZTargetLowering::
11548verifyNarrowIntegerArgs_Ret(const SmallVectorImpl<ISD::OutputArg> &Outs,
11549 const Function *F) const {
11550 // Temporarily only do the check when explicitly requested, until it can be
11551 // enabled by default.
11553 return;
11554
11555 if (!isInternal(F) && !verifyNarrowIntegerArgs(Outs)) {
11556 errs() << "ERROR: Missing extension attribute of returned "
11557 << "value from function:\n";
11559 llvm_unreachable("");
11560 }
11561}
11562
11563// Verify that narrow integer arguments are extended as required by the ABI.
11564// Return false if an error is found.
11565bool SystemZTargetLowering::verifyNarrowIntegerArgs(
11566 const SmallVectorImpl<ISD::OutputArg> &Outs) const {
11567 if (!Subtarget.isTargetELF())
11568 return true;
11569
11572 return true;
11573 } else if (!getTargetMachine().Options.VerifyArgABICompliance)
11574 return true;
11575
11576 for (unsigned i = 0; i < Outs.size(); ++i) {
11577 MVT VT = Outs[i].VT;
11578 ISD::ArgFlagsTy Flags = Outs[i].Flags;
11579 if (VT.isInteger()) {
11580 assert((VT == MVT::i32 || VT.getSizeInBits() >= 64) &&
11581 "Unexpected integer argument VT.");
11582 if (VT == MVT::i32 &&
11583 !Flags.isSExt() && !Flags.isZExt() && !Flags.isNoExt())
11584 return false;
11585 }
11586 }
11587
11588 return true;
11589}
11590
11592 Module &M, const LibcallLoweringInfo &Libcalls) const {
11593 StringRef GuardMode = M.getStackProtectorGuard();
11594
11595 // In the TLS case, no symbol needs to be inserted.
11596 if (GuardMode == "tls" || GuardMode.empty())
11597 return;
11598
11599 // Otherwise (in the global case), insert the appropriate global variable.
11601}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
unsigned Imm
unsigned uint64_t
AMDGPU Register Bank Select
static bool isZeroVector(SDValue N)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis false
Function Alias Analysis Results
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, const CCValAssign &VA, const SDLoc &DL)
static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, const CCValAssign &VA, const SDLoc &DL)
#define Check(C,...)
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
static LVOptions Options
Definition LVOptions.cpp:25
static bool isSelectPseudo(MachineInstr &MI)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
static bool isUndef(const MachineInstr &MI)
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t High
uint64_t IntrinsicInst * II
#define P(N)
static constexpr MCPhysReg SPReg
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
const char * Msg
This file defines the SmallSet class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SDValue getI128Select(SelectionDAG &DAG, const SDLoc &DL, Comparison C, SDValue TrueOp, SDValue FalseOp)
static SmallVector< SDValue, 4 > simplifyAssumingCCVal(SDValue &Val, SDValue &CC, SelectionDAG &DAG)
static void adjustForTestUnderMask(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static void printFunctionArgExts(const Function *F, raw_fd_ostream &OS)
static void adjustForLTGFR(Comparison &C)
static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static SDValue joinDwords(SelectionDAG &DAG, const SDLoc &DL, SDValue Op0, SDValue Op1)
#define CONV(X)
static cl::opt< bool > EnableIntArgExtCheck("argext-abi-check", cl::init(false), cl::desc("Verify that narrow int args are properly extended per the " "SystemZ ABI."))
static bool isOnlyUsedByStores(SDValue StoredVal, SelectionDAG &DAG)
static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT, unsigned Opcode, SDValue Op0, SDValue Op1, SDValue &Even, SDValue &Odd)
static void adjustForRedundantAnd(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static SDValue lowerAddrSpaceCast(SDValue Op, SelectionDAG &DAG)
static SDValue buildScalarToVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT, SDValue Value)
static SDValue lowerI128ToGR128(SelectionDAG &DAG, SDValue In)
static bool isSimpleShift(SDValue N, unsigned &ShiftVal)
static SDValue mergeHighParts(SelectionDAG &DAG, const SDLoc &DL, unsigned MergedBits, EVT VT, SDValue Op0, SDValue Op1)
static bool isI128MovedToParts(LoadSDNode *LD, SDNode *&LoPart, SDNode *&HiPart)
static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1)
static uint32_t findZeroVectorIdx(SDValue *Ops, unsigned Num)
static bool isVectorElementSwap(ArrayRef< int > M, EVT VT)
static void getCSAddressAndShifts(SDValue Addr, SelectionDAG &DAG, SDLoc DL, SDValue &AlignedAddr, SDValue &BitShift, SDValue &NegBitShift)
static bool isShlDoublePermute(const SmallVectorImpl< int > &Bytes, unsigned &StartIndex, unsigned &OpNo0, unsigned &OpNo1)
static SDValue getPermuteNode(SelectionDAG &DAG, const SDLoc &DL, const Permute &P, SDValue Op0, SDValue Op1)
static SDNode * emitIntrinsicWithCCAndChain(SelectionDAG &DAG, SDValue Op, unsigned Opcode)
static SDValue getCCResult(SelectionDAG &DAG, SDValue CCReg)
static void adjustForStackGuardCompare(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode, unsigned &CCValid)
static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend, SDValue Op0, SDValue Op1, SDValue &Hi, SDValue &Lo)
static bool isF128MovedToParts(LoadSDNode *LD, SDNode *&LoPart, SDNode *&HiPart)
static void createPHIsForSelects(SmallVector< MachineInstr *, 8 > &Selects, MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB, MachineBasicBlock *SinkMBB)
static SDValue getGeneralPermuteNode(SelectionDAG &DAG, const SDLoc &DL, SDValue *Ops, const SmallVectorImpl< int > &Bytes)
static unsigned getVectorComparisonOrInvert(ISD::CondCode CC, CmpMode Mode, bool &Invert)
static unsigned CCMaskForCondCode(ISD::CondCode CC)
static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static void adjustForFNeg(Comparison &C)
static bool isScalarToVector(SDValue Op)
static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue CCReg, unsigned CCValid, unsigned CCMask)
static bool matchPermute(const SmallVectorImpl< int > &Bytes, const Permute &P, unsigned &OpNo0, unsigned &OpNo1)
static bool isAddCarryChain(SDValue Carry)
static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static MachineOperand earlyUseOperand(MachineOperand Op)
static bool canUseSiblingCall(const CCState &ArgCCInfo, SmallVectorImpl< CCValAssign > &ArgLocs, SmallVectorImpl< ISD::OutputArg > &Outs)
static bool getzOSCalleeAndADA(SelectionDAG &DAG, SDValue &Callee, SDValue &ADA, SDLoc &DL, SDValue &Chain)
static SDValue convertToF16(SDValue Op, SelectionDAG &DAG)
static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask, SelectionDAG &DAG)
static bool shouldSwapCmpOperands(const Comparison &C)
static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType)
static SDValue getADAEntry(SelectionDAG &DAG, SDValue Val, SDLoc DL, unsigned Offset, bool LoadAdr=false)
static SDNode * emitIntrinsicWithCC(SelectionDAG &DAG, SDValue Op, unsigned Opcode)
static void adjustForSubtraction(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static bool getVPermMask(SDValue ShuffleOp, SmallVectorImpl< int > &Bytes)
static const Permute PermuteForms[]
static bool isI128MovedFromParts(SDValue Val, SDValue &LoPart, SDValue &HiPart)
static std::pair< SDValue, int > findCCUse(const SDValue &Val, unsigned Depth=0)
static bool isSubBorrowChain(SDValue Carry)
static void adjustICmp128(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static bool analyzeArgSplit(const SmallVectorImpl< ArgTy > &Args, SmallVector< CCValAssign, 16 > &ArgLocs, unsigned I, MVT &PartVT, unsigned &NumParts)
static APInt getDemandedSrcElements(SDValue Op, const APInt &DemandedElts, unsigned OpNo)
static SDValue getAbsolute(SelectionDAG &DAG, const SDLoc &DL, SDValue Op, bool IsNegative)
static unsigned computeNumSignBitsBinOp(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth, unsigned OpNo)
static SDValue expandBitCastI128ToF128(SelectionDAG &DAG, SDValue Src, const SDLoc &SL)
static SDValue tryBuildVectorShuffle(SelectionDAG &DAG, BuildVectorSDNode *BVN)
static SDValue convertFromF16(SDValue Op, SDLoc DL, SelectionDAG &DAG)
static unsigned getVectorComparison(ISD::CondCode CC, CmpMode Mode)
static SDValue lowerGR128ToI128(SelectionDAG &DAG, SDValue In)
static SDValue MergeInputChains(SDNode *N1, SDNode *N2)
static SDValue expandBitCastF128ToI128(SelectionDAG &DAG, SDValue Src, const SDLoc &SL)
static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask, uint64_t Mask, uint64_t CmpVal, unsigned ICmpType)
static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid)
static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL, SDValue Op, SDValue Chain)
static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1, ISD::CondCode Cond, const SDLoc &DL, SDValue Chain=SDValue(), bool IsSignaling=false)
static bool checkCCKill(MachineInstr &MI, MachineBasicBlock *MBB)
static Register forceReg(MachineInstr &MI, MachineOperand &Base, const SystemZInstrInfo *TII)
static bool is32Bit(EVT VT)
static std::pair< unsigned, const TargetRegisterClass * > parseRegisterNumber(StringRef Constraint, const TargetRegisterClass *RC, const unsigned *Map, unsigned Size)
static unsigned detectEvenOddMultiplyOperand(const SelectionDAG &DAG, const SystemZSubtarget &Subtarget, SDValue &Op)
static bool matchDoublePermute(const SmallVectorImpl< int > &Bytes, const Permute &P, SmallVectorImpl< int > &Transform)
static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode, SDValue Call, unsigned CCValid, uint64_t CC, ISD::CondCode Cond)
static SDValue buildFPVecFromScalars4(SelectionDAG &DAG, const SDLoc &DL, EVT VT, SmallVectorImpl< SDValue > &Elems, unsigned Pos)
static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg)
static AddressingMode getLoadStoreAddrMode(bool HasVector, Type *Ty)
static SDValue buildMergeScalars(SelectionDAG &DAG, const SDLoc &DL, EVT VT, SDValue Op0, SDValue Op1)
static void computeKnownBitsBinOp(const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth, unsigned OpNo)
static bool getShuffleInput(const SmallVectorImpl< int > &Bytes, unsigned Start, unsigned BytesPerElement, int &Base)
static AddressingMode supportedAddressingMode(Instruction *I, bool HasVector)
static bool isF128MovedFromParts(SDValue Val, SDValue &LoPart, SDValue &HiPart)
static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
Value * LHS
BinaryOperator * Mul
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:225
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:254
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool isSingleWord() const
Determine if this APInt just has one word to store value.
Definition APInt.h:318
LLVM_ABI void insertBits(const APInt &SubBits, unsigned bitPosition)
Insert the bits from a smaller APInt starting at bitPosition.
Definition APInt.cpp:393
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:860
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
an instruction that atomically reads a memory location, combines it with another value,...
@ Add
*p = old + v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
BinOp getOperation() const
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:410
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
static LLVM_ABI StringRef getNameFromAttrKind(Attribute::AttrKind AttrKind)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
A "pseudo-class" with methods for operating on BUILD_VECTORs.
LLVM_ABI bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef, unsigned &SplatBitSize, bool &HasAnyUndefs, unsigned MinSplatBits=0, bool isBigEndian=false) const
Check if this is a constant splat, and if so, find the smallest element size that splats the vector.
LLVM_ABI bool isConstant() const
CCState - This class holds information needed while lowering arguments and return values.
LLVM_ABI void AnalyzeCallResult(const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn Fn)
AnalyzeCallResult - Analyze the return values of a call, incorporating info about the passed values i...
LLVM_ABI bool CheckReturn(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
CheckReturn - Analyze the return values of a function, returning true if the return can be performed ...
LLVM_ABI void AnalyzeReturn(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
AnalyzeReturn - Analyze the returned values of a return, incorporating info about the result values i...
LLVM_ABI void AnalyzeCallOperands(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
AnalyzeCallOperands - Analyze the outgoing arguments to a call, incorporating info about the passed v...
uint64_t getStackSize() const
Returns the size of the currently allocated portion of the stack.
LLVM_ABI void AnalyzeFormalArguments(const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn Fn)
AnalyzeFormalArguments - Analyze an array of argument values, incorporating info about the formals in...
CCValAssign - Represent assignment of one arg/retval to a location.
Register getLocReg() const
LocInfo getLocInfo() const
bool needsCustom() const
bool isExtInLoc() const
int64_t getLocMemOffset() const
This class represents a function call, abstracting a target machine's calling convention.
bool isTailCall() const
MachineConstantPoolValue * getMachineCPVal() const
const Constant * getConstVal() const
uint64_t getZExtValue() const
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI unsigned getPointerSize(unsigned AS=0) const
The pointer representation size in bytes, rounded up to a whole number of bytes.
A debug info location.
Definition DebugLoc.h:126
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:767
iterator end()
Definition DenseMap.h:687
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:316
bool hasAddressTaken(const User **=nullptr, bool IgnoreCallbackUses=false, bool IgnoreAssumeLikeCalls=true, bool IngoreLLVMUsed=false, bool IgnoreARCAttachedCall=false, bool IgnoreCastedDirectCall=false) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
Definition Function.cpp:944
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:769
uint64_t getFnAttributeAsParsedInteger(StringRef Kind, uint64_t Default=0) const
For a string attribute Kind, parse attribute as an integer.
Definition Function.cpp:781
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:734
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:730
bool hasLocalLinkage() const
bool hasPrivateLinkage() const
bool hasInternalLinkage() const
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Tracks which library functions to use for a particular subtarget or function.
An instruction for reading from memory.
This class is used to represent ISD::LOAD nodes.
Machine Value Type.
static auto integer_fixedlen_vector_valuetypes()
SimpleValueType SimpleTy
uint64_t getScalarSizeInBits() const
bool isVector() const
Return true if this is a vector value type.
bool isInteger() const
Return true if this is an integer or a vector integer type.
static auto integer_valuetypes()
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
static auto fixedlen_vector_valuetypes()
ElementCount getVectorElementCount() const
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
static MVT getVectorVT(MVT VT, unsigned NumElements)
static MVT getIntegerVT(unsigned BitWidth)
static auto fp_valuetypes()
MVT getScalarType() const
If this is a vector, return the element type, otherwise return this.
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
void setMachineBlockAddressTaken()
Set this block to indicate that its address is used as something other than the target of a terminato...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
void setMaxCallFrameSize(uint64_t S)
LLVM_ABI int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
void setFrameAddressIsTaken(bool T)
uint64_t getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call.
void setReturnAddressIsTaken(bool s)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
void push_back(MachineBasicBlock *MBB)
reverse_iterator rbegin()
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineFunctionProperties & getProperties() const
Get the function properties.
Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & setMemRefs(ArrayRef< MachineMemOperand * > MMOs) const
const MachineInstrBuilder & setOperandDead(unsigned OpIdx) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addFrameIndex(int Idx) const
const MachineInstrBuilder & addRegMask(const uint32_t *Mask) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
Representation of each machine instruction.
bool killsRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr kills the specified register.
const MachineOperand & getOperand(unsigned i) const
A description of a memory reference used in the backend.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
Register getReg() const
getReg - Returns the register number.
LLVM_ABI bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
void addLiveIn(MCRegister Reg, Register vreg=Register())
addLiveIn - Add the specified register as a live-in.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool hasOneUse() const
Return true if there is exactly one use of this node.
SDNodeFlags getFlags() const
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
unsigned getNumOperands() const
Return the number of values used by this operation.
unsigned getMachineOpcode() const
This may only be called if isMachineOpcode returns true.
const SDValue & getOperand(unsigned Num) const
bool hasNUsesOfValue(unsigned NUses, unsigned Value) const
Return true if there are exactly NUSES uses of the indicated value.
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
iterator_range< user_iterator > users()
void setFlags(SDNodeFlags NewFlags)
Represents a use of a SDNode.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
bool isMachineOpcode() const
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
const APInt & getConstantOperandAPInt(unsigned i) const
uint64_t getScalarValueSizeInBits() const
unsigned getResNo() const
get the index which selects a specific result in the SDNode
uint64_t getConstantOperandVal(unsigned i) const
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
unsigned getMachineOpcode() const
unsigned getOpcode() const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
SDValue getExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT, unsigned Opcode)
Convert Op, which must be of integer type, to the integer type VT, by either any/sign/zero-extending ...
const TargetSubtargetInfo & getSubtarget() const
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI SDValue getAtomicLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT MemVT, EVT VT, SDValue Chain, SDValue Ptr, MachineMemOperand *MMO)
LLVM_ABI SDValue getConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offs=0, bool isT=false, unsigned TargetFlags=0)
LLVM_ABI bool isConstantIntBuildVectorOrConstantInt(SDValue N, bool AllowOpaques=true) const
Test whether the given value is a constant int or similar node.
LLVM_ABI SDValue UnrollVectorOp(SDNode *N, unsigned ResNE=0)
Utility function used by legalize and lowering to "unroll" a vector operation by splitting out the sc...
LLVM_ABI SDValue getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, unsigned SrcAS, unsigned DestAS, const SDNodeFlags Flags=SDNodeFlags())
Return an AddrSpaceCastSDNode.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
SDValue getGLOBAL_OFFSET_TABLE(EVT VT)
Return a GLOBAL_OFFSET_TABLE node. This does not have a useful SDLoc.
LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, LocationSize Size=LocationSize::precise(0), const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
LLVM_ABI SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDValue Chain, SDValue Ptr, SDValue Val, MachineMemOperand *MMO)
Gets a node for an atomic op, produces result (if relevant) and chain and takes 2 operands.
void addNoMergeSiteInfo(const SDNode *Node, bool NoMerge)
Set NoMergeSiteInfo to be associated with Node if NoMerge is true.
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
const TargetLowering & getTargetLoweringInfo() const
SDValue getTargetJumpTable(int JTI, EVT VT, unsigned TargetFlags=0)
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2, SDValue InGlue, const SDLoc &DL)
Return a new CALLSEQ_END node, which always must have a glue result (to ensure it's not CSE'd).
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI bool isSplatValue(SDValue V, const APInt &DemandedElts, APInt &UndefElts, unsigned Depth=0) const
Test whether V has a splatted value for all the demanded elements.
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
const DataLayout & getDataLayout() const
SDValue getTargetFrameIndex(int FI, EVT VT)
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
SDValue getSignedTargetConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
SDValue getSplatVector(EVT VT, const SDLoc &DL, SDValue Op)
SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, const SDLoc &DL)
Return a new CALLSEQ_START node, that starts new call frame, in which InSize bytes are set up inside ...
LLVM_ABI bool SignBitIsZero(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero.
LLVM_ABI SDValue getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand)
A convenience function for creating TargetInstrInfo::EXTRACT_SUBREG nodes.
LLVM_ABI SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI std::pair< SDValue, SDValue > getStrictFPExtendOrRound(SDValue Op, SDValue Chain, const SDLoc &DL, EVT VT)
Convert Op, which must be a STRICT operation of float type, to the float type VT, by either extending...
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of float type, to the float type VT, by either extending or rounding (by tr...
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI unsigned ComputeNumSignBits(SDValue Op, unsigned Depth=0) const
Return the number of times the sign bit of the register is replicated into the other bits.
SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, unsigned TargetFlags=0)
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op)
Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all elements.
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset)
Create an add instruction with appropriate flags when used for addressing some offset of an object.
LLVMContext * getContext() const
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment)
Create a stack temporary based on the size in bytes and the alignment.
LLVM_ABI SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
SDValue getTargetConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offset=0, unsigned TargetFlags=0)
LLVM_ABI SDValue getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand, SDValue Subreg)
A convenience function for creating TargetInstrInfo::INSERT_SUBREG nodes.
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
LLVM_ABI std::pair< SDValue, SDValue > SplitScalar(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the scalar node with EXTRACT_ELEMENT using the provided VTs and return the low/high part.
LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
This SDNode is used to implement the code generator support for the llvm IR shufflevector instruction...
ArrayRef< int > getMask() const
const_iterator begin() const
Definition SmallSet.h:216
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
size_type size() const
Definition SmallSet.h:171
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
This class is used to represent ISD::STORE nodes.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:490
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition StringRef.h:720
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
iterator end() const
Definition StringRef.h:116
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
A SystemZ-specific class detailing special use registers particular for calling conventions.
static SystemZConstantPoolValue * Create(const GlobalValue *GV, SystemZCP::SystemZCPModifier Modifier)
const SystemZInstrInfo * getInstrInfo() const override
SystemZCallingConventionRegisters * getSpecialRegisters() const
AtomicExpansionKind shouldExpandAtomicRMWInIR(const AtomicRMWInst *RMW) const override
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all.
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
This callback is invoked for operations that are unsupported by the target, which are registered to u...
EVT getOptimalMemOpType(LLVMContext &Context, const MemOp &Op, const AttributeList &FuncAttributes) const override
Returns the target specific optimal type for load and store operations as a result of memset,...
bool hasInlineStackProbe(const MachineFunction &MF) const override
Returns true if stack probing through inline assembly is requested.
MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *BB) const override
This method should be implemented by targets that mark instructions with the 'usesCustomInserter' fla...
MachineBasicBlock * emitEHSjLjSetJmp(MachineInstr &MI, MachineBasicBlock *MBB) const
AtomicExpansionKind shouldCastAtomicLoadInIR(LoadInst *LI) const override
Returns how the given (atomic) load should be cast by the IR-level AtomicExpand pass.
EVT getSetCCResultType(const DataLayout &DL, LLVMContext &, EVT) const override
Return the ValueType of the result of SETCC operations.
bool allowTruncateForTailCall(Type *, Type *) const override
Return true if a truncation from FromTy to ToTy is permitted when deciding whether a call is in tail ...
SDValue LowerAsmOutputForConstraint(SDValue &Chain, SDValue &Flag, const SDLoc &DL, const AsmOperandInfo &Constraint, SelectionDAG &DAG) const override
SDValue LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, const SmallVectorImpl< SDValue > &OutVals, const SDLoc &DL, SelectionDAG &DAG) const override
This hook must be implemented to lower outgoing return values, described by the Outs array,...
MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
MachineBasicBlock * emitEHSjLjLongJmp(MachineInstr &MI, MachineBasicBlock *MBB) const
bool CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, LLVMContext &Context, const Type *RetTy) const override
This hook should be implemented to check whether the return values described by the Outs array can fi...
std::pair< SDValue, SDValue > makeExternalCall(SDValue Chain, SelectionDAG &DAG, const char *CalleeName, EVT RetVT, ArrayRef< SDValue > Ops, CallingConv::ID CallConv, bool IsSigned, SDLoc DL, bool DoesNotReturn, bool IsReturnValueUsed) const
void insertSSPDeclarations(Module &M, const LibcallLoweringInfo &Libcalls) const override
Insert SSP declaration if global stack protector is used.
bool mayBeEmittedAsTailCall(const CallInst *CI) const override
Return true if the target may be able emit the call instruction as a tail call.
bool splitValueIntoRegisterParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, unsigned NumParts, MVT PartVT, std::optional< CallingConv::ID > CC) const override
Target-specific splitting of values into parts that fit a register storing a legal type.
bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I=nullptr) const override
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Certain targets require unusual breakdowns of certain types.
bool isGuaranteedNotToBeUndefOrPoisonForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, UndefPoisonKind Kind, unsigned Depth) const override
Return true if this function can prove that Op is never poison and, Kind can be used to track poison ...
SystemZTargetLowering(const TargetMachine &TM, const SystemZSubtarget &STI)
bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, EVT VT) const override
Return true if an FMA operation is faster than a pair of fmul and fadd instructions.
bool isLegalICmpImmediate(int64_t Imm) const override
Return true if the specified immediate is legal icmp immediate, that is the target has icmp instructi...
std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const override
Given a physical register constraint (e.g.
TargetLowering::ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const override
Examine constraint string and operand type and determine a weight value.
bool allowsMisalignedMemoryAccesses(EVT VT, unsigned AS, Align Alignment, MachineMemOperand::Flags Flags, unsigned *Fast) const override
Determine if the target supports unaligned memory accesses.
const MCPhysReg * getScratchRegisters(CallingConv::ID CC) const override
Returns a 0 terminated array of registers that can be safely used as scratch registers.
TargetLowering::ConstraintType getConstraintType(StringRef Constraint) const override
Given a constraint, return the type of constraint it is for this target.
Register getExceptionSelectorRegister(ExceptionHandling EH, const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception typeid on entry to a la...
bool isFPImmLegal(const APFloat &Imm, EVT VT, bool ForCodeSize) const override
Returns true if the target can instruction select the specified FP immediate natively.
SDValue joinRegisterPartsIntoValue(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, MVT PartVT, EVT ValueVT, std::optional< CallingConv::ID > CC) const override
Target-specific combining of register parts into its original value.
bool isTruncateFree(Type *, Type *) const override
Return true if it's free to truncate a value of type FromTy to type ToTy.
SDValue useLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, MVT VT, SDValue Arg, SDLoc DL, SDValue Chain, bool IsStrict) const
unsigned ComputeNumSignBitsForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const override
Determine the number of bits in the operation that are sign bits.
void LowerOperationWrapper(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
This callback is invoked by the type legalizer to legalize nodes with an illegal operand type but leg...
SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override
This method will be invoked for all target nodes and for any target-independent nodes that the target...
SDValue LowerCall(CallLoweringInfo &CLI, SmallVectorImpl< SDValue > &InVals) const override
This hook must be implemented to lower calls into the specified DAG.
bool isLegalAddImmediate(int64_t Imm) const override
Return true if the specified immediate is legal add immediate, that is the target has add instruction...
CondMergingParams getJumpConditionMergingParams(Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs, const Function *F) const override
TargetLoweringBase::LegalizeTypeAction getPreferredVectorAction(MVT VT) const override
Return the preferred vector type legalization action.
bool findOptimalMemOpLowering(LLVMContext &Context, std::vector< EVT > &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, unsigned SrcAS, const AttributeList &FuncAttributes, EVT *LargestVT=nullptr) const override
Determines the optimal series of memory ops to replace the memset / memcpy.
void ReplaceNodeResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
This callback is invoked when a node result type is illegal for the target, and the operation was reg...
void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const override
Lower the specified operand into the Ops vector.
Register getExceptionPointerRegister(ExceptionHandling EH, const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception address on entry to an ...
unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const override
Certain targets such as MIPS require that some types such as vectors are always broken down into scal...
AtomicExpansionKind shouldCastAtomicStoreInIR(StoreInst *SI) const override
Returns how the given (atomic) store should be cast by the IR-level AtomicExpand pass into.
Register getRegisterByName(const char *RegName, LLT VT, const MachineFunction &MF) const override
Return the register ID of the name passed in.
bool hasAndNot(SDValue Y) const override
Return true if the target has a bitwise and-not operation: X = ~A & B This can be used to simplify se...
SDValue LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl< ISD::InputArg > &Ins, const SDLoc &DL, SelectionDAG &DAG, SmallVectorImpl< SDValue > &InVals) const override
This hook must be implemented to lower the incoming (formal) arguments, described by the Ins array,...
void computeKnownBitsForTargetNode(const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth=0) const override
Determine which of the bits specified in Mask are known to be either zero or one and return them in t...
unsigned getStackProbeSize(const MachineFunction &MF) const
XPLINK64 calling convention specific use registers Particular to z/OS when in 64 bit mode.
Information about stack frame layout on the target.
unsigned getStackAlignment() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
TargetInstrInfo - Interface to description of machine instruction set.
void setBooleanVectorContents(BooleanContent Ty)
Specify how the target extends the result of a vector boolean value from a vector of i1 to a wider ty...
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
unsigned MaxStoresPerMemcpyOptSize
Likewise for functions with the OptSize attribute.
MachineBasicBlock * emitPatchPoint(MachineInstr &MI, MachineBasicBlock *MBB) const
Replace/modify any TargetFrameIndex operands with a targte-dependent sequence of memory operands that...
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
const TargetMachine & getTargetMachine() const
virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain targets require unusual breakdowns of certain types.
virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
LegalizeTypeAction
This enum indicates whether a types are legal for a target, and if not, what action should be used to...
virtual void insertSSPDeclarations(Module &M, const LibcallLoweringInfo &Libcalls) const
Inserts necessary declarations for SSP (stack protection) purpose.
void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits)
Set the maximum atomic operation size supported by the backend.
virtual TargetLoweringBase::LegalizeTypeAction getPreferredVectorAction(MVT VT) const
Return the preferred vector type legalization action.
void setAtomicLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Let target indicate that an extending atomic load of the specified type is legal.
virtual unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const
Certain targets such as MIPS require that some types such as vectors are always broken down into scal...
Register getStackPointerRegisterToSaveRestore() const
If a physical register, this specifies the register that llvm.savestack/llvm.restorestack should save...
void setMinFunctionAlignment(Align Alignment)
Set the target's minimum function alignment.
unsigned MaxStoresPerMemsetOptSize
Likewise for functions with the OptSize attribute.
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of integer and floating point boolean values from i1 to a w...
unsigned MaxStoresPerMemmove
Specify maximum number of store instructions per memmove call.
void computeRegisterProperties(const TargetRegisterInfo *TRI)
Once all of the register classes are added, this allows us to compute derived properties we expose.
unsigned MaxStoresPerMemmoveOptSize
Likewise for functions with the OptSize attribute.
void addRegisterClass(MVT VT, const TargetRegisterClass *RC)
Add the specified register class as an available regclass for the specified value type.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
void setPrefFunctionAlignment(Align Alignment)
Set the target's preferred function alignment.
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
unsigned MaxStoresPerMemset
Specify maximum number of store instructions per memset call.
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
virtual const TargetRegisterClass * getRepRegClassFor(MVT VT) const
Return the 'representative' register class for the specified value type.
void setStackPointerRegisterToSaveRestore(Register R)
If set to a physical register, this specifies the register that llvm.savestack/llvm....
AtomicExpansionKind
Enum that specifies what an atomic load/AtomicRMWInst is expanded to, if at all.
void setTargetDAGCombine(ArrayRef< ISD::NodeType > NTs)
Targets should invoke this method for each target independent node that they want to provide a custom...
void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified load with extension does not work with the specified type and indicate wh...
virtual bool shouldSignExtendTypeInLibCall(Type *Ty, bool IsSigned) const
Returns true if arguments should be sign-extended in lib calls.
std::vector< ArgListEntry > ArgListTy
unsigned MaxStoresPerMemcpy
Specify maximum number of store instructions per memcpy call.
virtual MVT getPointerMemTy(const DataLayout &DL, uint32_t AS=0) const
Return the in-memory pointer type for the given address space, defaults to the pointer type from the ...
void setSchedulingPreference(Sched::Preference Pref)
Specify the target scheduling preference.
LegalizeAction getOperationAction(unsigned Op, EVT VT) const
Return how this operation should be treated: either it is legal, needs to be promoted to a larger siz...
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
virtual bool findOptimalMemOpLowering(LLVMContext &Context, std::vector< EVT > &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, unsigned SrcAS, const AttributeList &FuncAttributes, EVT *LargestVT=nullptr) const
Determines the optimal series of memory ops to replace the memset / memcpy.
virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, SelectionDAG &DAG) const
Lower TLS global address SDNode for target independent emulated TLS model.
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
virtual ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const
Examine constraint string and operand type and determine a weight value.
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
TargetLowering(const TargetLowering &)=delete
virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
std::pair< SDValue, SDValue > makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl, EVT RetVT, ArrayRef< SDValue > Ops, MakeLibCallOptions CallOptions, const SDLoc &dl, SDValue Chain=SDValue()) const
Returns a pair of (return value, chain).
Primary interface to the complete machine description for the target machine.
TLSModel::Model getTLSModel(const GlobalValue *GV) const
Returns the TLS model which should be used for the given global variable.
bool useEmulatedTLS() const
Returns true if this target uses emulated TLS.
CodeModel::Model getCodeModel() const
Returns the code model.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:339
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
user_iterator user_begin()
Definition Value.h:404
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
int getNumOccurrences() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
A raw_ostream that writes to a file descriptor.
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:837
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:263
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:516
@ POISON
POISON - A poison node.
Definition ISDOpcodes.h:238
@ EH_SJLJ_LONGJMP
OUTCHAIN = EH_SJLJ_LONGJMP(INCHAIN, buffer) This corresponds to the eh.sjlj.longjmp intrinsic.
Definition ISDOpcodes.h:170
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:277
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:797
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ATOMIC_STORE
OUTCHAIN = ATOMIC_STORE(INCHAIN, val, ptr) This corresponds to "store atomic" instruction.
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:871
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:523
@ PSEUDO_FMIN
PSEUDO_FMIN is strictly equivalent to op0 olt op1 ?
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:222
@ GlobalAddress
Definition ISDOpcodes.h:90
@ ATOMIC_CMP_SWAP_WITH_SUCCESS
Val, Success, OUTCHAIN = ATOMIC_CMP_SWAP_WITH_SUCCESS(INCHAIN, ptr, cmp, swap) N.b.
@ STRICT_FMINIMUM
Definition ISDOpcodes.h:476
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:898
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:757
@ MEMBARRIER
MEMBARRIER - Compiler barrier only; generate a no-op.
@ ATOMIC_FENCE
OUTCHAIN = ATOMIC_FENCE(INCHAIN, ordering, scope) This corresponds to the fence instruction.
@ SIGN_EXTEND_VECTOR_INREG
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition ISDOpcodes.h:928
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:282
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ STRICT_PSEUDO_FMAX
Definition ISDOpcodes.h:465
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:256
@ STRICT_FSQRT
Constrained versions of libm-equivalent floating point intrinsics.
Definition ISDOpcodes.h:441
@ BUILTIN_OP_END
BUILTIN_OP_END - This must be the last enum value in this list.
@ GlobalTLSAddress
Definition ISDOpcodes.h:91
@ CTLZ_ZERO_POISON
Definition ISDOpcodes.h:806
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:862
@ STRICT_UINT_TO_FP
Definition ISDOpcodes.h:490
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:675
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ STRICT_PSEUDO_FMIN
Definition ISDOpcodes.h:464
@ FSINCOS
FSINCOS - Compute both fsin and fcos as a single operation.
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:355
@ BR_JT
BR_JT - Jumptable branch.
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:553
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:814
@ ATOMIC_LOAD
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:235
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:249
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:682
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:351
@ VECREDUCE_ADD
Integer reductions may have a result type larger than the vector element type.
@ GET_ROUNDING
Returns current rounding mode: -1 Undefined 0 Round to 0 1 Round to nearest, ties to even 2 Round to ...
Definition ISDOpcodes.h:988
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:714
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:779
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:659
@ STRICT_FMAXIMUM
Definition ISDOpcodes.h:475
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:581
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:868
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:829
@ FMINNUM
FMINNUM/FMAXNUM - Perform floating-point minimum maximum on two values, following IEEE-754 definition...
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ ANY_EXTEND_VECTOR_INREG
ANY_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register any-extension of the low la...
Definition ISDOpcodes.h:917
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:906
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:737
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:996
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:823
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:331
@ STRICT_SINT_TO_FP
STRICT_[US]INT_TO_FP - Convert a signed or unsigned integer to a floating point value.
Definition ISDOpcodes.h:489
@ STRICT_FROUNDEVEN
Definition ISDOpcodes.h:469
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:112
@ STRICT_FP_TO_UINT
Definition ISDOpcodes.h:483
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:505
@ STRICT_FP_TO_SINT
STRICT_FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:482
@ FMINIMUM
FMINIMUM/FMAXIMUM - NaN-propagating minimum/maximum that also treat -0.0 as less than 0....
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:944
@ READCYCLECOUNTER
READCYCLECOUNTER - This corresponds to the readcyclecounter intrinsic.
@ STRICT_FP_EXTEND
X = STRICT_FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:510
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:749
@ TRAP
TRAP - Trapping instruction.
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ STRICT_FADD
Constrained versions of the binary floating point operators.
Definition ISDOpcodes.h:430
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:570
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ ATOMIC_SWAP
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN,...
@ CTTZ_ZERO_POISON
Bit counting operators with a poisoned result for zero inputs.
Definition ISDOpcodes.h:805
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:977
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:939
@ ADDRSPACECAST
ADDRSPACECAST - This operator converts between pointers of different address spaces.
@ STRICT_FNEARBYINT
Definition ISDOpcodes.h:461
@ EH_SJLJ_SETJMP
RESULT, OUTCHAIN = EH_SJLJ_SETJMP(INCHAIN, buffer) This corresponds to the eh.sjlj....
Definition ISDOpcodes.h:164
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:874
@ BRCOND
BRCOND - Conditional branch.
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:851
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:64
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:539
@ GET_DYNAMIC_AREA_OFFSET
GET_DYNAMIC_AREA_OFFSET - get offset from native SP to the address of the most recent dynamic alloca.
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - minimumnum/maximumnum that is same with FMINNUM_IEEE and FMAXNUM_IEEE besid...
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:561
bool isNormalStore(const SDNode *N)
Returns true if the specified node is a non-truncating and unindexed store.
LLVM_ABI bool isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly=false)
Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are 0 o...
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, EVT Type)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
LLVM_ABI CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y).
LLVM_ABI bool isBuildVectorAllZeros(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are 0 or undef.
LLVM_ABI bool isConstantSplatVector(const SDNode *N, APInt &SplatValue)
Node predicates.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
bool isNormalLoad(const SDNode *N)
Returns true if the specified node is a non-extending and unindexed load.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
auto m_Cmp()
Matches any compare instruction and ignore it.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
LLVM_ABI Libcall getSINTTOFP(EVT OpVT, EVT RetVT)
getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getUINTTOFP(EVT OpVT, EVT RetVT)
getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getFPTOSINT(EVT OpVT, EVT RetVT)
getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:58
const unsigned GR64Regs[16]
const unsigned VR128Regs[32]
const unsigned VR16Regs[32]
const unsigned GR128Regs[16]
const unsigned FP32Regs[16]
const unsigned FP16Regs[16]
const unsigned GR32Regs[16]
const unsigned FP64Regs[16]
const int64_t ELFCallFrameSize
const unsigned VR64Regs[32]
const unsigned FP128Regs[16]
const unsigned VR32Regs[32]
unsigned odd128(bool Is32bit)
const unsigned CCMASK_CMP_GE
Definition SystemZ.h:42
static bool isImmHH(uint64_t Val)
Definition SystemZ.h:178
const unsigned CCMASK_TEND
Definition SystemZ.h:99
const unsigned CCMASK_CS_EQ
Definition SystemZ.h:69
const unsigned CCMASK_TBEGIN
Definition SystemZ.h:94
const unsigned CCMASK_0
Definition SystemZ.h:29
const MCPhysReg ELFArgFPRs[ELFNumArgFPRs]
MachineBasicBlock * splitBlockBefore(MachineBasicBlock::iterator MI, MachineBasicBlock *MBB)
const unsigned CCMASK_TM_SOME_1
Definition SystemZ.h:84
const unsigned CCMASK_LOGICAL_CARRY
Definition SystemZ.h:62
const unsigned TDCMASK_NORMAL_MINUS
Definition SystemZ.h:124
const unsigned CCMASK_TDC
Definition SystemZ.h:111
const unsigned CCMASK_FCMP
Definition SystemZ.h:50
const unsigned CCMASK_TM_SOME_0
Definition SystemZ.h:83
static bool isImmHL(uint64_t Val)
Definition SystemZ.h:173
const unsigned TDCMASK_SUBNORMAL_MINUS
Definition SystemZ.h:126
const unsigned PFD_READ
Definition SystemZ.h:117
const unsigned CCMASK_1
Definition SystemZ.h:30
const unsigned TDCMASK_NORMAL_PLUS
Definition SystemZ.h:123
const unsigned PFD_WRITE
Definition SystemZ.h:118
const unsigned CCMASK_CMP_GT
Definition SystemZ.h:39
const unsigned TDCMASK_QNAN_MINUS
Definition SystemZ.h:130
const unsigned CCMASK_CS
Definition SystemZ.h:71
const unsigned CCMASK_ANY
Definition SystemZ.h:33
const unsigned CCMASK_ARITH
Definition SystemZ.h:57
const unsigned CCMASK_TM_MIXED_MSB_0
Definition SystemZ.h:80
const unsigned TDCMASK_SUBNORMAL_PLUS
Definition SystemZ.h:125
static bool isImmLL(uint64_t Val)
Definition SystemZ.h:163
const unsigned VectorBits
Definition SystemZ.h:156
static bool isImmLH(uint64_t Val)
Definition SystemZ.h:168
MachineBasicBlock * emitBlockAfter(MachineBasicBlock *MBB)
const unsigned TDCMASK_INFINITY_PLUS
Definition SystemZ.h:127
unsigned reverseCCMask(unsigned CCMask)
const unsigned CCMASK_TM_ALL_0
Definition SystemZ.h:79
const unsigned IPM_CC
Definition SystemZ.h:114
const unsigned CCMASK_CMP_LE
Definition SystemZ.h:41
const unsigned CCMASK_CMP_O
Definition SystemZ.h:46
const unsigned CCMASK_CMP_EQ
Definition SystemZ.h:37
const unsigned VectorBytes
Definition SystemZ.h:160
const unsigned TDCMASK_INFINITY_MINUS
Definition SystemZ.h:128
const unsigned CCMASK_ICMP
Definition SystemZ.h:49
const unsigned CCMASK_VCMP_ALL
Definition SystemZ.h:103
const unsigned CCMASK_VCMP_NONE
Definition SystemZ.h:105
MachineBasicBlock * splitBlockAfter(MachineBasicBlock::iterator MI, MachineBasicBlock *MBB)
const unsigned CCMASK_VCMP
Definition SystemZ.h:106
const unsigned CCMASK_TM_MIXED_MSB_1
Definition SystemZ.h:81
const unsigned CCMASK_TM_MSB_0
Definition SystemZ.h:85
const unsigned CCMASK_ARITH_OVERFLOW
Definition SystemZ.h:56
const unsigned CCMASK_CS_NE
Definition SystemZ.h:70
const unsigned TDCMASK_SNAN_PLUS
Definition SystemZ.h:131
const unsigned CCMASK_TM
Definition SystemZ.h:87
const unsigned CCMASK_3
Definition SystemZ.h:32
const unsigned CCMASK_NONE
Definition SystemZ.h:28
const unsigned CCMASK_CMP_LT
Definition SystemZ.h:38
const unsigned CCMASK_CMP_NE
Definition SystemZ.h:40
const unsigned TDCMASK_ZERO_PLUS
Definition SystemZ.h:121
const unsigned TDCMASK_QNAN_PLUS
Definition SystemZ.h:129
const unsigned TDCMASK_ZERO_MINUS
Definition SystemZ.h:122
unsigned even128(bool Is32bit)
const unsigned CCMASK_TM_ALL_1
Definition SystemZ.h:82
const unsigned CCMASK_LOGICAL_BORROW
Definition SystemZ.h:64
const unsigned ELFNumArgFPRs
const unsigned CCMASK_CMP_UO
Definition SystemZ.h:45
const unsigned CCMASK_LOGICAL
Definition SystemZ.h:66
const unsigned CCMASK_TM_MSB_1
Definition SystemZ.h:86
const unsigned TDCMASK_SNAN_MINUS
Definition SystemZ.h:132
initializer< Ty > init(const Ty &Val)
support::ulittle32_t Word
Definition IRSymtab.h:53
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
NodeAddr< CodeNode * > Code
Definition RDFGraph.h:388
This is an optimization pass for GlobalISel generic memory operations.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
@ Known
Known to have no common set bits.
@ Define
Register definition.
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Done
Definition Threading.h:60
@ Load
The value being inserted comes from a load (InsertElement only).
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition Error.h:198
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
constexpr T maskLeadingOnes(unsigned N)
Create a bitmask with the N left-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:89
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI void dumpBytes(ArrayRef< uint8_t > Bytes, raw_ostream &OS)
Convert ‘Bytes’ to a hex string and output to ‘OS’.
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition bit.h:362
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
LLVM_ABI bool isBitwiseNot(SDValue V, bool AllowUndefs=false)
Returns true if V is a bitwise not operation.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Success
The lock was released successfully.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
AtomicOrdering
Atomic ordering for LLVM's memory model.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ BeforeLegalizeTypes
Definition DAGCombine.h:16
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
@ Fast
Assign the register banks as fast as possible (default).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
constexpr unsigned BitWidth
ExceptionHandling
Definition CodeGen.h:54
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:567
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:78
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:347
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
LLVM_ABI bool isAllOnesConstant(SDValue V)
Returns true if V is an integer constant with all bits set.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
#define EQ(a, b)
Definition regexec.c:65
AddressingMode(bool LongDispl, bool IdxReg)
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Extended Value Type.
Definition ValueTypes.h:35
EVT changeVectorElementTypeToInteger() const
Return a vector with the same number of elements as this vector, but with the element type converted ...
Definition ValueTypes.h:90
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:418
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:145
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:155
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:408
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
Definition ValueTypes.h:404
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:346
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
bool isRound() const
Return true if the size is a power-of-two number of bytes.
Definition ValueTypes.h:271
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:351
bool isVectorOf(EVT EltVT) const
Return true if this is a vector with matching element type.
Definition ValueTypes.h:181
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:165
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:359
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition KnownBits.h:325
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getConstantPool(MachineFunction &MF)
Return a MachinePointerInfo record that refers to the constant pool.
MachinePointerInfo getWithOffset(int64_t O) const
static LLVM_ABI MachinePointerInfo getGOT(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a GOT entry.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
SmallVector< unsigned, 2 > OpVals
bool isVectorConstantLegal(const SystemZSubtarget &Subtarget)
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*...
This contains information for each constraint that we are lowering.
This structure contains all information that is necessary for lowering calls.
SmallVector< ISD::InputArg, 32 > Ins
CallLoweringInfo & setDiscardResult(bool Value=true)
CallLoweringInfo & setZExtResult(bool Value=true)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
CallLoweringInfo & setSExtResult(bool Value=true)
CallLoweringInfo & setNoReturn(bool Value=true)
SmallVector< ISD::OutputArg, 32 > Outs
CallLoweringInfo & setChain(SDValue InChain)
CallLoweringInfo & setCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList, AttributeSet ResultAttrs={})
This structure is used to pass arguments to makeLibCall function.