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"
31#include <cctype>
32#include <optional>
33
34using namespace llvm;
35
36#define DEBUG_TYPE "systemz-lower"
37
38namespace {
39// Represents information about a comparison.
40struct Comparison {
41 Comparison(SDValue Op0In, SDValue Op1In, SDValue ChainIn)
42 : Op0(Op0In), Op1(Op1In), Chain(ChainIn),
43 Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
44
45 // The operands to the comparison.
46 SDValue Op0, Op1;
47
48 // Chain if this is a strict floating-point comparison.
49 SDValue Chain;
50
51 // The opcode that should be used to compare Op0 and Op1.
52 unsigned Opcode;
53
54 // A SystemZICMP value. Only used for integer comparisons.
55 unsigned ICmpType;
56
57 // The mask of CC values that Opcode can produce.
58 unsigned CCValid;
59
60 // The mask of CC values for which the original condition is true.
61 unsigned CCMask;
62};
63} // end anonymous namespace
64
65// Classify VT as either 32 or 64 bit.
66static bool is32Bit(EVT VT) {
67 switch (VT.getSimpleVT().SimpleTy) {
68 case MVT::i32:
69 return true;
70 case MVT::i64:
71 return false;
72 default:
73 llvm_unreachable("Unsupported type");
74 }
75}
76
77// Return a version of MachineOperand that can be safely used before the
78// final use.
80 if (Op.isReg())
81 Op.setIsKill(false);
82 return Op;
83}
84
86 const SystemZSubtarget &STI)
87 : TargetLowering(TM, STI), Subtarget(STI) {
88 MVT PtrVT = MVT::i64;
89
90 auto *Regs = STI.getSpecialRegisters();
91
92 // Set up the register classes.
93 if (Subtarget.hasHighWord())
94 addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
95 else
96 addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
97 addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass);
98 if (!useSoftFloat()) {
99 if (Subtarget.hasVector()) {
100 addRegisterClass(MVT::f16, &SystemZ::VR16BitRegClass);
101 addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass);
102 addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass);
103 } else {
104 addRegisterClass(MVT::f16, &SystemZ::FP16BitRegClass);
105 addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass);
106 addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass);
107 }
108 if (Subtarget.hasVectorEnhancements1())
109 addRegisterClass(MVT::f128, &SystemZ::VR128BitRegClass);
110 else
111 addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
112
113 if (Subtarget.hasVector()) {
114 addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass);
115 addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass);
116 addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass);
117 addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass);
118 addRegisterClass(MVT::v8f16, &SystemZ::VR128BitRegClass);
119 addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass);
120 addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass);
121 }
122
123 if (Subtarget.hasVector())
124 addRegisterClass(MVT::i128, &SystemZ::VR128BitRegClass);
125 }
126
127 // Without vector support, model GR128 register pairs as v2i64.
128 if (!Subtarget.hasVector())
129 addRegisterClass(MVT::v2i64, &SystemZ::GR128BitRegClass);
130
131 // Compute derived properties from the register classes
132 computeRegisterProperties(Subtarget.getRegisterInfo());
133
134 // Set up special registers.
135 setStackPointerRegisterToSaveRestore(Regs->getStackPointerRegister());
136
137 // TODO: It may be better to default to latency-oriented scheduling, however
138 // LLVM's current latency-oriented scheduler can't handle physreg definitions
139 // such as SystemZ has with CC, so set this to the register-pressure
140 // scheduler, because it can.
142
145
147
148 // Instructions are strings of 2-byte aligned 2-byte values.
150 // For performance reasons we prefer 16-byte alignment.
152
153 // Handle operations that are handled in a similar way for all types.
154 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
155 I <= MVT::LAST_FP_VALUETYPE;
156 ++I) {
158 if (isTypeLegal(VT)) {
159 // Lower SET_CC into an IPM-based sequence.
163
164 // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
166
167 // Lower SELECT_CC and BR_CC into separate comparisons and branches.
170 }
171 }
172
173 // Expand jump table branches as address arithmetic followed by an
174 // indirect jump.
176
177 // Expand BRCOND into a BR_CC (see above).
179
180 // Handle integer types except i128.
181 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
182 I <= MVT::LAST_INTEGER_VALUETYPE;
183 ++I) {
185 if (isTypeLegal(VT) && VT != MVT::i128) {
187
188 // Expand individual DIV and REMs into DIVREMs.
195
196 // Support addition/subtraction with overflow.
199
200 // Support addition/subtraction with carry.
203
204 // Support carry in as value rather than glue.
207
208 // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
209 // available, or if the operand is constant.
211
212 // Use POPCNT on z196 and above.
213 if (Subtarget.hasPopulationCount())
215 else
217
218 // No special instructions for these.
221
222 // Use *MUL_LOHI where possible instead of MULH*.
227
228 // The fp<=>i32/i64 conversions are all Legal except for f16 and for
229 // unsigned on z10 (only z196 and above have native support for
230 // unsigned conversions).
237 // Handle unsigned 32-bit input types as signed 64-bit types on z10.
238 auto OpAction =
239 (!Subtarget.hasFPExtension() && VT == MVT::i32) ? Promote : Custom;
240 setOperationAction(Op, VT, OpAction);
241 }
242 }
243 }
244
245 // Handle i128 if legal.
246 if (isTypeLegal(MVT::i128)) {
247 // No special instructions for these.
254
255 // We may be able to use VSLDB/VSLD/VSRD for these.
258
259 // No special instructions for these before z17.
260 if (!Subtarget.hasVectorEnhancements3()) {
270 } else {
271 // Even if we do have a legal 128-bit multiply, we do not
272 // want 64-bit multiply-high operations to use it.
275 }
276
277 // Support addition/subtraction with carry.
282
283 // Use VPOPCT and add up partial results.
285
286 // Additional instructions available with z17.
287 if (Subtarget.hasVectorEnhancements3()) {
288 setOperationAction(ISD::ABS, MVT::i128, Legal);
289
291 MVT::i128, Legal);
292 }
293 }
294
295 // These need custom handling in order to handle the f16 conversions.
304
305 // Lower 8- and 16-bit atomic operations into full i32 operations during
306 // type legalization.
312 {MVT::i8, MVT::i16}, Custom);
313
314 // Whether or not i128 is not a legal type, we need to custom lower
315 // the atomic operations in order to exploit SystemZ instructions.
320
321 // Mark sign/zero extending atomic loads as legal, which will make
322 // DAGCombiner fold extensions into atomic loads if possible.
324 {MVT::i8, MVT::i16, MVT::i32}, Legal);
326 {MVT::i8, MVT::i16}, Legal);
328 MVT::i8, Legal);
329
330 // We can use the CC result of compare-and-swap to implement
331 // the "success" result of ATOMIC_CMP_SWAP_WITH_SUCCESS.
335
337
338 // Traps are legal, as we will convert them to "j .+2".
339 setOperationAction(ISD::TRAP, MVT::Other, Legal);
340
341 // We have native support for a 64-bit CTLZ, via FLOGR.
345
346 // On z17 we have native support for a 64-bit CTTZ, PDEP, and PEXT.
347 if (Subtarget.hasMiscellaneousExtensions4()) {
353 }
354
355 // On z15 we have native support for a 64-bit CTPOP.
356 if (Subtarget.hasMiscellaneousExtensions3()) {
359 }
360
361 // Give LowerOperation the chance to replace 64-bit ORs with subregs.
363
364 // Expand 128 bit shifts without using a libcall.
368
369 // Also expand 256 bit shifts if i128 is a legal type.
370 if (isTypeLegal(MVT::i128)) {
374 }
375
376 // Handle bitcast from fp128 to i128.
377 if (!isTypeLegal(MVT::i128))
379
380 // We have native instructions for i8, i16 and i32 extensions, but not i1.
382 for (MVT VT : MVT::integer_valuetypes()) {
386 }
387
388 // Handle the various types of symbolic address.
394
395 // We need to handle dynamic allocations specially because of the
396 // 160-byte area at the bottom of the stack.
399
402
403 // Handle prefetches with PFD or PFDRL.
405
406 // Handle readcyclecounter with STCKF.
408
410 // Assume by default that all vector operations need to be expanded.
411 for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
412 if (getOperationAction(Opcode, VT) == Legal)
413 setOperationAction(Opcode, VT, Expand);
414
415 // Likewise all truncating stores and extending loads.
416 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
417 setTruncStoreAction(VT, InnerVT, Expand);
420 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
421 }
422
423 if (Subtarget.hasVector() && isTypeLegal(VT)) {
424 // These operations are legal for anything that can be stored in a
425 // vector register, even if there is no native support for the format
426 // as such. In particular, we can do these for v4f32 even though there
427 // are no specific instructions for that format.
433
434 // Likewise, except that we need to replace the nodes with something
435 // more specific.
438 }
439 }
440
441 if (!Subtarget.hasVector()) {
442 // A v2i64 GR128 pair can only be built from or split into its halves.
443 // Loads and stores are expanded to avoid tying up a register pair.
446 MVT::v2i64, Legal);
448 MVT::v2i64, Custom);
449 }
450
451 // Handle integer vector types.
453 if (Subtarget.hasVector() && isTypeLegal(VT)) {
454 // These operations have direct equivalents.
459 if (VT != MVT::v2i64 || Subtarget.hasVectorEnhancements3()) {
463 }
464 if (Subtarget.hasVectorEnhancements3() &&
465 VT != MVT::v16i8 && VT != MVT::v8i16) {
470 }
475 if (Subtarget.hasVectorEnhancements1())
477 else
481
482 // Convert a GPR scalar to a vector by inserting it into element 0.
484
485 // Use a series of unpacks for extensions.
488
489 // Detect shifts/rotates by a scalar amount and convert them into
490 // V*_BY_SCALAR.
495
496 // Add ISD::VECREDUCE_ADD as custom in order to implement
497 // it with VZERO+VSUM
499
500 // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
501 // and inverting the result as necessary.
503
505 Legal);
506 }
507 }
508
509 if (Subtarget.hasVector()) {
510 // There should be no need to check for float types other than v2f64
511 // since <2 x f32> isn't a legal type.
520
529 }
530
531 if (Subtarget.hasVectorEnhancements2()) {
540
549 }
550
551 // Handle floating-point types.
552 if (!useSoftFloat()) {
553 // Promote all f16 operations to float, with some exceptions below.
554 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
555 setOperationAction(Opc, MVT::f16, Promote);
557 for (MVT VT : {MVT::f32, MVT::f64, MVT::f128}) {
558 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
559 setTruncStoreAction(VT, MVT::f16, Expand);
560 }
562 setOperationAction(Op, MVT::f16, Subtarget.hasVector() ? Legal : Custom);
566
567 for (auto Op : {ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN})
568 setOperationAction(Op, MVT::f16, Legal);
569 }
570
571 for (unsigned I = MVT::FIRST_FP_VALUETYPE;
572 I <= MVT::LAST_FP_VALUETYPE;
573 ++I) {
575 if (isTypeLegal(VT) && VT != MVT::f16) {
576 // We can use FI for FRINT.
578
579 // We can use the extended form of FI for other rounding operations.
580 if (Subtarget.hasFPExtension()) {
587 }
588
589 // No special instructions for these.
595
596 // Special treatment.
598
599 // Handle constrained floating-point operations.
608 if (Subtarget.hasFPExtension()) {
615 }
616
617 // Extension from f16 needs libcall.
620 }
621 }
622
623 // Handle floating-point vector types.
624 if (Subtarget.hasVector()) {
625 // Scalar-to-vector conversion is just a subreg.
629
630 // Some insertions and extractions can be done directly but others
631 // need to go via integers.
638
639 // These operations have direct equivalents.
640 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
641 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
642 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
643 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
644 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
645 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
646 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
647 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
648 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
651 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
655
656 // Handle constrained floating-point operations.
670
675 if (Subtarget.hasVectorEnhancements1()) {
678 }
679 }
680
681 // The vector enhancements facility 1 has instructions for these.
682 if (Subtarget.hasVectorEnhancements1()) {
683 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
684 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
685 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
686 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
687 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
688 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
689 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
690 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
691 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
694 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
698
699 for (MVT Type : {MVT::f64, MVT::v2f64, MVT::f32, MVT::v4f32, MVT::f128}) {
708 }
709
710 // Handle constrained floating-point operations.
724 for (auto VT : { MVT::f32, MVT::f64, MVT::f128,
725 MVT::v4f32, MVT::v2f64 }) {
732 }
733 }
734
735 // We only have fused f128 multiply-addition on vector registers.
736 if (!Subtarget.hasVectorEnhancements1()) {
739 }
740
741 // We don't have a copysign instruction on vector registers.
742 if (Subtarget.hasVectorEnhancements1())
744
745 // Needed so that we don't try to implement f128 constant loads using
746 // a load-and-extend of a f80 constant (in cases where the constant
747 // would fit in an f80).
748 for (MVT VT : MVT::fp_valuetypes())
749 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
750
751 // We don't have extending load instruction on vector registers.
752 if (Subtarget.hasVectorEnhancements1()) {
753 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
754 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
755 }
756
757 // Floating-point truncation and stores need to be done separately.
758 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
759 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
760 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
761
762 // We have 64-bit FPR<->GPR moves, but need special handling for
763 // 32-bit forms.
764 if (!Subtarget.hasVector()) {
767 }
768
769 // VASTART and VACOPY need to deal with the SystemZ-specific varargs
770 // structure, but VAEND is a no-op.
774
775 if (Subtarget.isTargetzOS()) {
776 // Handle address space casts between mixed sized pointers.
779 }
780
782
783 // Codes for which we want to perform some z-specific combinations.
787 ISD::LOAD,
800 ISD::SRL,
801 ISD::SRA,
802 ISD::MUL,
803 ISD::SDIV,
804 ISD::UDIV,
805 ISD::SREM,
806 ISD::UREM,
809
810 // Handle intrinsics.
813
814 // We're not using SJLJ for exception handling, but they're implemented
815 // solely to support use of __builtin_setjmp / __builtin_longjmp.
818
819 // We want to use MVC in preference to even a single load/store pair.
820 MaxStoresPerMemcpy = Subtarget.hasVector() ? 2 : 0;
822
823 // Same with memmove.
824 MaxStoresPerMemmove = Subtarget.hasVector() ? 2 : 0;
826
827 // The main memset sequence is a byte store followed by an MVC.
828 // Two STC or MV..I stores win over that, but the kind of fused stores
829 // generated by target-independent code don't when the byte value is
830 // variable. E.g. "STC <reg>;MHI <reg>,257;STH <reg>" is not better
831 // than "STC;MVC". Handle the choice in target-specific code instead.
832 MaxStoresPerMemset = Subtarget.hasVector() ? 2 : 0;
834
835 // Default to having -disable-strictnode-mutation on
836 IsStrictFPEnabled = true;
837}
838
840 return Subtarget.hasSoftFloat();
841}
842
845 // Widen subvectors to the full width rather than promoting integer
846 // elements. This is better because:
847 //
848 // (a) it means that we can handle the ABI for passing and returning
849 // sub-128 vectors without having to handle them as legal types.
850 //
851 // (b) we don't have instructions to extend on load and truncate on store,
852 // so promoting the integers is less efficient.
853 //
854 // (c) there are no multiplication instructions for the widest integer
855 // type (v2i64).
856
857 // Expand (narrow) f16 vectors during type legalization to avoid
858 // operations for all elements as with expansion after widening. Without
859 // vector support, v2i64 is only legal as a GR128 pair, so do not widen or
860 // promote to it.
861 if (!Subtarget.hasVector() || VT.getScalarType() == MVT::f16)
864 if (VT.getScalarSizeInBits() % 8 == 0)
865 return TypeWidenVector;
867}
868
870 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
871 unsigned &NumIntermediates, MVT &RegisterVT) const {
872 // Pass fp16 vectors in VR(s).
873 if (Subtarget.hasVector() && VT.isVectorOf(MVT::f16)) {
874 IntermediateVT = RegisterVT = MVT::v8f16;
875 return NumIntermediates =
877 }
879 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
880 // Without vector support, v2i64 is a GR128 pair, which is never used to pass
881 // values. Pass the elements individually.
882 if (RegisterVT == MVT::v2i64 && !Subtarget.hasVector()) {
883 IntermediateVT = RegisterVT = MVT::i64;
884 NumIntermediates *= 2;
885 NumRegs *= 2;
886 }
887 return NumRegs;
888}
889
892 EVT VT) const {
893 // 128-bit single-element vector types are passed like other vectors,
894 // not like their element type.
895 if (Subtarget.hasVector() && VT.isVector() && VT.getSizeInBits() == 128 &&
896 VT.getVectorNumElements() == 1)
897 return MVT::v16i8;
898 // Pass fp16 vectors in VR(s).
899 if (Subtarget.hasVector() && VT.isVectorOf(MVT::f16))
900 return MVT::v8f16;
901 MVT RegisterVT =
903 if (RegisterVT == MVT::v2i64 && !Subtarget.hasVector())
904 return MVT::i64;
905 return RegisterVT;
906}
907
909 LLVMContext &Context, CallingConv::ID CC, EVT VT) const {
910 // Pass fp16 vectors in VR(s).
911 if (Subtarget.hasVector() && VT.isVectorOf(MVT::f16))
913 unsigned NumRegs =
915 MVT RegisterVT =
917 if (RegisterVT == MVT::v2i64 && !Subtarget.hasVector())
918 return NumRegs * 2;
919 return NumRegs;
920}
921
923 LLVMContext &, EVT VT) const {
924 if (!VT.isVector())
925 return MVT::i32;
927}
928
930 const MachineFunction &MF, EVT VT) const {
931 if (useSoftFloat())
932 return false;
933
934 VT = VT.getScalarType();
935
936 if (!VT.isSimple())
937 return false;
938
939 switch (VT.getSimpleVT().SimpleTy) {
940 case MVT::f32:
941 case MVT::f64:
942 return true;
943 case MVT::f128:
944 return Subtarget.hasVectorEnhancements1();
945 default:
946 break;
947 }
948
949 return false;
950}
951
952// Return true if the constant can be generated with a vector instruction,
953// such as VGM, VGMB or VREPI.
956 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
957 if (!Subtarget.hasVector() ||
958 (isFP128 && !Subtarget.hasVectorEnhancements1()))
959 return false;
960
961 // Try using VECTOR GENERATE BYTE MASK. This is the architecturally-
962 // preferred way of creating all-zero and all-one vectors so give it
963 // priority over other methods below.
964 unsigned Mask = 0;
965 unsigned I = 0;
966 for (; I < SystemZ::VectorBytes; ++I) {
967 uint64_t Byte = IntBits.lshr(I * 8).trunc(8).getZExtValue();
968 if (Byte == 0xff)
969 Mask |= 1ULL << I;
970 else if (Byte != 0)
971 break;
972 }
973 if (I == SystemZ::VectorBytes) {
974 Opcode = SystemZISD::BYTE_MASK;
975 OpVals.push_back(Mask);
977 return true;
978 }
979
980 if (SplatBitSize > 64)
981 return false;
982
983 auto TryValue = [&](uint64_t Value) -> bool {
984 // Try VECTOR REPLICATE IMMEDIATE
985 int64_t SignedValue = SignExtend64(Value, SplatBitSize);
986 if (isInt<16>(SignedValue)) {
987 OpVals.push_back(((unsigned) SignedValue));
988 Opcode = SystemZISD::REPLICATE;
990 SystemZ::VectorBits / SplatBitSize);
991 return true;
992 }
993 // Try VECTOR GENERATE MASK
994 unsigned Start, End;
995 if (TII->isRxSBGMask(Value, SplatBitSize, Start, End)) {
996 // isRxSBGMask returns the bit numbers for a full 64-bit value, with 0
997 // denoting 1 << 63 and 63 denoting 1. Convert them to bit numbers for
998 // an SplatBitSize value, so that 0 denotes 1 << (SplatBitSize-1).
999 OpVals.push_back(Start - (64 - SplatBitSize));
1000 OpVals.push_back(End - (64 - SplatBitSize));
1001 Opcode = SystemZISD::ROTATE_MASK;
1003 SystemZ::VectorBits / SplatBitSize);
1004 return true;
1005 }
1006 return false;
1007 };
1008
1009 // First try assuming that any undefined bits above the highest set bit
1010 // and below the lowest set bit are 1s. This increases the likelihood of
1011 // being able to use a sign-extended element value in VECTOR REPLICATE
1012 // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
1013 uint64_t SplatBitsZ = SplatBits.getZExtValue();
1014 uint64_t SplatUndefZ = SplatUndef.getZExtValue();
1015 unsigned LowerBits = llvm::countr_zero(SplatBitsZ);
1016 unsigned UpperBits = llvm::countl_zero(SplatBitsZ);
1017 uint64_t Lower = SplatUndefZ & maskTrailingOnes<uint64_t>(LowerBits);
1018 uint64_t Upper = SplatUndefZ & maskLeadingOnes<uint64_t>(UpperBits);
1019 if (TryValue(SplatBitsZ | Upper | Lower))
1020 return true;
1021
1022 // Now try assuming that any undefined bits between the first and
1023 // last defined set bits are set. This increases the chances of
1024 // using a non-wraparound mask.
1025 uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
1026 return TryValue(SplatBitsZ | Middle);
1027}
1028
1030 if (IntImm.isSingleWord()) {
1031 IntBits = APInt(128, IntImm.getZExtValue());
1032 IntBits <<= (SystemZ::VectorBits - IntImm.getBitWidth());
1033 } else
1034 IntBits = IntImm;
1035 assert(IntBits.getBitWidth() == 128 && "Unsupported APInt.");
1036
1037 // Find the smallest splat.
1038 SplatBits = IntImm;
1039 unsigned Width = SplatBits.getBitWidth();
1040 while (Width > 8) {
1041 unsigned HalfSize = Width / 2;
1042 APInt HighValue = SplatBits.lshr(HalfSize).trunc(HalfSize);
1043 APInt LowValue = SplatBits.trunc(HalfSize);
1044
1045 // If the two halves do not match, stop here.
1046 if (HighValue != LowValue || 8 > HalfSize)
1047 break;
1048
1049 SplatBits = HighValue;
1050 Width = HalfSize;
1051 }
1052 SplatUndef = 0;
1053 SplatBitSize = Width;
1054}
1055
1057 assert(BVN->isConstant() && "Expected a constant BUILD_VECTOR");
1058 bool HasAnyUndefs;
1059
1060 // Get IntBits by finding the 128 bit splat.
1061 BVN->isConstantSplat(IntBits, SplatUndef, SplatBitSize, HasAnyUndefs, 128,
1062 true);
1063
1064 // Get SplatBits by finding the 8 bit or greater splat.
1065 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 8,
1066 true);
1067}
1068
1071 bool ForCodeSize) const {
1072 // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
1073 if (Imm.isZero() || Imm.isNegZero())
1074 return FPImmAction::Legal;
1075
1079}
1080
1083 MachineBasicBlock *MBB) const {
1084 DebugLoc DL = MI.getDebugLoc();
1085 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1086 const SystemZRegisterInfo *TRI = Subtarget.getRegisterInfo();
1087
1088 MachineFunction *MF = MBB->getParent();
1090
1091 const BasicBlock *BB = MBB->getBasicBlock();
1092 MachineFunction::iterator I = ++MBB->getIterator();
1093
1094 Register DstReg = MI.getOperand(0).getReg();
1095 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
1096 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
1097 (void)TRI;
1098 Register MainDstReg = MRI.createVirtualRegister(RC);
1099 Register RestoreDstReg = MRI.createVirtualRegister(RC);
1100
1101 MVT PVT = getPointerTy(MF->getDataLayout());
1102 assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
1103 // For v = setjmp(buf), we generate.
1104 // Algorithm:
1105 //
1106 // ---------
1107 // | thisMBB |
1108 // ---------
1109 // |
1110 // ------------------------
1111 // | |
1112 // ---------- ---------------
1113 // | mainMBB | | restoreMBB |
1114 // | v = 0 | | v = 1 |
1115 // ---------- ---------------
1116 // | |
1117 // -------------------------
1118 // |
1119 // -----------------------------
1120 // | sinkMBB |
1121 // | phi(v_mainMBB,v_restoreMBB) |
1122 // -----------------------------
1123 // thisMBB:
1124 // buf[FPOffset] = Frame Pointer if hasFP.
1125 // buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB.
1126 // buf[BCOffset] = Backchain value if building with -mbackchain.
1127 // buf[SPOffset] = Stack Pointer.
1128 // buf[LPOffset] = We never write this slot with R13, gcc stores R13 always.
1129 // SjLjSetup restoreMBB
1130 // mainMBB:
1131 // v_main = 0
1132 // sinkMBB:
1133 // v = phi(v_main, v_restore)
1134 // restoreMBB:
1135 // v_restore = 1
1136
1137 MachineBasicBlock *ThisMBB = MBB;
1138 MachineBasicBlock *MainMBB = MF->CreateMachineBasicBlock(BB);
1139 MachineBasicBlock *SinkMBB = MF->CreateMachineBasicBlock(BB);
1140 MachineBasicBlock *RestoreMBB = MF->CreateMachineBasicBlock(BB);
1141
1142 MF->insert(I, MainMBB);
1143 MF->insert(I, SinkMBB);
1144 MF->push_back(RestoreMBB);
1145 RestoreMBB->setMachineBlockAddressTaken();
1146
1148
1149 // Transfer the remainder of BB and its successor edges to sinkMBB.
1150 SinkMBB->splice(SinkMBB->begin(), MBB,
1151 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
1153
1154 // thisMBB:
1155 const int64_t FPOffset = 0; // Slot 1.
1156 const int64_t LabelOffset = 1 * PVT.getStoreSize(); // Slot 2.
1157 const int64_t BCOffset = 2 * PVT.getStoreSize(); // Slot 3.
1158 const int64_t SPOffset = 3 * PVT.getStoreSize(); // Slot 4.
1159
1160 // Buf address.
1161 Register BufReg = MI.getOperand(1).getReg();
1162
1163 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
1164 Register LabelReg = MRI.createVirtualRegister(PtrRC);
1165
1166 // Prepare IP for longjmp.
1167 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::LARL), LabelReg)
1168 .addMBB(RestoreMBB);
1169 // Store IP for return from jmp, slot 2, offset = 1.
1170 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1171 .addReg(LabelReg)
1172 .addReg(BufReg)
1173 .addImm(LabelOffset)
1174 .addReg(0);
1175
1176 auto *SpecialRegs = Subtarget.getSpecialRegisters();
1177 bool HasFP = Subtarget.getFrameLowering()->hasFP(*MF);
1178 if (HasFP) {
1179 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1180 .addReg(SpecialRegs->getFramePointerRegister())
1181 .addReg(BufReg)
1182 .addImm(FPOffset)
1183 .addReg(0);
1184 }
1185
1186 // Store SP.
1187 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1188 .addReg(SpecialRegs->getStackPointerRegister())
1189 .addReg(BufReg)
1190 .addImm(SPOffset)
1191 .addReg(0);
1192
1193 // Slot 3(Offset = 2) Backchain value (if building with -mbackchain).
1194 bool BackChain = MF->getSubtarget<SystemZSubtarget>().hasBackChain();
1195 if (BackChain) {
1196 Register BCReg = MRI.createVirtualRegister(PtrRC);
1197 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
1198 MIB = BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::LG), BCReg)
1199 .addReg(SpecialRegs->getStackPointerRegister())
1200 .addImm(TFL->getBackchainOffset(*MF))
1201 .addReg(0);
1202
1203 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1204 .addReg(BCReg)
1205 .addReg(BufReg)
1206 .addImm(BCOffset)
1207 .addReg(0);
1208 }
1209
1210 // Setup.
1211 MIB = BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::EH_SjLj_Setup))
1212 .addMBB(RestoreMBB);
1213
1214 const SystemZRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1215 MIB.addRegMask(RegInfo->getNoPreservedMask());
1216
1217 ThisMBB->addSuccessor(MainMBB);
1218 ThisMBB->addSuccessor(RestoreMBB);
1219
1220 // mainMBB:
1221 BuildMI(MainMBB, DL, TII->get(SystemZ::LHI), MainDstReg).addImm(0);
1222 MainMBB->addSuccessor(SinkMBB);
1223
1224 // sinkMBB:
1225 BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII->get(SystemZ::PHI), DstReg)
1226 .addReg(MainDstReg)
1227 .addMBB(MainMBB)
1228 .addReg(RestoreDstReg)
1229 .addMBB(RestoreMBB);
1230
1231 // restoreMBB.
1232 BuildMI(RestoreMBB, DL, TII->get(SystemZ::LHI), RestoreDstReg).addImm(1);
1233 BuildMI(RestoreMBB, DL, TII->get(SystemZ::J)).addMBB(SinkMBB);
1234 RestoreMBB->addSuccessor(SinkMBB);
1235
1236 MI.eraseFromParent();
1237
1238 return SinkMBB;
1239}
1240
1243 MachineBasicBlock *MBB) const {
1244
1245 DebugLoc DL = MI.getDebugLoc();
1246 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1247
1248 MachineFunction *MF = MBB->getParent();
1250
1251 MVT PVT = getPointerTy(MF->getDataLayout());
1252 assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
1253 Register BufReg = MI.getOperand(0).getReg();
1254 const TargetRegisterClass *RC = MRI.getRegClass(BufReg);
1255 auto *SpecialRegs = Subtarget.getSpecialRegisters();
1256
1257 Register Tmp = MRI.createVirtualRegister(RC);
1258 Register BCReg = MRI.createVirtualRegister(RC);
1259
1261
1262 const int64_t FPOffset = 0;
1263 const int64_t LabelOffset = 1 * PVT.getStoreSize();
1264 const int64_t BCOffset = 2 * PVT.getStoreSize();
1265 const int64_t SPOffset = 3 * PVT.getStoreSize();
1266 const int64_t LPOffset = 4 * PVT.getStoreSize();
1267
1268 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG), Tmp)
1269 .addReg(BufReg)
1270 .addImm(LabelOffset)
1271 .addReg(0);
1272
1273 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG),
1274 SpecialRegs->getFramePointerRegister())
1275 .addReg(BufReg)
1276 .addImm(FPOffset)
1277 .addReg(0);
1278
1279 // We are restoring R13 even though we never stored in setjmp from llvm,
1280 // as gcc always stores R13 in builtin_setjmp. We could have mixed code
1281 // gcc setjmp and llvm longjmp.
1282 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG), SystemZ::R13D)
1283 .addReg(BufReg)
1284 .addImm(LPOffset)
1285 .addReg(0);
1286
1287 bool BackChain = MF->getSubtarget<SystemZSubtarget>().hasBackChain();
1288 if (BackChain) {
1289 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG), BCReg)
1290 .addReg(BufReg)
1291 .addImm(BCOffset)
1292 .addReg(0);
1293 }
1294
1295 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG),
1296 SpecialRegs->getStackPointerRegister())
1297 .addReg(BufReg)
1298 .addImm(SPOffset)
1299 .addReg(0);
1300
1301 if (BackChain) {
1302 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
1303 BuildMI(*MBB, MI, DL, TII->get(SystemZ::STG))
1304 .addReg(BCReg)
1305 .addReg(SpecialRegs->getStackPointerRegister())
1306 .addImm(TFL->getBackchainOffset(*MF))
1307 .addReg(0);
1308 }
1309
1310 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::BR)).addReg(Tmp);
1311
1312 MI.eraseFromParent();
1313 return MBB;
1314}
1315
1317 const MachineFunction &MF) const {
1318 // Without vector support, a v2i64 store would just be split again.
1319 return MemVT != MVT::v2i64 || Subtarget.hasVector();
1320}
1321
1323 EVT VecVT) const {
1324 // Without vector support, a v2i64 is just a pair of GPRs.
1325 return !Subtarget.hasVector();
1326}
1327
1328/// Returns true if stack probing through inline assembly is requested.
1330 // If the function specifically requests inline stack probes, emit them.
1331 if (MF.getFunction().hasFnAttribute("probe-stack"))
1332 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
1333 "inline-asm";
1334 return false;
1335}
1336
1341
1346
1349 const AtomicRMWInst *RMW) const {
1350 // Don't expand subword operations as they require special treatment.
1351 if (RMW->getType()->isIntegerTy(8) || RMW->getType()->isIntegerTy(16))
1353
1354 // Don't expand if there is a target instruction available.
1355 if (Subtarget.hasInterlockedAccess1() &&
1356 (RMW->getType()->isIntegerTy(32) || RMW->getType()->isIntegerTy(64)) &&
1363
1365}
1366
1368 // We can use CGFI or CLGFI.
1369 return isInt<32>(Imm) || isUInt<32>(Imm);
1370}
1371
1373 // We can use ALGFI or SLGFI.
1374 return isUInt<32>(Imm) || isUInt<32>(-Imm);
1375}
1376
1378 EVT VT, unsigned, Align, MachineMemOperand::Flags, unsigned *Fast) const {
1379 // Unaligned accesses should never be slower than the expanded version.
1380 // We check specifically for aligned accesses in the few cases where
1381 // they are required.
1382 if (Fast)
1383 *Fast = 1;
1384 return true;
1385}
1386
1388 EVT VT = Y.getValueType();
1389
1390 // We can use NC(G)RK for types in GPRs ...
1391 if (VT == MVT::i32 || VT == MVT::i64)
1392 return Subtarget.hasMiscellaneousExtensions3();
1393
1394 // ... or VNC for types in VRs.
1395 if (VT.isVector() || VT == MVT::i128)
1396 return Subtarget.hasVector();
1397
1398 return false;
1399}
1400
1401// Information about the addressing mode for a memory access.
1403 // True if a long displacement is supported.
1405
1406 // True if use of index register is supported.
1408
1409 AddressingMode(bool LongDispl, bool IdxReg) :
1410 LongDisplacement(LongDispl), IndexReg(IdxReg) {}
1411};
1412
1413// Return the desired addressing mode for a Load which has only one use (in
1414// the same block) which is a Store.
1416 Type *Ty) {
1417 // With vector support a Load->Store combination may be combined to either
1418 // an MVC or vector operations and it seems to work best to allow the
1419 // vector addressing mode.
1420 if (HasVector)
1421 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
1422
1423 // Otherwise only the MVC case is special.
1424 bool MVC = Ty->isIntegerTy(8);
1425 return AddressingMode(!MVC/*LongDispl*/, !MVC/*IdxReg*/);
1426}
1427
1428// Return the addressing mode which seems most desirable given an LLVM
1429// Instruction pointer.
1430static AddressingMode
1433 switch (II->getIntrinsicID()) {
1434 default: break;
1435 case Intrinsic::memset:
1436 case Intrinsic::memmove:
1437 case Intrinsic::memcpy:
1438 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
1439 }
1440 }
1441
1442 if (isa<LoadInst>(I) && I->hasOneUse()) {
1443 auto *SingleUser = cast<Instruction>(*I->user_begin());
1444 if (SingleUser->getParent() == I->getParent()) {
1445 if (isa<ICmpInst>(SingleUser)) {
1446 if (auto *C = dyn_cast<ConstantInt>(SingleUser->getOperand(1)))
1447 if (C->getBitWidth() <= 64 &&
1448 (isInt<16>(C->getSExtValue()) || isUInt<16>(C->getZExtValue())))
1449 // Comparison of memory with 16 bit signed / unsigned immediate
1450 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
1451 } else if (isa<StoreInst>(SingleUser))
1452 // Load->Store
1453 return getLoadStoreAddrMode(HasVector, I->getType());
1454 }
1455 } else if (auto *StoreI = dyn_cast<StoreInst>(I)) {
1456 if (auto *LoadI = dyn_cast<LoadInst>(StoreI->getValueOperand()))
1457 if (LoadI->hasOneUse() && LoadI->getParent() == I->getParent())
1458 // Load->Store
1459 return getLoadStoreAddrMode(HasVector, LoadI->getType());
1460 }
1461
1462 if (HasVector && (isa<LoadInst>(I) || isa<StoreInst>(I))) {
1463
1464 // * Use LDE instead of LE/LEY for z13 to avoid partial register
1465 // dependencies (LDE only supports small offsets).
1466 // * Utilize the vector registers to hold floating point
1467 // values (vector load / store instructions only support small
1468 // offsets).
1469
1470 Type *MemAccessTy = (isa<LoadInst>(I) ? I->getType() :
1471 I->getOperand(0)->getType());
1472 bool IsFPAccess = MemAccessTy->isFloatingPointTy();
1473 bool IsVectorAccess = MemAccessTy->isVectorTy();
1474
1475 // A store of an extracted vector element will be combined into a VSTE type
1476 // instruction.
1477 if (!IsVectorAccess && isa<StoreInst>(I)) {
1478 Value *DataOp = I->getOperand(0);
1479 if (isa<ExtractElementInst>(DataOp))
1480 IsVectorAccess = true;
1481 }
1482
1483 // A load which gets inserted into a vector element will be combined into a
1484 // VLE type instruction.
1485 if (!IsVectorAccess && isa<LoadInst>(I) && I->hasOneUse()) {
1486 User *LoadUser = *I->user_begin();
1487 if (isa<InsertElementInst>(LoadUser))
1488 IsVectorAccess = true;
1489 }
1490
1491 if (IsFPAccess || IsVectorAccess)
1492 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
1493 }
1494
1495 return AddressingMode(true/*LongDispl*/, true/*IdxReg*/);
1496}
1497
1499 const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I) const {
1500 // Punt on globals for now, although they can be used in limited
1501 // RELATIVE LONG cases.
1502 if (AM.BaseGV)
1503 return false;
1504
1505 // Require a 20-bit signed offset.
1506 if (!isInt<20>(AM.BaseOffs))
1507 return false;
1508
1509 bool RequireD12 =
1510 Subtarget.hasVector() && (Ty->isVectorTy() || Ty->isIntegerTy(128));
1511 AddressingMode SupportedAM(!RequireD12, true);
1512 if (I != nullptr)
1513 SupportedAM = supportedAddressingMode(I, Subtarget.hasVector());
1514
1515 if (!SupportedAM.LongDisplacement && !isUInt<12>(AM.BaseOffs))
1516 return false;
1517
1518 if (!SupportedAM.IndexReg)
1519 // No indexing allowed.
1520 return AM.Scale == 0;
1521 else
1522 // Indexing is OK but no scale factor can be applied.
1523 return AM.Scale == 0 || AM.Scale == 1;
1524}
1525
1527 LLVMContext &Context, std::vector<EVT> &MemOps, unsigned Limit,
1528 const MemOp &Op, unsigned DstAS, unsigned SrcAS,
1529 const AttributeList &FuncAttributes, EVT *LargestVT) const {
1530
1531 assert(Limit != ~0U &&
1532 "Expected EmitTargetCodeForMemXXX() to handle AlwaysInline cases.");
1533
1534 if (Op.isZeroMemset())
1535 return false; // Memset zero: Use XC.
1536
1537 const int MVCFastLen = 16;
1538 // Use MVC up to 16 bytes for memcpy. Small memset uses STC/MVI for first
1539 // byte.
1540 if (Op.isMemcpy() && Op.size() <= MVCFastLen)
1541 return false;
1542 if (Op.isMemset() && Op.size() - 1 <= MVCFastLen)
1543 return false;
1544
1545 // Avoid unaligned VL/VST:s.
1546 if ((Op.size() >= 16 && !Op.isAligned(Align(8))) ||
1547 (Op.size() >= 25 && Op.size() <= 31))
1548 return false;
1549
1551 Context, MemOps, Limit, Op, DstAS, SrcAS, FuncAttributes, LargestVT);
1552}
1553
1555 LLVMContext &Context, const MemOp &Op,
1556 const AttributeList &FuncAttributes) const {
1557 return Subtarget.hasVector() ? MVT::v2i64 : MVT::Other;
1558}
1559
1560bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
1561 if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
1562 return false;
1563 unsigned FromBits = FromType->getPrimitiveSizeInBits().getFixedValue();
1564 unsigned ToBits = ToType->getPrimitiveSizeInBits().getFixedValue();
1565 return FromBits > ToBits;
1566}
1567
1569 if (!FromVT.isInteger() || !ToVT.isInteger())
1570 return false;
1571 unsigned FromBits = FromVT.getFixedSizeInBits();
1572 unsigned ToBits = ToVT.getFixedSizeInBits();
1573 return FromBits > ToBits;
1574}
1575
1577 unsigned Opc = N->getOpcode();
1578 if ((Opc == ISD::SINT_TO_FP || Opc == ISD::UINT_TO_FP) && VT.isVector() &&
1579 VT.getScalarSizeInBits() < N->getValueType(0).getScalarSizeInBits())
1580 return false;
1582}
1583
1584//===----------------------------------------------------------------------===//
1585// Inline asm support
1586//===----------------------------------------------------------------------===//
1587
1590 if (Constraint.size() == 1) {
1591 switch (Constraint[0]) {
1592 case 'a': // Address register
1593 case 'd': // Data register (equivalent to 'r')
1594 case 'f': // Floating-point register
1595 case 'h': // High-part register
1596 case 'r': // General-purpose register
1597 case 'v': // Vector register
1598 return C_RegisterClass;
1599
1600 case 'Q': // Memory with base and unsigned 12-bit displacement
1601 case 'R': // Likewise, plus an index
1602 case 'S': // Memory with base and signed 20-bit displacement
1603 case 'T': // Likewise, plus an index
1604 case 'm': // Equivalent to 'T'.
1605 return C_Memory;
1606
1607 case 'I': // Unsigned 8-bit constant
1608 case 'J': // Unsigned 12-bit constant
1609 case 'K': // Signed 16-bit constant
1610 case 'L': // Signed 20-bit displacement (on all targets we support)
1611 case 'M': // 0x7fffffff
1612 return C_Immediate;
1613
1614 default:
1615 break;
1616 }
1617 } else if (Constraint.size() == 2 && Constraint[0] == 'Z') {
1618 switch (Constraint[1]) {
1619 case 'Q': // Address with base and unsigned 12-bit displacement
1620 case 'R': // Likewise, plus an index
1621 case 'S': // Address with base and signed 20-bit displacement
1622 case 'T': // Likewise, plus an index
1623 return C_Address;
1624
1625 default:
1626 break;
1627 }
1628 } else if (Constraint.size() == 5 && Constraint.starts_with("{")) {
1629 if (StringRef("{@cc}").compare(Constraint) == 0)
1630 return C_Other;
1631 }
1632 return TargetLowering::getConstraintType(Constraint);
1633}
1634
1637 AsmOperandInfo &Info, const char *Constraint) const {
1639 Value *CallOperandVal = Info.CallOperandVal;
1640 // If we don't have a value, we can't do a match,
1641 // but allow it at the lowest weight.
1642 if (!CallOperandVal)
1643 return CW_Default;
1644 Type *type = CallOperandVal->getType();
1645 // Look at the constraint type.
1646 switch (*Constraint) {
1647 default:
1648 Weight = TargetLowering::getSingleConstraintMatchWeight(Info, Constraint);
1649 break;
1650
1651 case 'a': // Address register
1652 case 'd': // Data register (equivalent to 'r')
1653 case 'h': // High-part register
1654 case 'r': // General-purpose register
1655 Weight =
1656 CallOperandVal->getType()->isIntegerTy() ? CW_Register : CW_Default;
1657 break;
1658
1659 case 'f': // Floating-point register
1660 if (!useSoftFloat())
1661 Weight = type->isFloatingPointTy() ? CW_Register : CW_Default;
1662 break;
1663
1664 case 'v': // Vector register
1665 if (Subtarget.hasVector())
1666 Weight = (type->isVectorTy() || type->isFloatingPointTy()) ? CW_Register
1667 : CW_Default;
1668 break;
1669
1670 case 'I': // Unsigned 8-bit constant
1671 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1672 if (isUInt<8>(C->getZExtValue()))
1673 Weight = CW_Constant;
1674 break;
1675
1676 case 'J': // Unsigned 12-bit constant
1677 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1678 if (isUInt<12>(C->getZExtValue()))
1679 Weight = CW_Constant;
1680 break;
1681
1682 case 'K': // Signed 16-bit constant
1683 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1684 if (isInt<16>(C->getSExtValue()))
1685 Weight = CW_Constant;
1686 break;
1687
1688 case 'L': // Signed 20-bit displacement (on all targets we support)
1689 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1690 if (isInt<20>(C->getSExtValue()))
1691 Weight = CW_Constant;
1692 break;
1693
1694 case 'M': // 0x7fffffff
1695 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1696 if (C->getZExtValue() == 0x7fffffff)
1697 Weight = CW_Constant;
1698 break;
1699 }
1700 return Weight;
1701}
1702
1703// Parse a "{tNNN}" register constraint for which the register type "t"
1704// has already been verified. MC is the class associated with "t" and
1705// Map maps 0-based register numbers to LLVM register numbers.
1706static std::pair<unsigned, const TargetRegisterClass *>
1708 const unsigned *Map, unsigned Size) {
1709 assert(*(Constraint.end()-1) == '}' && "Missing '}'");
1710 if (isdigit(Constraint[2])) {
1711 unsigned Index;
1712 bool Failed =
1713 Constraint.slice(2, Constraint.size() - 1).getAsInteger(10, Index);
1714 if (!Failed && Index < Size && Map[Index])
1715 return std::make_pair(Map[Index], RC);
1716 }
1717 return std::make_pair(0U, nullptr);
1718}
1719
1720std::pair<unsigned, const TargetRegisterClass *>
1722 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
1723 if (Constraint.size() == 1) {
1724 // GCC Constraint Letters
1725 switch (Constraint[0]) {
1726 default: break;
1727 case 'd': // Data register (equivalent to 'r')
1728 case 'r': // General-purpose register
1729 // MVT::Other has no size, e.g. an aggregate operand that could not be
1730 // converted to an integer type.
1731 if (VT == MVT::Other)
1732 break;
1733 if (VT.getSizeInBits() == 64)
1734 return std::make_pair(0U, &SystemZ::GR64BitRegClass);
1735 else if (VT.getSizeInBits() == 128)
1736 return std::make_pair(0U, &SystemZ::GR128BitRegClass);
1737 return std::make_pair(0U, &SystemZ::GR32BitRegClass);
1738
1739 case 'a': // Address register
1740 if (VT == MVT::i64)
1741 return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
1742 else if (VT == MVT::i128)
1743 return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
1744 return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
1745
1746 case 'h': // High-part register (an LLVM extension)
1747 return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
1748
1749 case 'f': // Floating-point register
1750 if (!useSoftFloat()) {
1751 if (VT == MVT::Other)
1752 break;
1753 if (VT.getSizeInBits() == 16)
1754 return std::make_pair(0U, &SystemZ::FP16BitRegClass);
1755 else if (VT.getSizeInBits() == 64)
1756 return std::make_pair(0U, &SystemZ::FP64BitRegClass);
1757 else if (VT.getSizeInBits() == 128)
1758 return std::make_pair(0U, &SystemZ::FP128BitRegClass);
1759 return std::make_pair(0U, &SystemZ::FP32BitRegClass);
1760 }
1761 break;
1762
1763 case 'v': // Vector register
1764 if (Subtarget.hasVector()) {
1765 if (VT == MVT::Other)
1766 break;
1767 if (VT.getSizeInBits() == 16)
1768 return std::make_pair(0U, &SystemZ::VR16BitRegClass);
1769 if (VT.getSizeInBits() == 32)
1770 return std::make_pair(0U, &SystemZ::VR32BitRegClass);
1771 if (VT.getSizeInBits() == 64)
1772 return std::make_pair(0U, &SystemZ::VR64BitRegClass);
1773 return std::make_pair(0U, &SystemZ::VR128BitRegClass);
1774 }
1775 break;
1776 }
1777 }
1778 if (Constraint.starts_with("{")) {
1779
1780 // A clobber constraint (e.g. ~{f0}) will have MVT::Other which is illegal
1781 // to check the size on.
1782 auto getVTSizeInBits = [&VT]() {
1783 return VT == MVT::Other ? 0 : VT.getSizeInBits();
1784 };
1785
1786 // We need to override the default register parsing for GPRs and FPRs
1787 // because the interpretation depends on VT. The internal names of
1788 // the registers are also different from the external names
1789 // (F0D and F0S instead of F0, etc.).
1790 if (Constraint[1] == 'r') {
1791 if (getVTSizeInBits() == 32)
1792 return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
1794 if (getVTSizeInBits() == 128)
1795 return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
1797 return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
1799 }
1800 if (Constraint[1] == 'f') {
1801 if (useSoftFloat())
1802 return std::make_pair(
1803 0u, static_cast<const TargetRegisterClass *>(nullptr));
1804 if (getVTSizeInBits() == 16)
1805 return parseRegisterNumber(Constraint, &SystemZ::FP16BitRegClass,
1807 if (getVTSizeInBits() == 32)
1808 return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
1810 if (getVTSizeInBits() == 128)
1811 return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
1813 return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
1815 }
1816 if (Constraint[1] == 'v') {
1817 if (!Subtarget.hasVector())
1818 return std::make_pair(
1819 0u, static_cast<const TargetRegisterClass *>(nullptr));
1820 if (getVTSizeInBits() == 16)
1821 return parseRegisterNumber(Constraint, &SystemZ::VR16BitRegClass,
1823 if (getVTSizeInBits() == 32)
1824 return parseRegisterNumber(Constraint, &SystemZ::VR32BitRegClass,
1826 if (getVTSizeInBits() == 64)
1827 return parseRegisterNumber(Constraint, &SystemZ::VR64BitRegClass,
1829 return parseRegisterNumber(Constraint, &SystemZ::VR128BitRegClass,
1831 }
1832 if (Constraint[1] == '@') {
1833 if (StringRef("{@cc}").compare(Constraint) == 0)
1834 return std::make_pair(SystemZ::CC, &SystemZ::CCRRegClass);
1835 }
1836 }
1837 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1838}
1839
1840// FIXME? Maybe this could be a TableGen attribute on some registers and
1841// this table could be generated automatically from RegInfo.
1844 const MachineFunction &MF) const {
1845 Register Reg =
1847 .Case("r4", Subtarget.isTargetXPLINK64() ? SystemZ::R4D
1848 : SystemZ::NoRegister)
1849 .Case("r15",
1850 Subtarget.isTargetELF() ? SystemZ::R15D : SystemZ::NoRegister)
1851 .Default(Register());
1852
1853 return Reg;
1854}
1855
1857 ExceptionHandling EH, const Constant *PersonalityFn) const {
1858 return Subtarget.isTargetXPLINK64() ? SystemZ::R1D : SystemZ::R6D;
1859}
1860
1862 ExceptionHandling EH, const Constant *PersonalityFn) const {
1863 return Subtarget.isTargetXPLINK64() ? SystemZ::R2D : SystemZ::R7D;
1864}
1865
1866// Convert condition code in CCReg to an i32 value.
1868 SDLoc DL(CCReg);
1869 SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, CCReg);
1870 return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM,
1871 DAG.getConstant(SystemZ::IPM_CC, DL, MVT::i32));
1872}
1873
1874// Lower @cc targets via setcc.
1876 SDValue &Chain, SDValue &Glue, const SDLoc &DL,
1877 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
1878 if (StringRef("{@cc}").compare(OpInfo.ConstraintCode) != 0)
1879 return SDValue();
1880
1881 // Check that return type is valid.
1882 if (OpInfo.ConstraintVT.isVector() || !OpInfo.ConstraintVT.isInteger() ||
1883 OpInfo.ConstraintVT.getSizeInBits() < 8)
1884 report_fatal_error("Glue output operand is of invalid type");
1885
1886 if (Glue.getNode()) {
1887 Glue = DAG.getCopyFromReg(Chain, DL, SystemZ::CC, MVT::i32, Glue);
1888 Chain = Glue.getValue(1);
1889 } else
1890 Glue = DAG.getCopyFromReg(Chain, DL, SystemZ::CC, MVT::i32);
1891 return getCCResult(DAG, Glue);
1892}
1893
1895 SDValue Op, StringRef Constraint, std::vector<SDValue> &Ops,
1896 SelectionDAG &DAG) const {
1897 // Only support length 1 constraints for now.
1898 if (Constraint.size() == 1) {
1899 switch (Constraint[0]) {
1900 case 'I': // Unsigned 8-bit constant
1901 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1902 if (isUInt<8>(C->getZExtValue()))
1903 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1904 Op.getValueType()));
1905 return;
1906
1907 case 'J': // Unsigned 12-bit constant
1908 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1909 if (isUInt<12>(C->getZExtValue()))
1910 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1911 Op.getValueType()));
1912 return;
1913
1914 case 'K': // Signed 16-bit constant
1915 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1916 if (isInt<16>(C->getSExtValue()))
1917 Ops.push_back(DAG.getSignedTargetConstant(
1918 C->getSExtValue(), SDLoc(Op), Op.getValueType()));
1919 return;
1920
1921 case 'L': // Signed 20-bit displacement (on all targets we support)
1922 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1923 if (isInt<20>(C->getSExtValue()))
1924 Ops.push_back(DAG.getSignedTargetConstant(
1925 C->getSExtValue(), SDLoc(Op), Op.getValueType()));
1926 return;
1927
1928 case 'M': // 0x7fffffff
1929 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1930 if (C->getZExtValue() == 0x7fffffff)
1931 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1932 Op.getValueType()));
1933 return;
1934 }
1935 }
1937}
1938
1939//===----------------------------------------------------------------------===//
1940// Calling conventions
1941//===----------------------------------------------------------------------===//
1942
1943#define GET_CALLING_CONV_IMPL
1944#include "SystemZGenCallingConv.inc"
1945
1947 CallingConv::ID) const {
1948 static const MCPhysReg ScratchRegs[] = { SystemZ::R0D, SystemZ::R1D,
1949 SystemZ::R14D, 0 };
1950 return ScratchRegs;
1951}
1952
1954 Type *ToType) const {
1955 return isTruncateFree(FromType, ToType);
1956}
1957
1959 return CI->isTailCall();
1960}
1961
1962// Value is a value that has been passed to us in the location described by VA
1963// (and so has type VA.getLocVT()). Convert Value to VA.getValVT(), chaining
1964// any loads onto Chain.
1966 CCValAssign &VA, SDValue Chain,
1967 SDValue Value) {
1968 // If the argument has been promoted from a smaller type, insert an
1969 // assertion to capture this.
1970 if (VA.getLocInfo() == CCValAssign::SExt)
1972 DAG.getValueType(VA.getValVT()));
1973 else if (VA.getLocInfo() == CCValAssign::ZExt)
1975 DAG.getValueType(VA.getValVT()));
1976
1977 if (VA.isExtInLoc())
1978 Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
1979 else if (VA.getLocInfo() == CCValAssign::BCvt) {
1980 // If this is a short vector argument loaded from the stack,
1981 // extend from i64 to full vector size and then bitcast.
1982 assert(VA.getLocVT() == MVT::i64);
1983 assert(VA.getValVT().isVector());
1984 Value = DAG.getBuildVector(MVT::v2i64, DL, {Value, DAG.getUNDEF(MVT::i64)});
1985 Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
1986 } else
1987 assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
1988 return Value;
1989}
1990
1991// Value is a value of type VA.getValVT() that we need to copy into
1992// the location described by VA. Return a copy of Value converted to
1993// VA.getValVT(). The caller is responsible for handling indirect values.
1995 CCValAssign &VA, SDValue Value) {
1996 switch (VA.getLocInfo()) {
1997 case CCValAssign::SExt:
1998 return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
1999 case CCValAssign::ZExt:
2000 return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
2001 case CCValAssign::AExt:
2002 return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
2003 case CCValAssign::BCvt: {
2004 assert(VA.getLocVT() == MVT::i64 || VA.getLocVT() == MVT::i128);
2005 assert(VA.getValVT().isVector() || VA.getValVT() == MVT::f32 ||
2006 VA.getValVT() == MVT::f64 || VA.getValVT() == MVT::f128);
2007 // For an f32 vararg we need to first promote it to an f64 and then
2008 // bitcast it to an i64.
2009 if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i64)
2010 Value = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f64, Value);
2011 MVT BitCastToType = VA.getValVT().isVector() && VA.getLocVT() == MVT::i64
2012 ? MVT::v2i64
2013 : VA.getLocVT();
2014 Value = DAG.getNode(ISD::BITCAST, DL, BitCastToType, Value);
2015 // For ELF, this is a short vector argument to be stored to the stack,
2016 // bitcast to v2i64 and then extract first element.
2017 if (BitCastToType == MVT::v2i64)
2018 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
2019 DAG.getConstant(0, DL, MVT::i32));
2020 return Value;
2021 }
2022 case CCValAssign::Full:
2023 return Value;
2024 default:
2025 llvm_unreachable("Unhandled getLocInfo()");
2026 }
2027}
2028
2030 SDLoc DL(In);
2031 SDValue Lo, Hi;
2032 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128)) {
2033 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, In);
2034 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
2035 DAG.getNode(ISD::SRL, DL, MVT::i128, In,
2036 DAG.getConstant(64, DL, MVT::i32)));
2037 } else {
2038 std::tie(Lo, Hi) = DAG.SplitScalar(In, DL, MVT::i64, MVT::i64);
2039 }
2040
2041 return DAG.getNode(SystemZISD::PAIR128, DL, MVT::v2i64, Hi, Lo);
2042}
2043
2045 SDLoc DL(In);
2046 SDValue Hi = DAG.getTargetExtractSubreg(SystemZ::subreg_h64,
2047 DL, MVT::i64, In);
2048 SDValue Lo = DAG.getTargetExtractSubreg(SystemZ::subreg_l64,
2049 DL, MVT::i64, In);
2050
2051 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128)) {
2052 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, Lo);
2053 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, Hi);
2054 Hi = DAG.getNode(ISD::SHL, DL, MVT::i128, Hi,
2055 DAG.getConstant(64, DL, MVT::i32));
2056 return DAG.getNode(ISD::OR, DL, MVT::i128, Lo, Hi);
2057 } else {
2058 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128, Lo, Hi);
2059 }
2060}
2061
2063 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
2064 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
2065 EVT ValueVT = Val.getValueType();
2066 if (ValueVT.getSizeInBits() == 128 && NumParts == 1 && PartVT == MVT::Untyped) {
2067 // Inline assembly operand.
2068 Parts[0] = lowerI128ToGR128(DAG, DAG.getBitcast(MVT::i128, Val));
2069 return true;
2070 }
2071
2072 return false;
2073}
2074
2076 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
2077 MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const {
2078 if (ValueVT.getSizeInBits() == 128 && NumParts == 1 && PartVT == MVT::Untyped) {
2079 // Inline assembly operand.
2080 SDValue Res = lowerGR128ToI128(DAG, Parts[0]);
2081 return DAG.getBitcast(ValueVT, Res);
2082 }
2083
2084 return SDValue();
2085}
2086
2087// The first part of a split stack argument is at index I in Args (and
2088// ArgLocs). Return the type of a part and the number of them by reference.
2089template <class ArgTy>
2091 SmallVector<CCValAssign, 16> &ArgLocs, unsigned I,
2092 MVT &PartVT, unsigned &NumParts) {
2093 if (!Args[I].Flags.isSplit())
2094 return false;
2095 assert(I < ArgLocs.size() && ArgLocs.size() == Args.size() &&
2096 "ArgLocs havoc.");
2097 PartVT = ArgLocs[I].getValVT();
2098 NumParts = 1;
2099 for (unsigned PartIdx = I + 1;; ++PartIdx) {
2100 assert(PartIdx != ArgLocs.size() && "SplitEnd not found.");
2101 assert(ArgLocs[PartIdx].getValVT() == PartVT && "Unsupported split.");
2102 ++NumParts;
2103 if (Args[PartIdx].Flags.isSplitEnd())
2104 break;
2105 }
2106 return true;
2107}
2108
2109// Return the virtual register holding the incoming "ADA" special register (R5)
2110// of an XPLINK function, creating it on first use. LowerFormalArguments is not
2111// called for naked functions, but those still get R5 on entry and may use it to
2112// address globals and functions.
2114 SystemZMachineFunctionInfo *FuncInfo =
2116 Register ADAvReg = FuncInfo->getADAVirtualRegister();
2117 if (ADAvReg)
2118 return ADAvReg;
2119
2121 ADAvReg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
2122 auto *Regs = static_cast<SystemZXPLINK64Registers *>(
2124 MRI.addLiveIn(Regs->getADARegister(), ADAvReg);
2125 FuncInfo->setADAVirtualRegister(ADAvReg);
2126 return ADAvReg;
2127}
2128
2130 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
2131 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2132 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2134 MachineFrameInfo &MFI = MF.getFrameInfo();
2136 SystemZMachineFunctionInfo *FuncInfo =
2138 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>();
2139 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2140
2141 // Assign locations to all of the incoming arguments.
2143 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2144 CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
2145 FuncInfo->setSizeOfFnParams(CCInfo.getStackSize());
2146
2147 unsigned NumFixedGPRs = 0;
2148 unsigned NumFixedFPRs = 0;
2149 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
2150 SDValue ArgValue;
2151 CCValAssign &VA = ArgLocs[I];
2152 EVT LocVT = VA.getLocVT();
2153 if (VA.isRegLoc()) {
2154 // Arguments passed in registers
2155 const TargetRegisterClass *RC;
2156 switch (LocVT.getSimpleVT().SimpleTy) {
2157 default:
2158 // Integers smaller than i64 should be promoted to i64.
2159 llvm_unreachable("Unexpected argument type");
2160 case MVT::i32:
2161 NumFixedGPRs += 1;
2162 RC = &SystemZ::GR32BitRegClass;
2163 break;
2164 case MVT::i64:
2165 NumFixedGPRs += 1;
2166 RC = &SystemZ::GR64BitRegClass;
2167 break;
2168 case MVT::f16:
2169 NumFixedFPRs += 1;
2170 RC = &SystemZ::FP16BitRegClass;
2171 break;
2172 case MVT::f32:
2173 NumFixedFPRs += 1;
2174 RC = &SystemZ::FP32BitRegClass;
2175 break;
2176 case MVT::f64:
2177 NumFixedFPRs += 1;
2178 RC = &SystemZ::FP64BitRegClass;
2179 break;
2180 case MVT::f128:
2181 NumFixedFPRs += 2;
2182 RC = &SystemZ::FP128BitRegClass;
2183 break;
2184 case MVT::v16i8:
2185 case MVT::v8i16:
2186 case MVT::v4i32:
2187 case MVT::v2i64:
2188 case MVT::v8f16:
2189 case MVT::v4f32:
2190 case MVT::v2f64:
2191 RC = &SystemZ::VR128BitRegClass;
2192 break;
2193 }
2194
2195 Register VReg = MRI.createVirtualRegister(RC);
2196 MRI.addLiveIn(VA.getLocReg(), VReg);
2197 ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
2198 } else {
2199 assert(VA.isMemLoc() && "Argument not register or memory");
2200
2201 // Create the frame index object for this incoming parameter.
2202 // FIXME: Pre-include call frame size in the offset, should not
2203 // need to manually add it here.
2204 int64_t ArgSPOffset = VA.getLocMemOffset();
2205 if (Subtarget.isTargetXPLINK64()) {
2206 auto &XPRegs =
2207 Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
2208 ArgSPOffset += XPRegs.getCallFrameSize();
2209 }
2210 int FI =
2211 MFI.CreateFixedObject(LocVT.getSizeInBits() / 8, ArgSPOffset, true);
2212
2213 // Create the SelectionDAG nodes corresponding to a load
2214 // from this parameter. Unpromoted ints and floats are
2215 // passed as right-justified 8-byte values.
2216 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2217 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32 ||
2218 VA.getLocVT() == MVT::f16) {
2219 unsigned SlotOffs = VA.getLocVT() == MVT::f16 ? 6 : 4;
2220 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2221 DAG.getIntPtrConstant(SlotOffs, DL));
2222 }
2223 ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
2225 }
2226
2227 // Convert the value of the argument register into the value that's
2228 // being passed.
2229 if (VA.getLocInfo() == CCValAssign::Indirect) {
2230 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
2232 // If the original argument was split (e.g. i128), we need
2233 // to load all parts of it here (using the same address).
2234 MVT PartVT;
2235 unsigned NumParts;
2236 if (analyzeArgSplit(Ins, ArgLocs, I, PartVT, NumParts)) {
2237 for (unsigned PartIdx = 1; PartIdx < NumParts; ++PartIdx) {
2238 ++I;
2239 CCValAssign &PartVA = ArgLocs[I];
2240 unsigned PartOffset = Ins[I].PartOffset;
2241 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
2242 DAG.getIntPtrConstant(PartOffset, DL));
2243 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
2245 assert(PartOffset && "Offset should be non-zero.");
2246 }
2247 }
2248 } else if (Subtarget.isTargetXPLINK64() &&
2249 (VA.getLocInfo() == CCValAssign::SExt ||
2250 VA.getLocInfo() == CCValAssign::ZExt) &&
2251 Ins[I].ArgVT.isSimple()) {
2252 // Some prior z/OS compilers do not always perform the extension of
2253 // short integer arguments or pointers. To accommodate those, do not
2254 // rely on that extension by avoiding any AssertSext/AssertZext nodes by
2255 // directly truncating ArgValue to the original argument type.
2256 MVT OrigVT = Ins[I].ArgVT.getSimpleVT();
2257 InVals.push_back(DAG.getNode(ISD::TRUNCATE, DL, OrigVT, ArgValue));
2258 } else
2259 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
2260 }
2261
2262 if (IsVarArg && Subtarget.isTargetXPLINK64()) {
2263 // Save the number of non-varargs registers for later use by va_start, etc.
2264 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
2265 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
2266
2267 auto *Regs = static_cast<SystemZXPLINK64Registers *>(
2268 Subtarget.getSpecialRegisters());
2269
2270 // Likewise the address (in the form of a frame index) of where the
2271 // first stack vararg would be. The 1-byte size here is arbitrary.
2272 // FIXME: Pre-include call frame size in the offset, should not
2273 // need to manually add it here.
2274 int64_t VarArgOffset = CCInfo.getStackSize() + Regs->getCallFrameSize();
2275 int FI = MFI.CreateFixedObject(1, VarArgOffset, true);
2276 FuncInfo->setVarArgsFrameIndex(FI);
2277 }
2278
2279 if (IsVarArg && Subtarget.isTargetELF()) {
2280 // Save the number of non-varargs registers for later use by va_start, etc.
2281 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
2282 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
2283
2284 // Likewise the address (in the form of a frame index) of where the
2285 // first stack vararg would be. The 1-byte size here is arbitrary.
2286 int64_t VarArgsOffset = CCInfo.getStackSize();
2287 FuncInfo->setVarArgsFrameIndex(
2288 MFI.CreateFixedObject(1, VarArgsOffset, true));
2289
2290 // ...and a similar frame index for the caller-allocated save area
2291 // that will be used to store the incoming registers.
2292 int64_t RegSaveOffset =
2293 -SystemZMC::ELFCallFrameSize + TFL->getRegSpillOffset(MF, SystemZ::R2D) - 16;
2294 unsigned RegSaveIndex = MFI.CreateFixedObject(1, RegSaveOffset, true);
2295 FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
2296
2297 // Store the FPR varargs in the reserved frame slots. (We store the
2298 // GPRs as part of the prologue.)
2299 if (NumFixedFPRs < SystemZ::ELFNumArgFPRs && !useSoftFloat()) {
2301 for (unsigned I = NumFixedFPRs; I < SystemZ::ELFNumArgFPRs; ++I) {
2302 unsigned Offset = TFL->getRegSpillOffset(MF, SystemZ::ELFArgFPRs[I]);
2303 int FI =
2305 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2307 &SystemZ::FP64BitRegClass);
2308 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
2309 MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
2311 }
2312 // Join the stores, which are independent of one another.
2313 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2314 ArrayRef(&MemOps[NumFixedFPRs],
2315 SystemZ::ELFNumArgFPRs - NumFixedFPRs));
2316 }
2317 }
2318
2319 return Chain;
2320}
2321
2322static bool canUseSiblingCall(const CCState &ArgCCInfo,
2325 // Punt if there are any indirect or stack arguments, or if the call
2326 // needs the callee-saved argument register R6, or if the call uses
2327 // the callee-saved register arguments SwiftSelf and SwiftError.
2328 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
2329 CCValAssign &VA = ArgLocs[I];
2331 return false;
2332 if (!VA.isRegLoc())
2333 return false;
2334 Register Reg = VA.getLocReg();
2335 if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
2336 return false;
2337 if (Outs[I].Flags.isSwiftSelf() || Outs[I].Flags.isSwiftError())
2338 return false;
2339 }
2340 return true;
2341}
2342
2344 unsigned Offset, bool LoadAdr = false) {
2348
2349 SDValue Reg = DAG.getRegister(ADAvReg, PtrVT);
2350 SDValue Ofs = DAG.getTargetConstant(Offset, DL, PtrVT);
2351
2352 SDValue Result = DAG.getNode(SystemZISD::ADA_ENTRY, DL, PtrVT, Val, Reg, Ofs);
2353 if (!LoadAdr)
2354 Result = DAG.getLoad(
2355 PtrVT, DL, DAG.getEntryNode(), Result, MachinePointerInfo(), Align(8),
2357
2358 return Result;
2359}
2360
2361// ADA access using Global value
2362// Note: for functions, address of descriptor is returned
2364 EVT PtrVT) {
2365 unsigned ADAtype;
2366 bool LoadAddr = false;
2367 const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV);
2368 bool IsFunction =
2369 (isa<Function>(GV)) || (GA && isa<Function>(GA->getAliaseeObject()));
2370 bool IsInternal = (GV->hasInternalLinkage() || GV->hasPrivateLinkage());
2371
2372 if (IsFunction) {
2373 if (IsInternal) {
2375 LoadAddr = true;
2376 } else
2378 } else {
2380 }
2381 SDValue Val = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ADAtype);
2382
2383 return getADAEntry(DAG, Val, DL, 0, LoadAddr);
2384}
2385
2386static bool getzOSCalleeAndADA(SelectionDAG &DAG, SDValue &Callee, SDValue &ADA,
2387 SDLoc &DL, SDValue &Chain) {
2388 unsigned ADADelta = 0; // ADA offset in desc.
2389 unsigned EPADelta = 8; // EPA offset in desc.
2392
2393 // XPLink calling convention.
2394 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2395 bool IsInternal = (G->getGlobal()->hasInternalLinkage() ||
2396 G->getGlobal()->hasPrivateLinkage());
2397 if (IsInternal) {
2399 ADA = DAG.getCopyFromReg(Chain, DL, ADAvReg, PtrVT);
2400 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
2401 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2402 return true;
2403 } else {
2405 G->getGlobal(), DL, PtrVT, 0, SystemZII::MO_ADA_DIRECT_FUNC_DESC);
2406 ADA = getADAEntry(DAG, GA, DL, ADADelta);
2407 Callee = getADAEntry(DAG, GA, DL, EPADelta);
2408 }
2409 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2411 E->getSymbol(), PtrVT, SystemZII::MO_ADA_DIRECT_FUNC_DESC);
2412 ADA = getADAEntry(DAG, ES, DL, ADADelta);
2413 Callee = getADAEntry(DAG, ES, DL, EPADelta);
2414 } else {
2415 // Function pointer case
2416 ADA = DAG.getNode(ISD::ADD, DL, PtrVT, Callee,
2417 DAG.getConstant(ADADelta, DL, PtrVT));
2418 ADA = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), ADA,
2420 Callee = DAG.getNode(ISD::ADD, DL, PtrVT, Callee,
2421 DAG.getConstant(EPADelta, DL, PtrVT));
2422 Callee = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Callee,
2424 }
2425 return false;
2426}
2427
2428SDValue
2430 SmallVectorImpl<SDValue> &InVals) const {
2431 SelectionDAG &DAG = CLI.DAG;
2432 SDLoc &DL = CLI.DL;
2434 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2436 SDValue Chain = CLI.Chain;
2437 SDValue Callee = CLI.Callee;
2438 bool &IsTailCall = CLI.IsTailCall;
2439 CallingConv::ID CallConv = CLI.CallConv;
2440 bool IsVarArg = CLI.IsVarArg;
2442 EVT PtrVT = getPointerTy(MF.getDataLayout());
2443 LLVMContext &Ctx = *DAG.getContext();
2444 SystemZCallingConventionRegisters *Regs = Subtarget.getSpecialRegisters();
2445
2446 // FIXME: z/OS support to be added in later.
2447 if (Subtarget.isTargetXPLINK64()) {
2448 if (CLI.CB && CLI.CB->isMustTailCall())
2449 report_fatal_error("musttail call is not supported on XPLINK64");
2450 IsTailCall = false;
2451 }
2452
2453 // Integer args <=32 bits should have an extension attribute.
2454 verifyNarrowIntegerArgs_Call(CLI, Outs, &MF.getFunction(), Callee);
2455
2456 // Analyze the operands of the call, assigning locations to each operand.
2458 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, Ctx);
2459 ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
2460
2461 // We don't support GuaranteedTailCallOpt, only automatically-detected
2462 // sibling calls.
2463 if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs, Outs))
2464 IsTailCall = false;
2465
2466 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
2467 report_fatal_error("failed to perform tail call elimination on a call "
2468 "site marked musttail");
2469
2470 // Get a count of how many bytes are to be pushed on the stack.
2471 unsigned NumBytes = ArgCCInfo.getStackSize();
2472
2473 // Mark the start of the call.
2474 if (!IsTailCall)
2475 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
2476
2477 // Copy argument values to their designated locations.
2479 SmallVector<SDValue, 8> MemOpChains;
2480 SDValue StackPtr;
2481 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
2482 CCValAssign &VA = ArgLocs[I];
2483 SDValue ArgValue = OutVals[I];
2484
2485 if (VA.getLocInfo() == CCValAssign::Indirect) {
2486 // Store the argument in a stack slot and pass its address.
2487 EVT SlotVT;
2488 MVT PartVT;
2489 unsigned NumParts = 1;
2490 if (analyzeArgSplit(Outs, ArgLocs, I, PartVT, NumParts))
2491 SlotVT = EVT::getIntegerVT(Ctx, PartVT.getSizeInBits() * NumParts);
2492 else
2493 SlotVT = Outs[I].VT;
2494 SDValue SpillSlot = DAG.CreateStackTemporary(SlotVT);
2495 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2496
2497 MachinePointerInfo StackPtrInfo =
2499 MemOpChains.push_back(
2500 DAG.getStore(Chain, DL, ArgValue, SpillSlot, StackPtrInfo));
2501 // If the original argument was split (e.g. i128), we need
2502 // to store all parts of it here (and pass just one address).
2503 assert(Outs[I].PartOffset == 0);
2504 for (unsigned PartIdx = 1; PartIdx < NumParts; ++PartIdx) {
2505 ++I;
2506 SDValue PartValue = OutVals[I];
2507 unsigned PartOffset = Outs[I].PartOffset;
2508 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
2509 DAG.getIntPtrConstant(PartOffset, DL));
2510 MemOpChains.push_back(
2511 DAG.getStore(Chain, DL, PartValue, Address,
2512 StackPtrInfo.getWithOffset(PartOffset)));
2513 assert(PartOffset && "Offset should be non-zero.");
2514 assert((PartOffset + PartValue.getValueType().getStoreSize() <=
2515 SlotVT.getStoreSize()) && "Not enough space for argument part!");
2516 }
2517 ArgValue = SpillSlot;
2518 } else
2519 ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
2520
2521 if (VA.isRegLoc()) {
2522 // In XPLINK64, for the 128-bit vararg case, ArgValue is bitcasted to a
2523 // MVT::i128 type. We decompose the 128-bit type to a pair of its high
2524 // and low values.
2525 if (VA.getLocVT() == MVT::i128)
2526 ArgValue = lowerI128ToGR128(DAG, ArgValue);
2527 // Queue up the argument copies and emit them at the end.
2528 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
2529 } else {
2530 assert(VA.isMemLoc() && "Argument not register or memory");
2531
2532 // Work out the address of the stack slot. Unpromoted ints and
2533 // floats are passed as right-justified 8-byte values.
2534 if (!StackPtr.getNode())
2535 StackPtr = DAG.getCopyFromReg(Chain, DL,
2536 Regs->getStackPointerRegister(), PtrVT);
2537 unsigned Offset = Regs->getStackPointerBias() + Regs->getCallFrameSize() +
2538 VA.getLocMemOffset();
2539 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
2540 Offset += 4;
2541 else if (VA.getLocVT() == MVT::f16)
2542 Offset += 6;
2543 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
2545
2546 // Emit the store.
2547 MemOpChains.push_back(
2548 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
2549
2550 // Although long doubles or vectors are passed through the stack when
2551 // they are vararg (non-fixed arguments), if a long double or vector
2552 // occupies the third and fourth slot of the argument list GPR3 should
2553 // still shadow the third slot of the argument list.
2554 if (Subtarget.isTargetXPLINK64() && VA.needsCustom()) {
2555 SDValue ShadowArgValue =
2556 DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, ArgValue,
2557 DAG.getIntPtrConstant(1, DL));
2558 RegsToPass.push_back(std::make_pair(SystemZ::R3D, ShadowArgValue));
2559 }
2560 }
2561 }
2562
2563 // Join the stores, which are independent of one another.
2564 if (!MemOpChains.empty())
2565 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2566
2567 // Accept direct calls by converting symbolic call addresses to the
2568 // associated Target* opcodes. Force %r1 to be used for indirect
2569 // tail calls.
2570 SDValue Glue;
2571
2572 if (Subtarget.isTargetXPLINK64()) {
2573 SDValue ADA;
2574 bool IsBRASL = getzOSCalleeAndADA(DAG, Callee, ADA, DL, Chain);
2575 if (!IsBRASL) {
2576 unsigned CalleeReg = static_cast<SystemZXPLINK64Registers *>(Regs)
2577 ->getAddressOfCalleeRegister();
2578 Chain = DAG.getCopyToReg(Chain, DL, CalleeReg, Callee, Glue);
2579 Glue = Chain.getValue(1);
2580 Callee = DAG.getRegister(CalleeReg, Callee.getValueType());
2581 }
2582 RegsToPass.push_back(std::make_pair(
2583 static_cast<SystemZXPLINK64Registers *>(Regs)->getADARegister(), ADA));
2584 } else {
2585 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2586 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
2587 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2588 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2589 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
2590 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2591 } else if (IsTailCall) {
2592 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
2593 Glue = Chain.getValue(1);
2594 Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
2595 }
2596 }
2597
2598 // Build a sequence of copy-to-reg nodes, chained and glued together.
2599 for (const auto &[Reg, N] : RegsToPass) {
2600 Chain = DAG.getCopyToReg(Chain, DL, Reg, N, Glue);
2601 Glue = Chain.getValue(1);
2602 }
2603
2604 // The first call operand is the chain and the second is the target address.
2606 Ops.push_back(Chain);
2607 Ops.push_back(Callee);
2608
2609 // Add argument registers to the end of the list so that they are
2610 // known live into the call.
2611 for (const auto &[Reg, N] : RegsToPass)
2612 Ops.push_back(DAG.getRegister(Reg, N.getValueType()));
2613
2614 // Add a register mask operand representing the call-preserved registers.
2615 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2616 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2617 assert(Mask && "Missing call preserved mask for calling convention");
2618 Ops.push_back(DAG.getRegisterMask(Mask));
2619
2620 // Glue the call to the argument copies, if any.
2621 if (Glue.getNode())
2622 Ops.push_back(Glue);
2623
2624 // Emit the call.
2625 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2626 if (IsTailCall) {
2627 SDValue Ret = DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
2628 DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge);
2629 return Ret;
2630 }
2631 Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
2632 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2633 Glue = Chain.getValue(1);
2634
2635 // Mark the end of the call, which is glued to the call itself.
2636 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, Glue, DL);
2637 Glue = Chain.getValue(1);
2638
2639 // Assign locations to each value returned by this call.
2641 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, Ctx);
2642 RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
2643
2644 // Copy all of the result registers out of their specified physreg.
2645 for (CCValAssign &VA : RetLocs) {
2646 // Copy the value out, gluing the copy to the end of the call sequence.
2647 SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
2648 VA.getLocVT(), Glue);
2649 Chain = RetValue.getValue(1);
2650 Glue = RetValue.getValue(2);
2651
2652 // Convert the value of the return register into the value that's
2653 // being returned.
2654 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
2655 }
2656
2657 return Chain;
2658}
2659
2660// Generate a call taking the given operands as arguments and returning a
2661// result of type RetVT.
2663 SDValue Chain, SelectionDAG &DAG, const char *CalleeName, EVT RetVT,
2664 ArrayRef<SDValue> Ops, CallingConv::ID CallConv, bool IsSigned, SDLoc DL,
2665 bool DoesNotReturn, bool IsReturnValueUsed) const {
2667 Args.reserve(Ops.size());
2668
2669 for (SDValue Op : Ops) {
2671 Op, Op.getValueType().getTypeForEVT(*DAG.getContext()));
2672 Entry.IsSExt = shouldSignExtendTypeInLibCall(Entry.Ty, IsSigned);
2673 Entry.IsZExt = !Entry.IsSExt;
2674 Args.push_back(Entry);
2675 }
2676
2677 SDValue Callee =
2678 DAG.getExternalSymbol(CalleeName, getPointerTy(DAG.getDataLayout()));
2679
2680 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2682 bool SignExtend = shouldSignExtendTypeInLibCall(RetTy, IsSigned);
2683 CLI.setDebugLoc(DL)
2684 .setChain(Chain)
2685 .setCallee(CallConv, RetTy, Callee, std::move(Args))
2686 .setNoReturn(DoesNotReturn)
2687 .setDiscardResult(!IsReturnValueUsed)
2688 .setSExtResult(SignExtend)
2689 .setZExtResult(!SignExtend);
2690 return LowerCallTo(CLI);
2691}
2692
2694 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
2695 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context,
2696 const Type *RetTy) const {
2697 // Special case that we cannot easily detect in RetCC_SystemZ since
2698 // i128 may not be a legal type.
2699 for (auto &Out : Outs)
2700 if (Out.ArgVT.isScalarInteger() && Out.ArgVT.getSizeInBits() > 64)
2701 return false;
2702
2704 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, Context);
2705 return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ);
2706}
2707
2708SDValue
2710 bool IsVarArg,
2712 const SmallVectorImpl<SDValue> &OutVals,
2713 const SDLoc &DL, SelectionDAG &DAG) const {
2715
2716 // Integer args <=32 bits should have an extension attribute.
2717 verifyNarrowIntegerArgs_Ret(CallConv, Outs, &MF.getFunction());
2718
2719 // Assign locations to each returned value.
2721 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
2722 RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
2723
2724 // Quick exit for void returns
2725 if (RetLocs.empty())
2726 return DAG.getNode(SystemZISD::RET_GLUE, DL, MVT::Other, Chain);
2727
2728 if (CallConv == CallingConv::GHC)
2729 report_fatal_error("GHC functions return void only");
2730
2731 // Copy the result values into the output registers.
2732 SDValue Glue;
2734 RetOps.push_back(Chain);
2735 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
2736 CCValAssign &VA = RetLocs[I];
2737 SDValue RetValue = OutVals[I];
2738
2739 // Make the return register live on exit.
2740 assert(VA.isRegLoc() && "Can only return in registers!");
2741
2742 // Promote the value as required.
2743 RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
2744
2745 // Chain and glue the copies together.
2746 Register Reg = VA.getLocReg();
2747 Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
2748 Glue = Chain.getValue(1);
2749 RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
2750 }
2751
2752 // Update chain and glue.
2753 RetOps[0] = Chain;
2754 if (Glue.getNode())
2755 RetOps.push_back(Glue);
2756
2757 return DAG.getNode(SystemZISD::RET_GLUE, DL, MVT::Other, RetOps);
2758}
2759
2760// Return true if Op is an intrinsic node with chain that returns the CC value
2761// as its only (other) argument. Provide the associated SystemZISD opcode and
2762// the mask of valid CC values if so.
2763static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
2764 unsigned &CCValid) {
2765 unsigned Id = Op.getConstantOperandVal(1);
2766 switch (Id) {
2767 case Intrinsic::s390_tbegin:
2768 Opcode = SystemZISD::TBEGIN;
2769 CCValid = SystemZ::CCMASK_TBEGIN;
2770 return true;
2771
2772 case Intrinsic::s390_tbegin_nofloat:
2773 Opcode = SystemZISD::TBEGIN_NOFLOAT;
2774 CCValid = SystemZ::CCMASK_TBEGIN;
2775 return true;
2776
2777 case Intrinsic::s390_tend:
2778 Opcode = SystemZISD::TEND;
2779 CCValid = SystemZ::CCMASK_TEND;
2780 return true;
2781
2782 default:
2783 return false;
2784 }
2785}
2786
2787// Return true if Op is an intrinsic node without chain that returns the
2788// CC value as its final argument. Provide the associated SystemZISD
2789// opcode and the mask of valid CC values if so.
2790static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) {
2791 unsigned Id = Op.getConstantOperandVal(0);
2792 switch (Id) {
2793 case Intrinsic::s390_vpkshs:
2794 case Intrinsic::s390_vpksfs:
2795 case Intrinsic::s390_vpksgs:
2796 Opcode = SystemZISD::PACKS_CC;
2797 CCValid = SystemZ::CCMASK_VCMP;
2798 return true;
2799
2800 case Intrinsic::s390_vpklshs:
2801 case Intrinsic::s390_vpklsfs:
2802 case Intrinsic::s390_vpklsgs:
2803 Opcode = SystemZISD::PACKLS_CC;
2804 CCValid = SystemZ::CCMASK_VCMP;
2805 return true;
2806
2807 case Intrinsic::s390_vceqbs:
2808 case Intrinsic::s390_vceqhs:
2809 case Intrinsic::s390_vceqfs:
2810 case Intrinsic::s390_vceqgs:
2811 case Intrinsic::s390_vceqqs:
2812 Opcode = SystemZISD::VICMPES;
2813 CCValid = SystemZ::CCMASK_VCMP;
2814 return true;
2815
2816 case Intrinsic::s390_vchbs:
2817 case Intrinsic::s390_vchhs:
2818 case Intrinsic::s390_vchfs:
2819 case Intrinsic::s390_vchgs:
2820 case Intrinsic::s390_vchqs:
2821 Opcode = SystemZISD::VICMPHS;
2822 CCValid = SystemZ::CCMASK_VCMP;
2823 return true;
2824
2825 case Intrinsic::s390_vchlbs:
2826 case Intrinsic::s390_vchlhs:
2827 case Intrinsic::s390_vchlfs:
2828 case Intrinsic::s390_vchlgs:
2829 case Intrinsic::s390_vchlqs:
2830 Opcode = SystemZISD::VICMPHLS;
2831 CCValid = SystemZ::CCMASK_VCMP;
2832 return true;
2833
2834 case Intrinsic::s390_vtm:
2835 Opcode = SystemZISD::VTM;
2836 CCValid = SystemZ::CCMASK_VCMP;
2837 return true;
2838
2839 case Intrinsic::s390_vfaebs:
2840 case Intrinsic::s390_vfaehs:
2841 case Intrinsic::s390_vfaefs:
2842 Opcode = SystemZISD::VFAE_CC;
2843 CCValid = SystemZ::CCMASK_ANY;
2844 return true;
2845
2846 case Intrinsic::s390_vfaezbs:
2847 case Intrinsic::s390_vfaezhs:
2848 case Intrinsic::s390_vfaezfs:
2849 Opcode = SystemZISD::VFAEZ_CC;
2850 CCValid = SystemZ::CCMASK_ANY;
2851 return true;
2852
2853 case Intrinsic::s390_vfeebs:
2854 case Intrinsic::s390_vfeehs:
2855 case Intrinsic::s390_vfeefs:
2856 Opcode = SystemZISD::VFEE_CC;
2857 CCValid = SystemZ::CCMASK_ANY;
2858 return true;
2859
2860 case Intrinsic::s390_vfeezbs:
2861 case Intrinsic::s390_vfeezhs:
2862 case Intrinsic::s390_vfeezfs:
2863 Opcode = SystemZISD::VFEEZ_CC;
2864 CCValid = SystemZ::CCMASK_ANY;
2865 return true;
2866
2867 case Intrinsic::s390_vfenebs:
2868 case Intrinsic::s390_vfenehs:
2869 case Intrinsic::s390_vfenefs:
2870 Opcode = SystemZISD::VFENE_CC;
2871 CCValid = SystemZ::CCMASK_ANY;
2872 return true;
2873
2874 case Intrinsic::s390_vfenezbs:
2875 case Intrinsic::s390_vfenezhs:
2876 case Intrinsic::s390_vfenezfs:
2877 Opcode = SystemZISD::VFENEZ_CC;
2878 CCValid = SystemZ::CCMASK_ANY;
2879 return true;
2880
2881 case Intrinsic::s390_vistrbs:
2882 case Intrinsic::s390_vistrhs:
2883 case Intrinsic::s390_vistrfs:
2884 Opcode = SystemZISD::VISTR_CC;
2886 return true;
2887
2888 case Intrinsic::s390_vstrcbs:
2889 case Intrinsic::s390_vstrchs:
2890 case Intrinsic::s390_vstrcfs:
2891 Opcode = SystemZISD::VSTRC_CC;
2892 CCValid = SystemZ::CCMASK_ANY;
2893 return true;
2894
2895 case Intrinsic::s390_vstrczbs:
2896 case Intrinsic::s390_vstrczhs:
2897 case Intrinsic::s390_vstrczfs:
2898 Opcode = SystemZISD::VSTRCZ_CC;
2899 CCValid = SystemZ::CCMASK_ANY;
2900 return true;
2901
2902 case Intrinsic::s390_vstrsb:
2903 case Intrinsic::s390_vstrsh:
2904 case Intrinsic::s390_vstrsf:
2905 Opcode = SystemZISD::VSTRS_CC;
2906 CCValid = SystemZ::CCMASK_ANY;
2907 return true;
2908
2909 case Intrinsic::s390_vstrszb:
2910 case Intrinsic::s390_vstrszh:
2911 case Intrinsic::s390_vstrszf:
2912 Opcode = SystemZISD::VSTRSZ_CC;
2913 CCValid = SystemZ::CCMASK_ANY;
2914 return true;
2915
2916 case Intrinsic::s390_vfcedbs:
2917 case Intrinsic::s390_vfcesbs:
2918 Opcode = SystemZISD::VFCMPES;
2919 CCValid = SystemZ::CCMASK_VCMP;
2920 return true;
2921
2922 case Intrinsic::s390_vfchdbs:
2923 case Intrinsic::s390_vfchsbs:
2924 Opcode = SystemZISD::VFCMPHS;
2925 CCValid = SystemZ::CCMASK_VCMP;
2926 return true;
2927
2928 case Intrinsic::s390_vfchedbs:
2929 case Intrinsic::s390_vfchesbs:
2930 Opcode = SystemZISD::VFCMPHES;
2931 CCValid = SystemZ::CCMASK_VCMP;
2932 return true;
2933
2934 case Intrinsic::s390_vftcidb:
2935 case Intrinsic::s390_vftcisb:
2936 Opcode = SystemZISD::VFTCI;
2937 CCValid = SystemZ::CCMASK_VCMP;
2938 return true;
2939
2940 case Intrinsic::s390_tdc:
2941 Opcode = SystemZISD::TDC;
2942 CCValid = SystemZ::CCMASK_TDC;
2943 return true;
2944
2945 default:
2946 return false;
2947 }
2948}
2949
2950// Emit an intrinsic with chain and an explicit CC register result.
2952 unsigned Opcode) {
2953 // Copy all operands except the intrinsic ID.
2954 unsigned NumOps = Op.getNumOperands();
2956 Ops.reserve(NumOps - 1);
2957 Ops.push_back(Op.getOperand(0));
2958 for (unsigned I = 2; I < NumOps; ++I)
2959 Ops.push_back(Op.getOperand(I));
2960
2961 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
2962 SDVTList RawVTs = DAG.getVTList(MVT::i32, MVT::Other);
2963 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
2964 SDValue OldChain = SDValue(Op.getNode(), 1);
2965 SDValue NewChain = SDValue(Intr.getNode(), 1);
2966 DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
2967 return Intr.getNode();
2968}
2969
2970// Emit an intrinsic with an explicit CC register result.
2972 unsigned Opcode) {
2973 // Copy all operands except the intrinsic ID.
2974 SDLoc DL(Op);
2975 unsigned NumOps = Op.getNumOperands();
2977 Ops.reserve(NumOps - 1);
2978 for (unsigned I = 1; I < NumOps; ++I) {
2979 SDValue CurrOper = Op.getOperand(I);
2980 if (CurrOper.getValueType() == MVT::f16) {
2981 assert((Op.getConstantOperandVal(0) == Intrinsic::s390_tdc && I == 1) &&
2982 "Unhandled intrinsic with f16 operand.");
2983 CurrOper = DAG.getFPExtendOrRound(CurrOper, DL, MVT::f32);
2984 }
2985 Ops.push_back(CurrOper);
2986 }
2987
2988 SDValue Intr = DAG.getNode(Opcode, DL, Op->getVTList(), Ops);
2989 return Intr.getNode();
2990}
2991
2992// CC is a comparison that will be implemented using an integer or
2993// floating-point comparison. Return the condition code mask for
2994// a branch on true. In the integer case, CCMASK_CMP_UO is set for
2995// unsigned comparisons and clear for signed ones. In the floating-point
2996// case, CCMASK_CMP_UO has its normal mask meaning (unordered).
2998#define CONV(X) \
2999 case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
3000 case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
3001 case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
3002
3003 switch (CC) {
3004 default:
3005 llvm_unreachable("Invalid integer condition!");
3006
3007 CONV(EQ);
3008 CONV(NE);
3009 CONV(GT);
3010 CONV(GE);
3011 CONV(LT);
3012 CONV(LE);
3013
3014 case ISD::SETO: return SystemZ::CCMASK_CMP_O;
3016 }
3017#undef CONV
3018}
3019
3020// If C can be converted to a comparison against zero, adjust the operands
3021// as necessary.
3022static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
3023 if (C.ICmpType == SystemZICMP::UnsignedOnly)
3024 return;
3025
3026 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
3027 if (!ConstOp1 || ConstOp1->getValueSizeInBits(0) > 64)
3028 return;
3029
3030 int64_t Value = ConstOp1->getSExtValue();
3031 if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
3032 (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
3033 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
3034 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
3035 C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
3036 C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
3037 }
3038}
3039
3040// If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
3041// adjust the operands as necessary.
3042static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL,
3043 Comparison &C) {
3044 // For us to make any changes, it must a comparison between a single-use
3045 // load and a constant.
3046 if (!C.Op0.hasOneUse() ||
3047 C.Op0.getOpcode() != ISD::LOAD ||
3048 C.Op1.getOpcode() != ISD::Constant)
3049 return;
3050
3051 // We must have an 8- or 16-bit load.
3052 auto *Load = cast<LoadSDNode>(C.Op0);
3053 unsigned NumBits = Load->getMemoryVT().getSizeInBits();
3054 if ((NumBits != 8 && NumBits != 16) ||
3055 NumBits != Load->getMemoryVT().getStoreSizeInBits())
3056 return;
3057
3058 // The load must be an extending one and the constant must be within the
3059 // range of the unextended value.
3060 auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
3061 if (!ConstOp1 || ConstOp1->getValueSizeInBits(0) > 64)
3062 return;
3063 uint64_t Value = ConstOp1->getZExtValue();
3064 uint64_t Mask = (1 << NumBits) - 1;
3065 if (Load->getExtensionType() == ISD::SEXTLOAD) {
3066 // Make sure that ConstOp1 is in range of C.Op0.
3067 int64_t SignedValue = ConstOp1->getSExtValue();
3068 if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
3069 return;
3070 if (C.ICmpType != SystemZICMP::SignedOnly) {
3071 // Unsigned comparison between two sign-extended values is equivalent
3072 // to unsigned comparison between two zero-extended values.
3073 Value &= Mask;
3074 } else if (NumBits == 8) {
3075 // Try to treat the comparison as unsigned, so that we can use CLI.
3076 // Adjust CCMask and Value as necessary.
3077 if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
3078 // Test whether the high bit of the byte is set.
3079 Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
3080 else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
3081 // Test whether the high bit of the byte is clear.
3082 Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
3083 else
3084 // No instruction exists for this combination.
3085 return;
3086 C.ICmpType = SystemZICMP::UnsignedOnly;
3087 }
3088 } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
3089 if (Value > Mask)
3090 return;
3091 // If the constant is in range, we can use any comparison.
3092 C.ICmpType = SystemZICMP::Any;
3093 } else
3094 return;
3095
3096 // Make sure that the first operand is an i32 of the right extension type.
3097 ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
3100 if (C.Op0.getValueType() != MVT::i32 ||
3101 Load->getExtensionType() != ExtType) {
3102 C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32, Load->getChain(),
3103 Load->getBasePtr(), Load->getPointerInfo(),
3104 Load->getMemoryVT(), Load->getAlign(),
3105 Load->getMemOperand()->getFlags());
3106 // Update the chain uses.
3107 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), C.Op0.getValue(1));
3108 }
3109
3110 // Make sure that the second operand is an i32 with the right value.
3111 if (C.Op1.getValueType() != MVT::i32 ||
3112 Value != ConstOp1->getZExtValue())
3113 C.Op1 = DAG.getConstant((uint32_t)Value, DL, MVT::i32);
3114}
3115
3116// Return true if Op is either an unextended load, or a load suitable
3117// for integer register-memory comparisons of type ICmpType.
3118static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
3119 auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
3120 if (Load) {
3121 // There are no instructions to compare a register with a memory byte.
3122 if (Load->getMemoryVT() == MVT::i8)
3123 return false;
3124 // Otherwise decide on extension type.
3125 switch (Load->getExtensionType()) {
3126 case ISD::NON_EXTLOAD:
3127 return true;
3128 case ISD::SEXTLOAD:
3129 return ICmpType != SystemZICMP::UnsignedOnly;
3130 case ISD::ZEXTLOAD:
3131 return ICmpType != SystemZICMP::SignedOnly;
3132 default:
3133 break;
3134 }
3135 }
3136 return false;
3137}
3138
3139// Return true if it is better to swap the operands of C.
3140static bool shouldSwapCmpOperands(const Comparison &C) {
3141 // If one side of the compare is a load of the stackguard reference value,
3142 // then that load should be Op1.
3143 if (C.Op0.isMachineOpcode() &&
3144 (C.Op0.getMachineOpcode() == SystemZ::LOAD_STACK_GUARD))
3145 return true;
3146
3147 // Leave i128 and f128 comparisons alone, since they have no memory forms.
3148 if (C.Op0.getValueType() == MVT::i128)
3149 return false;
3150 if (C.Op0.getValueType() == MVT::f128)
3151 return false;
3152
3153 // Always keep a floating-point constant second, since comparisons with
3154 // zero can use LOAD TEST and comparisons with other constants make a
3155 // natural memory operand.
3156 if (isa<ConstantFPSDNode>(C.Op1))
3157 return false;
3158
3159 // Never swap comparisons with zero since there are many ways to optimize
3160 // those later.
3161 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
3162 if (ConstOp1 && ConstOp1->getZExtValue() == 0)
3163 return false;
3164
3165 // Also keep natural memory operands second if the loaded value is
3166 // only used here. Several comparisons have memory forms.
3167 if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
3168 return false;
3169
3170 // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
3171 // In that case we generally prefer the memory to be second.
3172 if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
3173 // The only exceptions are when the second operand is a constant and
3174 // we can use things like CHHSI.
3175 if (!ConstOp1)
3176 return true;
3177 // The unsigned memory-immediate instructions can handle 16-bit
3178 // unsigned integers.
3179 if (C.ICmpType != SystemZICMP::SignedOnly &&
3180 isUInt<16>(ConstOp1->getZExtValue()))
3181 return false;
3182 // The signed memory-immediate instructions can handle 16-bit
3183 // signed integers.
3184 if (C.ICmpType != SystemZICMP::UnsignedOnly &&
3185 isInt<16>(ConstOp1->getSExtValue()))
3186 return false;
3187 return true;
3188 }
3189
3190 // Try to promote the use of CGFR and CLGFR.
3191 unsigned Opcode0 = C.Op0.getOpcode();
3192 if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
3193 return true;
3194 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
3195 return true;
3196 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::AND &&
3197 C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
3198 C.Op0.getConstantOperandVal(1) == 0xffffffff)
3199 return true;
3200
3201 return false;
3202}
3203
3204// Check whether C tests for equality between X and Y and whether X - Y
3205// or Y - X is also computed. In that case it's better to compare the
3206// result of the subtraction against zero.
3208 Comparison &C) {
3209 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3210 C.CCMask == SystemZ::CCMASK_CMP_NE) {
3211 for (SDNode *N : C.Op0->users()) {
3212 if (N->getOpcode() == ISD::SUB &&
3213 ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
3214 (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
3215 // Disable the nsw and nuw flags: the backend needs to handle
3216 // overflow as well during comparison elimination.
3217 N->dropFlags(SDNodeFlags::NoWrap);
3218 C.Op0 = SDValue(N, 0);
3219 C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
3220 return;
3221 }
3222 }
3223 }
3224}
3225
3226// Check whether C compares a floating-point value with zero and if that
3227// floating-point value is also negated. In this case we can use the
3228// negation to set CC, so avoiding separate LOAD AND TEST and
3229// LOAD (NEGATIVE/COMPLEMENT) instructions.
3230static void adjustForFNeg(Comparison &C) {
3231 // This optimization is invalid for strict comparisons, since FNEG
3232 // does not raise any exceptions.
3233 if (C.Chain)
3234 return;
3235 auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
3236 if (C1 && C1->isZero()) {
3237 for (SDNode *N : C.Op0->users()) {
3238 if (N->getOpcode() == ISD::FNEG) {
3239 C.Op0 = SDValue(N, 0);
3240 C.CCMask = SystemZ::reverseCCMask(C.CCMask);
3241 return;
3242 }
3243 }
3244 }
3245}
3246
3247// Check whether C compares (shl X, 32) with 0 and whether X is
3248// also sign-extended. In that case it is better to test the result
3249// of the sign extension using LTGFR.
3250//
3251// This case is important because InstCombine transforms a comparison
3252// with (sext (trunc X)) into a comparison with (shl X, 32).
3253static void adjustForLTGFR(Comparison &C) {
3254 // Check for a comparison between (shl X, 32) and 0.
3255 if (C.Op0.getOpcode() == ISD::SHL && C.Op0.getValueType() == MVT::i64 &&
3256 C.Op1.getOpcode() == ISD::Constant && C.Op1->getAsZExtVal() == 0) {
3257 auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
3258 if (C1 && C1->getZExtValue() == 32) {
3259 SDValue ShlOp0 = C.Op0.getOperand(0);
3260 // See whether X has any SIGN_EXTEND_INREG uses.
3261 for (SDNode *N : ShlOp0->users()) {
3262 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
3263 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
3264 C.Op0 = SDValue(N, 0);
3265 return;
3266 }
3267 }
3268 }
3269 }
3270}
3271
3272// If C compares the truncation of an extending load, try to compare
3273// the untruncated value instead. This exposes more opportunities to
3274// reuse CC.
3275static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL,
3276 Comparison &C) {
3277 if (C.Op0.getOpcode() == ISD::TRUNCATE &&
3278 C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
3279 C.Op1.getOpcode() == ISD::Constant &&
3280 cast<ConstantSDNode>(C.Op1)->getValueSizeInBits(0) <= 64 &&
3281 C.Op1->getAsZExtVal() == 0) {
3282 auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
3283 if (L->getMemoryVT().getStoreSizeInBits().getFixedValue() <=
3284 C.Op0.getValueSizeInBits().getFixedValue()) {
3285 unsigned Type = L->getExtensionType();
3286 if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
3287 (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
3288 C.Op0 = C.Op0.getOperand(0);
3289 C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
3290 }
3291 }
3292 }
3293}
3294
3295// Adjust if a given Compare is a check of the stack guard against a stack
3296// guard instance on the stack. Specifically, this checks if:
3297// - The operands are a load of the stack guard, and a load from a stack slot
3298// - The original opcode is ICMP
3299// - ICMPType is compatible with unsigned comparison.
3301 Comparison &C) {
3302
3303 // Opcode must be ICMP.
3304 if (C.Opcode != SystemZISD::ICMP)
3305 return;
3306 // ICmpType must be Unsigned or Any.
3307 if (C.ICmpType == SystemZICMP::SignedOnly)
3308 return;
3309 // Op0 must be FrameIndex Load.
3310 if (!(ISD::isNormalLoad(C.Op0.getNode()) &&
3311 dyn_cast<FrameIndexSDNode>(C.Op0.getOperand(1))))
3312 return;
3313 // Op1 must be LOAD_STACK_GUARD.
3314 if (!C.Op1.isMachineOpcode() ||
3315 C.Op1.getMachineOpcode() != SystemZ::LOAD_STACK_GUARD)
3316 return;
3317
3318 // At this point we are sure that this is a proper CMP_STACKGUARD
3319 // case, update the opcode to reflect this.
3320 C.Opcode = SystemZISD::CMP_STACKGUARD;
3321 C.Op1 = SDValue();
3322}
3323
3324// Return true if shift operation N has an in-range constant shift value.
3325// Store it in ShiftVal if so.
3326static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
3327 auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
3328 if (!Shift)
3329 return false;
3330
3331 uint64_t Amount = Shift->getZExtValue();
3332 if (Amount >= N.getValueSizeInBits())
3333 return false;
3334
3335 ShiftVal = Amount;
3336 return true;
3337}
3338
3339// Check whether an AND with Mask is suitable for a TEST UNDER MASK
3340// instruction and whether the CC value is descriptive enough to handle
3341// a comparison of type Opcode between the AND result and CmpVal.
3342// CCMask says which comparison result is being tested and BitSize is
3343// the number of bits in the operands. If TEST UNDER MASK can be used,
3344// return the corresponding CC mask, otherwise return 0.
3345static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
3346 uint64_t Mask, uint64_t CmpVal,
3347 unsigned ICmpType) {
3348 assert(Mask != 0 && "ANDs with zero should have been removed by now");
3349
3350 // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
3351 if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
3352 !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
3353 return 0;
3354
3355 // Work out the masks for the lowest and highest bits.
3357 uint64_t Low = uint64_t(1) << llvm::countr_zero(Mask);
3358
3359 // Signed ordered comparisons are effectively unsigned if the sign
3360 // bit is dropped.
3361 bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
3362
3363 // Check for equality comparisons with 0, or the equivalent.
3364 if (CmpVal == 0) {
3365 if (CCMask == SystemZ::CCMASK_CMP_EQ)
3367 if (CCMask == SystemZ::CCMASK_CMP_NE)
3369 }
3370 if (EffectivelyUnsigned && CmpVal > 0 && CmpVal <= Low) {
3371 if (CCMask == SystemZ::CCMASK_CMP_LT)
3373 if (CCMask == SystemZ::CCMASK_CMP_GE)
3375 }
3376 if (EffectivelyUnsigned && CmpVal < Low) {
3377 if (CCMask == SystemZ::CCMASK_CMP_LE)
3379 if (CCMask == SystemZ::CCMASK_CMP_GT)
3381 }
3382
3383 // Check for equality comparisons with the mask, or the equivalent.
3384 if (CmpVal == Mask) {
3385 if (CCMask == SystemZ::CCMASK_CMP_EQ)
3387 if (CCMask == SystemZ::CCMASK_CMP_NE)
3389 }
3390 if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
3391 if (CCMask == SystemZ::CCMASK_CMP_GT)
3393 if (CCMask == SystemZ::CCMASK_CMP_LE)
3395 }
3396 if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
3397 if (CCMask == SystemZ::CCMASK_CMP_GE)
3399 if (CCMask == SystemZ::CCMASK_CMP_LT)
3401 }
3402
3403 // Check for ordered comparisons with the top bit.
3404 if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
3405 if (CCMask == SystemZ::CCMASK_CMP_LE)
3407 if (CCMask == SystemZ::CCMASK_CMP_GT)
3409 }
3410 if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
3411 if (CCMask == SystemZ::CCMASK_CMP_LT)
3413 if (CCMask == SystemZ::CCMASK_CMP_GE)
3415 }
3416
3417 // If there are just two bits, we can do equality checks for Low and High
3418 // as well.
3419 if (Mask == Low + High) {
3420 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
3422 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
3424 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
3426 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
3428 }
3429
3430 // Looks like we've exhausted our options.
3431 return 0;
3432}
3433
3434// See whether C can be implemented as a TEST UNDER MASK instruction.
3435// Update the arguments with the TM version if so.
3437 Comparison &C) {
3438 // Use VECTOR TEST UNDER MASK for i128 operations.
3439 if (C.Op0.getValueType() == MVT::i128) {
3440 // We can use VTM for EQ/NE comparisons of x & y against 0.
3441 if (C.Op0.getOpcode() == ISD::AND &&
3442 (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3443 C.CCMask == SystemZ::CCMASK_CMP_NE)) {
3444 auto *Mask = dyn_cast<ConstantSDNode>(C.Op1);
3445 if (Mask && Mask->getAPIntValue() == 0) {
3446 C.Opcode = SystemZISD::VTM;
3447 C.Op1 = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, C.Op0.getOperand(1));
3448 C.Op0 = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, C.Op0.getOperand(0));
3449 C.CCValid = SystemZ::CCMASK_VCMP;
3450 if (C.CCMask == SystemZ::CCMASK_CMP_EQ)
3451 C.CCMask = SystemZ::CCMASK_VCMP_ALL;
3452 else
3453 C.CCMask = SystemZ::CCMASK_VCMP_ALL ^ C.CCValid;
3454 }
3455 }
3456 return;
3457 }
3458
3459 // Check that we have a comparison with a constant.
3460 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
3461 if (!ConstOp1)
3462 return;
3463 uint64_t CmpVal = ConstOp1->getZExtValue();
3464
3465 // Check whether the nonconstant input is an AND with a constant mask.
3466 Comparison NewC(C);
3467 uint64_t MaskVal;
3468 ConstantSDNode *Mask = nullptr;
3469 if (C.Op0.getOpcode() == ISD::AND) {
3470 NewC.Op0 = C.Op0.getOperand(0);
3471 NewC.Op1 = C.Op0.getOperand(1);
3472 Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
3473 if (!Mask)
3474 return;
3475 MaskVal = Mask->getZExtValue();
3476 } else {
3477 // There is no instruction to compare with a 64-bit immediate
3478 // so use TMHH instead if possible. We need an unsigned ordered
3479 // comparison with an i64 immediate.
3480 if (NewC.Op0.getValueType() != MVT::i64 ||
3481 NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
3482 NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
3483 NewC.ICmpType == SystemZICMP::SignedOnly)
3484 return;
3485 // Convert LE and GT comparisons into LT and GE.
3486 if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
3487 NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
3488 if (CmpVal == uint64_t(-1))
3489 return;
3490 CmpVal += 1;
3491 NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
3492 }
3493 // If the low N bits of Op1 are zero than the low N bits of Op0 can
3494 // be masked off without changing the result.
3495 MaskVal = -(CmpVal & -CmpVal);
3496 NewC.ICmpType = SystemZICMP::UnsignedOnly;
3497 }
3498 if (!MaskVal)
3499 return;
3500
3501 // Check whether the combination of mask, comparison value and comparison
3502 // type are suitable.
3503 unsigned BitSize = NewC.Op0.getValueSizeInBits();
3504 unsigned NewCCMask, ShiftVal;
3505 if (NewC.ICmpType != SystemZICMP::SignedOnly &&
3506 NewC.Op0.getOpcode() == ISD::SHL &&
3507 isSimpleShift(NewC.Op0, ShiftVal) &&
3508 (MaskVal >> ShiftVal != 0) &&
3509 ((CmpVal >> ShiftVal) << ShiftVal) == CmpVal &&
3510 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
3511 MaskVal >> ShiftVal,
3512 CmpVal >> ShiftVal,
3513 SystemZICMP::Any))) {
3514 NewC.Op0 = NewC.Op0.getOperand(0);
3515 MaskVal >>= ShiftVal;
3516 } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
3517 NewC.Op0.getOpcode() == ISD::SRL &&
3518 isSimpleShift(NewC.Op0, ShiftVal) &&
3519 (MaskVal << ShiftVal != 0) &&
3520 ((CmpVal << ShiftVal) >> ShiftVal) == CmpVal &&
3521 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
3522 MaskVal << ShiftVal,
3523 CmpVal << ShiftVal,
3525 NewC.Op0 = NewC.Op0.getOperand(0);
3526 MaskVal <<= ShiftVal;
3527 } else {
3528 NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
3529 NewC.ICmpType);
3530 if (!NewCCMask)
3531 return;
3532 }
3533
3534 // Go ahead and make the change.
3535 C.Opcode = SystemZISD::TM;
3536 C.Op0 = NewC.Op0;
3537 if (Mask && Mask->getZExtValue() == MaskVal)
3538 C.Op1 = SDValue(Mask, 0);
3539 else
3540 C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
3541 C.CCValid = SystemZ::CCMASK_TM;
3542 C.CCMask = NewCCMask;
3543}
3544
3545// Implement i128 comparison in vector registers.
3546static void adjustICmp128(SelectionDAG &DAG, const SDLoc &DL,
3547 Comparison &C) {
3548 if (C.Opcode != SystemZISD::ICMP)
3549 return;
3550 if (C.Op0.getValueType() != MVT::i128)
3551 return;
3552
3553 // Recognize vector comparison reductions.
3554 if ((C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3555 C.CCMask == SystemZ::CCMASK_CMP_NE) &&
3556 (isNullConstant(C.Op1) || isAllOnesConstant(C.Op1))) {
3557 bool CmpEq = C.CCMask == SystemZ::CCMASK_CMP_EQ;
3558 bool CmpNull = isNullConstant(C.Op1);
3559 SDValue Src = peekThroughBitcasts(C.Op0);
3560 if (Src.hasOneUse() && isBitwiseNot(Src)) {
3561 Src = Src.getOperand(0);
3562 CmpNull = !CmpNull;
3563 }
3564 unsigned Opcode = 0;
3565 if (Src.hasOneUse()) {
3566 switch (Src.getOpcode()) {
3567 case SystemZISD::VICMPE: Opcode = SystemZISD::VICMPES; break;
3568 case SystemZISD::VICMPH: Opcode = SystemZISD::VICMPHS; break;
3569 case SystemZISD::VICMPHL: Opcode = SystemZISD::VICMPHLS; break;
3570 case SystemZISD::VFCMPE: Opcode = SystemZISD::VFCMPES; break;
3571 case SystemZISD::VFCMPH: Opcode = SystemZISD::VFCMPHS; break;
3572 case SystemZISD::VFCMPHE: Opcode = SystemZISD::VFCMPHES; break;
3573 default: break;
3574 }
3575 }
3576 if (Opcode) {
3577 C.Opcode = Opcode;
3578 C.Op0 = Src->getOperand(0);
3579 C.Op1 = Src->getOperand(1);
3580 C.CCValid = SystemZ::CCMASK_VCMP;
3582 if (!CmpEq)
3583 C.CCMask ^= C.CCValid;
3584 return;
3585 }
3586 }
3587
3588 // Everything below here is not useful if we have native i128 compares.
3589 if (DAG.getSubtarget<SystemZSubtarget>().hasVectorEnhancements3())
3590 return;
3591
3592 // (In-)Equality comparisons can be implemented via VCEQGS.
3593 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3594 C.CCMask == SystemZ::CCMASK_CMP_NE) {
3595 C.Opcode = SystemZISD::VICMPES;
3596 C.Op0 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, C.Op0);
3597 C.Op1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, C.Op1);
3598 C.CCValid = SystemZ::CCMASK_VCMP;
3599 if (C.CCMask == SystemZ::CCMASK_CMP_EQ)
3600 C.CCMask = SystemZ::CCMASK_VCMP_ALL;
3601 else
3602 C.CCMask = SystemZ::CCMASK_VCMP_ALL ^ C.CCValid;
3603 return;
3604 }
3605
3606 // Normalize other comparisons to GT.
3607 bool Swap = false, Invert = false;
3608 switch (C.CCMask) {
3609 case SystemZ::CCMASK_CMP_GT: break;
3610 case SystemZ::CCMASK_CMP_LT: Swap = true; break;
3611 case SystemZ::CCMASK_CMP_LE: Invert = true; break;
3612 case SystemZ::CCMASK_CMP_GE: Swap = Invert = true; break;
3613 default: llvm_unreachable("Invalid integer condition!");
3614 }
3615 if (Swap)
3616 std::swap(C.Op0, C.Op1);
3617
3618 if (C.ICmpType == SystemZICMP::UnsignedOnly)
3619 C.Opcode = SystemZISD::UCMP128HI;
3620 else
3621 C.Opcode = SystemZISD::SCMP128HI;
3622 C.CCValid = SystemZ::CCMASK_ANY;
3623 C.CCMask = SystemZ::CCMASK_1;
3624
3625 if (Invert)
3626 C.CCMask ^= C.CCValid;
3627}
3628
3629// See whether the comparison argument contains a redundant AND
3630// and remove it if so. This sometimes happens due to the generic
3631// BRCOND expansion.
3633 Comparison &C) {
3634 if (C.Op0.getOpcode() != ISD::AND)
3635 return;
3636 auto *Mask = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
3637 if (!Mask || Mask->getValueSizeInBits(0) > 64)
3638 return;
3639 KnownBits Known = DAG.computeKnownBits(C.Op0.getOperand(0));
3640 if ((~Known.Zero).getZExtValue() & ~Mask->getZExtValue())
3641 return;
3642
3643 C.Op0 = C.Op0.getOperand(0);
3644}
3645
3646// Return a Comparison that tests the condition-code result of intrinsic
3647// node Call against constant integer CC using comparison code Cond.
3648// Opcode is the opcode of the SystemZISD operation for the intrinsic
3649// and CCValid is the set of possible condition-code results.
3650static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
3651 SDValue Call, unsigned CCValid, uint64_t CC,
3653 Comparison C(Call, SDValue(), SDValue());
3654 C.Opcode = Opcode;
3655 C.CCValid = CCValid;
3656 if (Cond == ISD::SETEQ)
3657 // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
3658 C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
3659 else if (Cond == ISD::SETNE)
3660 // ...and the inverse of that.
3661 C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
3662 else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
3663 // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
3664 // always true for CC>3.
3665 C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1;
3666 else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
3667 // ...and the inverse of that.
3668 C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0;
3669 else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
3670 // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
3671 // always true for CC>3.
3672 C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1;
3673 else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
3674 // ...and the inverse of that.
3675 C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0;
3676 else
3677 llvm_unreachable("Unexpected integer comparison type");
3678 C.CCMask &= CCValid;
3679 return C;
3680}
3681
3682// Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
3683static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
3684 ISD::CondCode Cond, const SDLoc &DL,
3685 SDValue Chain = SDValue(),
3686 bool IsSignaling = false) {
3687 if (CmpOp1.getOpcode() == ISD::Constant) {
3688 assert(!Chain);
3689 unsigned Opcode, CCValid;
3690 if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
3691 CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
3692 isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
3693 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid,
3694 CmpOp1->getAsZExtVal(), Cond);
3695 if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
3696 CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 &&
3697 isIntrinsicWithCC(CmpOp0, Opcode, CCValid))
3698 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid,
3699 CmpOp1->getAsZExtVal(), Cond);
3700 }
3701 Comparison C(CmpOp0, CmpOp1, Chain);
3702 C.CCMask = CCMaskForCondCode(Cond);
3703 if (C.Op0.getValueType().isFloatingPoint()) {
3704 C.CCValid = SystemZ::CCMASK_FCMP;
3705 if (!C.Chain)
3706 C.Opcode = SystemZISD::FCMP;
3707 else if (!IsSignaling)
3708 C.Opcode = SystemZISD::STRICT_FCMP;
3709 else
3710 C.Opcode = SystemZISD::STRICT_FCMPS;
3712 } else {
3713 assert(!C.Chain);
3714 C.CCValid = SystemZ::CCMASK_ICMP;
3715 C.Opcode = SystemZISD::ICMP;
3716 // Choose the type of comparison. Equality and inequality tests can
3717 // use either signed or unsigned comparisons. The choice also doesn't
3718 // matter if both sign bits are known to be clear. In those cases we
3719 // want to give the main isel code the freedom to choose whichever
3720 // form fits best.
3721 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3722 C.CCMask == SystemZ::CCMASK_CMP_NE ||
3723 (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
3724 C.ICmpType = SystemZICMP::Any;
3725 else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
3726 C.ICmpType = SystemZICMP::UnsignedOnly;
3727 else
3728 C.ICmpType = SystemZICMP::SignedOnly;
3729 C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
3730 adjustForRedundantAnd(DAG, DL, C);
3731 adjustZeroCmp(DAG, DL, C);
3732 adjustSubwordCmp(DAG, DL, C);
3733 adjustForSubtraction(DAG, DL, C);
3735 adjustICmpTruncate(DAG, DL, C);
3736 }
3737
3738 if (shouldSwapCmpOperands(C)) {
3739 std::swap(C.Op0, C.Op1);
3740 C.CCMask = SystemZ::reverseCCMask(C.CCMask);
3741 }
3742
3744 adjustICmp128(DAG, DL, C);
3746 return C;
3747}
3748
3749// Emit the comparison instruction described by C.
3750static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
3751 if (!C.Op1.getNode()) {
3752 if (C.Opcode == SystemZISD::CMP_STACKGUARD)
3753 return DAG.getNode(SystemZISD::CMP_STACKGUARD, DL, MVT::i32, C.Op0);
3754 SDNode *Node;
3755 switch (C.Op0.getOpcode()) {
3757 Node = emitIntrinsicWithCCAndChain(DAG, C.Op0, C.Opcode);
3758 return SDValue(Node, 0);
3760 Node = emitIntrinsicWithCC(DAG, C.Op0, C.Opcode);
3761 return SDValue(Node, Node->getNumValues() - 1);
3762 default:
3763 llvm_unreachable("Invalid comparison operands");
3764 }
3765 }
3766 if (C.Opcode == SystemZISD::ICMP)
3767 return DAG.getNode(SystemZISD::ICMP, DL, MVT::i32, C.Op0, C.Op1,
3768 DAG.getTargetConstant(C.ICmpType, DL, MVT::i32));
3769 if (C.Opcode == SystemZISD::TM) {
3770 bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
3772 return DAG.getNode(SystemZISD::TM, DL, MVT::i32, C.Op0, C.Op1,
3773 DAG.getTargetConstant(RegisterOnly, DL, MVT::i32));
3774 }
3775 if (C.Opcode == SystemZISD::VICMPES ||
3776 C.Opcode == SystemZISD::VICMPHS ||
3777 C.Opcode == SystemZISD::VICMPHLS ||
3778 C.Opcode == SystemZISD::VFCMPES ||
3779 C.Opcode == SystemZISD::VFCMPHS ||
3780 C.Opcode == SystemZISD::VFCMPHES) {
3781 EVT IntVT = C.Op0.getValueType().changeVectorElementTypeToInteger();
3782 SDVTList VTs = DAG.getVTList(IntVT, MVT::i32);
3783 SDValue Val = DAG.getNode(C.Opcode, DL, VTs, C.Op0, C.Op1);
3784 return SDValue(Val.getNode(), 1);
3785 }
3786 if (C.Chain) {
3787 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
3788 return DAG.getNode(C.Opcode, DL, VTs, C.Chain, C.Op0, C.Op1);
3789 }
3790 return DAG.getNode(C.Opcode, DL, MVT::i32, C.Op0, C.Op1);
3791}
3792
3793// Implement a 32-bit *MUL_LOHI operation by extending both operands to
3794// 64 bits. Extend is the extension type to use. Store the high part
3795// in Hi and the low part in Lo.
3796static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend,
3797 SDValue Op0, SDValue Op1, SDValue &Hi,
3798 SDValue &Lo) {
3799 Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
3800 Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
3801 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
3802 Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
3803 DAG.getConstant(32, DL, MVT::i64));
3804 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
3805 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
3806}
3807
3808// Lower a binary operation that produces two VT results, one in each
3809// half of a GR128 pair. Op0 and Op1 are the VT operands to the operation,
3810// and Opcode performs the GR128 operation. Store the even register result
3811// in Even and the odd register result in Odd.
3812static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
3813 unsigned Opcode, SDValue Op0, SDValue Op1,
3814 SDValue &Even, SDValue &Odd) {
3815 SDValue Result = DAG.getNode(Opcode, DL, MVT::v2i64, Op0, Op1);
3816 bool Is32Bit = is32Bit(VT);
3817 Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
3818 Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
3819}
3820
3821// Return an i32 value that is 1 if the CC value produced by CCReg is
3822// in the mask CCMask and 0 otherwise. CC is known to have a value
3823// in CCValid, so other values can be ignored.
3824static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue CCReg,
3825 unsigned CCValid, unsigned CCMask) {
3826 SDValue Ops[] = {DAG.getConstant(1, DL, MVT::i32),
3827 DAG.getConstant(0, DL, MVT::i32),
3828 DAG.getTargetConstant(CCValid, DL, MVT::i32),
3829 DAG.getTargetConstant(CCMask, DL, MVT::i32), CCReg};
3830 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, MVT::i32, Ops);
3831}
3832
3833// Return the SystemISD vector comparison operation for CC, or 0 if it cannot
3834// be done directly. Mode is CmpMode::Int for integer comparisons, CmpMode::FP
3835// for regular floating-point comparisons, CmpMode::StrictFP for strict (quiet)
3836// floating-point comparisons, and CmpMode::SignalingFP for strict signaling
3837// floating-point comparisons.
3840 switch (CC) {
3841 case ISD::SETOEQ:
3842 case ISD::SETEQ:
3843 switch (Mode) {
3844 case CmpMode::Int: return SystemZISD::VICMPE;
3845 case CmpMode::FP: return SystemZISD::VFCMPE;
3846 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPE;
3847 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPES;
3848 }
3849 llvm_unreachable("Bad mode");
3850
3851 case ISD::SETOGE:
3852 case ISD::SETGE:
3853 switch (Mode) {
3854 case CmpMode::Int: return 0;
3855 case CmpMode::FP: return SystemZISD::VFCMPHE;
3856 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPHE;
3857 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHES;
3858 }
3859 llvm_unreachable("Bad mode");
3860
3861 case ISD::SETOGT:
3862 case ISD::SETGT:
3863 switch (Mode) {
3864 case CmpMode::Int: return SystemZISD::VICMPH;
3865 case CmpMode::FP: return SystemZISD::VFCMPH;
3866 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPH;
3867 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHS;
3868 }
3869 llvm_unreachable("Bad mode");
3870
3871 case ISD::SETUGT:
3872 switch (Mode) {
3873 case CmpMode::Int: return SystemZISD::VICMPHL;
3874 case CmpMode::FP: return 0;
3875 case CmpMode::StrictFP: return 0;
3876 case CmpMode::SignalingFP: return 0;
3877 }
3878 llvm_unreachable("Bad mode");
3879
3880 default:
3881 return 0;
3882 }
3883}
3884
3885// Return the SystemZISD vector comparison operation for CC or its inverse,
3886// or 0 if neither can be done directly. Indicate in Invert whether the
3887// result is for the inverse of CC. Mode is as above.
3889 bool &Invert) {
3890 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
3891 Invert = false;
3892 return Opcode;
3893 }
3894
3895 CC = ISD::getSetCCInverse(CC, Mode == CmpMode::Int ? MVT::i32 : MVT::f32);
3896 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
3897 Invert = true;
3898 return Opcode;
3899 }
3900
3901 return 0;
3902}
3903
3904// Return a v2f64 that contains the extended form of elements Start and Start+1
3905// of v4f32 value Op. If Chain is nonnull, return the strict form.
3906static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL,
3907 SDValue Op, SDValue Chain) {
3908 int Mask[] = { Start, -1, Start + 1, -1 };
3909 Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
3910 if (Chain) {
3911 SDVTList VTs = DAG.getVTList(MVT::v2f64, MVT::Other);
3912 return DAG.getNode(SystemZISD::STRICT_VEXTEND, DL, VTs, Chain, Op);
3913 }
3914 return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
3915}
3916
3917// Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
3918// producing a result of type VT. If Chain is nonnull, return the strict form.
3919SDValue SystemZTargetLowering::getVectorCmp(SelectionDAG &DAG, unsigned Opcode,
3920 const SDLoc &DL, EVT VT,
3921 SDValue CmpOp0,
3922 SDValue CmpOp1,
3923 SDValue Chain) const {
3924 // There is no hardware support for v4f32 (unless we have the vector
3925 // enhancements facility 1), so extend the vector into two v2f64s
3926 // and compare those.
3927 if (CmpOp0.getValueType() == MVT::v4f32 &&
3928 !Subtarget.hasVectorEnhancements1()) {
3929 SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0, Chain);
3930 SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0, Chain);
3931 SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1, Chain);
3932 SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1, Chain);
3933 if (Chain) {
3934 SDVTList VTs = DAG.getVTList(MVT::v2i64, MVT::Other);
3935 SDValue HRes = DAG.getNode(Opcode, DL, VTs, Chain, H0, H1);
3936 SDValue LRes = DAG.getNode(Opcode, DL, VTs, Chain, L0, L1);
3937 SDValue Res = DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
3938 SDValue Chains[6] = { H0.getValue(1), L0.getValue(1),
3939 H1.getValue(1), L1.getValue(1),
3940 HRes.getValue(1), LRes.getValue(1) };
3941 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
3942 SDValue Ops[2] = { Res, NewChain };
3943 return DAG.getMergeValues(Ops, DL);
3944 }
3945 SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
3946 SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
3947 return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
3948 }
3949 if (Chain) {
3950 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3951 return DAG.getNode(Opcode, DL, VTs, Chain, CmpOp0, CmpOp1);
3952 }
3953 return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
3954}
3955
3956// Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
3957// an integer mask of type VT. If Chain is nonnull, we have a strict
3958// floating-point comparison. If in addition IsSignaling is true, we have
3959// a strict signaling floating-point comparison.
3960SDValue SystemZTargetLowering::lowerVectorSETCC(SelectionDAG &DAG,
3961 const SDLoc &DL, EVT VT,
3963 SDValue CmpOp0,
3964 SDValue CmpOp1,
3965 SDValue Chain,
3966 bool IsSignaling) const {
3967 bool IsFP = CmpOp0.getValueType().isFloatingPoint();
3968 assert (!Chain || IsFP);
3969 assert (!IsSignaling || Chain);
3970 CmpMode Mode = IsSignaling ? CmpMode::SignalingFP :
3971 Chain ? CmpMode::StrictFP : IsFP ? CmpMode::FP : CmpMode::Int;
3972 bool Invert = false;
3973 SDValue Cmp;
3974 switch (CC) {
3975 // Handle tests for order using (or (ogt y x) (oge x y)).
3976 case ISD::SETUO:
3977 Invert = true;
3978 [[fallthrough]];
3979 case ISD::SETO: {
3980 assert(IsFP && "Unexpected integer comparison");
3981 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
3982 DL, VT, CmpOp1, CmpOp0, Chain);
3983 SDValue GE = getVectorCmp(DAG, getVectorComparison(ISD::SETOGE, Mode),
3984 DL, VT, CmpOp0, CmpOp1, Chain);
3985 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
3986 if (Chain)
3987 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
3988 LT.getValue(1), GE.getValue(1));
3989 break;
3990 }
3991
3992 // Handle <> tests using (or (ogt y x) (ogt x y)).
3993 case ISD::SETUEQ:
3994 Invert = true;
3995 [[fallthrough]];
3996 case ISD::SETONE: {
3997 assert(IsFP && "Unexpected integer comparison");
3998 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
3999 DL, VT, CmpOp1, CmpOp0, Chain);
4000 SDValue GT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
4001 DL, VT, CmpOp0, CmpOp1, Chain);
4002 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
4003 if (Chain)
4004 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4005 LT.getValue(1), GT.getValue(1));
4006 break;
4007 }
4008
4009 // Otherwise a single comparison is enough. It doesn't really
4010 // matter whether we try the inversion or the swap first, since
4011 // there are no cases where both work.
4012 default:
4013 // Optimize sign-bit comparisons to signed compares.
4014 if (Mode == CmpMode::Int && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
4016 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4017 APInt Mask;
4018 if (CmpOp0.getOpcode() == ISD::AND &&
4019 ISD::isConstantSplatVector(CmpOp0.getOperand(1), Mask) &&
4020 Mask == APInt::getSignMask(EltSize)) {
4022 CmpOp0 = CmpOp0.getOperand(0);
4023 }
4024 }
4025 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
4026 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1, Chain);
4027 else {
4029 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
4030 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0, Chain);
4031 else
4032 llvm_unreachable("Unhandled comparison");
4033 }
4034 if (Chain)
4035 Chain = Cmp.getValue(1);
4036 break;
4037 }
4038 if (Invert) {
4039 SDValue Mask =
4040 DAG.getSplatBuildVector(VT, DL, DAG.getAllOnesConstant(DL, MVT::i64));
4041 Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
4042 }
4043 if (Chain && Chain.getNode() != Cmp.getNode()) {
4044 SDValue Ops[2] = { Cmp, Chain };
4045 Cmp = DAG.getMergeValues(Ops, DL);
4046 }
4047 return Cmp;
4048}
4049
4050SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
4051 SelectionDAG &DAG) const {
4052 SDValue CmpOp0 = Op.getOperand(0);
4053 SDValue CmpOp1 = Op.getOperand(1);
4054 ISD::CondCode CC = Op.getOperandCondCode(2);
4055 SDLoc DL(Op);
4056 EVT VT = Op.getValueType();
4057 if (VT.isVector())
4058 return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
4059
4060 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
4061 SDValue CCReg = emitCmp(DAG, DL, C);
4062 return emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
4063}
4064
4065SDValue SystemZTargetLowering::lowerSTRICT_FSETCC(SDValue Op,
4066 SelectionDAG &DAG,
4067 bool IsSignaling) const {
4068 SDValue Chain = Op.getOperand(0);
4069 SDValue CmpOp0 = Op.getOperand(1);
4070 SDValue CmpOp1 = Op.getOperand(2);
4071 ISD::CondCode CC = Op.getOperandCondCode(3);
4072 SDLoc DL(Op);
4073 EVT VT = Op.getNode()->getValueType(0);
4074 if (VT.isVector()) {
4075 SDValue Res = lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1,
4076 Chain, IsSignaling);
4077 return Res.getValue(Op.getResNo());
4078 }
4079
4080 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL, Chain, IsSignaling));
4081 SDValue CCReg = emitCmp(DAG, DL, C);
4082 CCReg->setFlags(Op->getFlags());
4083 SDValue Result = emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
4084 SDValue Ops[2] = { Result, CCReg.getValue(1) };
4085 return DAG.getMergeValues(Ops, DL);
4086}
4087
4088SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4089 ISD::CondCode CC = Op.getOperandCondCode(1);
4090 SDValue CmpOp0 = Op.getOperand(2);
4091 SDValue CmpOp1 = Op.getOperand(3);
4092 SDValue Dest = Op.getOperand(4);
4093 SDLoc DL(Op);
4094
4095 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
4096 SDValue CCReg = emitCmp(DAG, DL, C);
4097 return DAG.getNode(
4098 SystemZISD::BR_CCMASK, DL, Op.getValueType(), Op.getOperand(0),
4099 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
4100 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), Dest, CCReg);
4101}
4102
4103// Return true if Pos is CmpOp and Neg is the negative of CmpOp,
4104// allowing Pos and Neg to be wider than CmpOp.
4105static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
4106 return (Neg.getOpcode() == ISD::SUB &&
4107 Neg.getOperand(0).getOpcode() == ISD::Constant &&
4108 Neg.getConstantOperandVal(0) == 0 && Neg.getOperand(1) == Pos &&
4109 (Pos == CmpOp || (Pos.getOpcode() == ISD::SIGN_EXTEND &&
4110 Pos.getOperand(0) == CmpOp)));
4111}
4112
4113// Return the absolute or negative absolute of Op; IsNegative decides which.
4115 bool IsNegative) {
4116 Op = DAG.getNode(ISD::ABS, DL, Op.getValueType(), Op);
4117 if (IsNegative)
4118 Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
4119 DAG.getConstant(0, DL, Op.getValueType()), Op);
4120 return Op;
4121}
4122
4124 Comparison C, SDValue TrueOp, SDValue FalseOp) {
4125 EVT VT = MVT::i128;
4126 unsigned Op;
4127
4128 if (C.CCMask == SystemZ::CCMASK_CMP_NE ||
4129 C.CCMask == SystemZ::CCMASK_CMP_GE ||
4130 C.CCMask == SystemZ::CCMASK_CMP_LE) {
4131 std::swap(TrueOp, FalseOp);
4132 C.CCMask ^= C.CCValid;
4133 }
4134 if (C.CCMask == SystemZ::CCMASK_CMP_LT) {
4135 std::swap(C.Op0, C.Op1);
4136 C.CCMask = SystemZ::CCMASK_CMP_GT;
4137 }
4138 switch (C.CCMask) {
4140 Op = SystemZISD::VICMPE;
4141 break;
4143 if (C.ICmpType == SystemZICMP::UnsignedOnly)
4144 Op = SystemZISD::VICMPHL;
4145 else
4146 Op = SystemZISD::VICMPH;
4147 break;
4148 default:
4149 llvm_unreachable("Unhandled comparison");
4150 break;
4151 }
4152
4153 SDValue Mask = DAG.getNode(Op, DL, VT, C.Op0, C.Op1);
4154 TrueOp = DAG.getNode(ISD::AND, DL, VT, TrueOp, Mask);
4155 FalseOp = DAG.getNode(ISD::AND, DL, VT, FalseOp, DAG.getNOT(DL, Mask, VT));
4156 return DAG.getNode(ISD::OR, DL, VT, TrueOp, FalseOp);
4157}
4158
4159SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
4160 SelectionDAG &DAG) const {
4161 SDValue CmpOp0 = Op.getOperand(0);
4162 SDValue CmpOp1 = Op.getOperand(1);
4163 SDValue TrueOp = Op.getOperand(2);
4164 SDValue FalseOp = Op.getOperand(3);
4165 ISD::CondCode CC = Op.getOperandCondCode(4);
4166 SDLoc DL(Op);
4167
4168 // SELECT_CC involving f16 will not have the cmp-ops promoted by the
4169 // legalizer, as it will be handled according to the type of the resulting
4170 // value. Extend them here if needed.
4171 if (CmpOp0.getSimpleValueType() == MVT::f16) {
4172 CmpOp0 = DAG.getFPExtendOrRound(CmpOp0, SDLoc(CmpOp0), MVT::f32);
4173 CmpOp1 = DAG.getFPExtendOrRound(CmpOp1, SDLoc(CmpOp1), MVT::f32);
4174 }
4175
4176 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
4177
4178 // Check for absolute and negative-absolute selections, including those
4179 // where the comparison value is sign-extended (for LPGFR and LNGFR).
4180 // This check supplements the one in DAGCombiner.
4181 if (C.Opcode == SystemZISD::ICMP && C.CCMask != SystemZ::CCMASK_CMP_EQ &&
4182 C.CCMask != SystemZ::CCMASK_CMP_NE &&
4183 C.Op1.getOpcode() == ISD::Constant &&
4184 cast<ConstantSDNode>(C.Op1)->getValueSizeInBits(0) <= 64 &&
4185 C.Op1->getAsZExtVal() == 0) {
4186 if (isAbsolute(C.Op0, TrueOp, FalseOp))
4187 return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
4188 if (isAbsolute(C.Op0, FalseOp, TrueOp))
4189 return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
4190 }
4191
4192 if (Subtarget.hasVectorEnhancements3() &&
4193 C.Opcode == SystemZISD::ICMP &&
4194 C.Op0.getValueType() == MVT::i128 &&
4195 TrueOp.getValueType() == MVT::i128) {
4196 return getI128Select(DAG, DL, C, TrueOp, FalseOp);
4197 }
4198
4199 SDValue CCReg = emitCmp(DAG, DL, C);
4200 SDValue Ops[] = {TrueOp, FalseOp,
4201 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
4202 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), CCReg};
4203
4204 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, Op.getValueType(), Ops);
4205}
4206
4207SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
4208 SelectionDAG &DAG) const {
4209 SDLoc DL(Node);
4210 const GlobalValue *GV = Node->getGlobal();
4211 int64_t Offset = Node->getOffset();
4212 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4214
4216 if (Subtarget.isPC32DBLSymbol(GV, CM)) {
4217 if (isInt<32>(Offset)) {
4218 // Assign anchors at 1<<12 byte boundaries.
4219 uint64_t Anchor = Offset & ~uint64_t(0xfff);
4220 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
4221 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4222
4223 // The offset can be folded into the address if it is aligned to a
4224 // halfword.
4225 Offset -= Anchor;
4226 if (Offset != 0 && (Offset & 1) == 0) {
4227 SDValue Full =
4228 DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
4229 Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
4230 Offset = 0;
4231 }
4232 } else {
4233 // Conservatively load a constant offset greater than 32 bits into a
4234 // register below.
4235 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT);
4236 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4237 }
4238 } else if (Subtarget.isTargetELF()) {
4239 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
4240 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4241 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4243 } else if (Subtarget.isTargetzOS()) {
4244 Result = getADAEntry(DAG, GV, DL, PtrVT);
4245 } else
4246 llvm_unreachable("Unexpected Subtarget");
4247
4248 // If there was a non-zero offset that we didn't fold, create an explicit
4249 // addition for it.
4250 if (Offset != 0)
4251 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
4252 DAG.getSignedConstant(Offset, DL, PtrVT));
4253
4254 return Result;
4255}
4256
4257SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
4258 SelectionDAG &DAG,
4259 unsigned Opcode,
4260 SDValue GOTOffset) const {
4261 SDLoc DL(Node);
4262 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4263 SDValue Chain = DAG.getEntryNode();
4264 SDValue Glue;
4265
4268 report_fatal_error("In GHC calling convention TLS is not supported");
4269
4270 // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
4271 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
4272 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
4273 Glue = Chain.getValue(1);
4274 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
4275 Glue = Chain.getValue(1);
4276
4277 // The first call operand is the chain and the second is the TLS symbol.
4279 Ops.push_back(Chain);
4280 Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
4281 Node->getValueType(0),
4282 0, 0));
4283
4284 // Add argument registers to the end of the list so that they are
4285 // known live into the call.
4286 Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
4287 Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
4288
4289 // Add a register mask operand representing the call-preserved registers.
4290 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4291 const uint32_t *Mask =
4292 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
4293 assert(Mask && "Missing call preserved mask for calling convention");
4294 Ops.push_back(DAG.getRegisterMask(Mask));
4295
4296 // Glue the call to the argument copies.
4297 Ops.push_back(Glue);
4298
4299 // Emit the call.
4300 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4301 Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
4302 Glue = Chain.getValue(1);
4303
4304 // Copy the return value from %r2.
4305 return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
4306}
4307
4308SDValue SystemZTargetLowering::lowerThreadPointer(const SDLoc &DL,
4309 SelectionDAG &DAG) const {
4310 SDValue Chain = DAG.getEntryNode();
4311 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4312
4313 // The high part of the thread pointer is in access register 0.
4314 SDValue TPHi = DAG.getCopyFromReg(Chain, DL, SystemZ::A0, MVT::i32);
4315 TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
4316
4317 // The low part of the thread pointer is in access register 1.
4318 SDValue TPLo = DAG.getCopyFromReg(Chain, DL, SystemZ::A1, MVT::i32);
4319 TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
4320
4321 // Merge them into a single 64-bit address.
4322 SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
4323 DAG.getConstant(32, DL, PtrVT));
4324 return DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
4325}
4326
4327SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
4328 SelectionDAG &DAG) const {
4329 if (DAG.getTarget().useEmulatedTLS())
4330 return LowerToTLSEmulatedModel(Node, DAG);
4331 SDLoc DL(Node);
4332 const GlobalValue *GV = Node->getGlobal();
4333 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4334 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
4335
4338 report_fatal_error("In GHC calling convention TLS is not supported");
4339
4340 SDValue TP = lowerThreadPointer(DL, DAG);
4341
4342 // Get the offset of GA from the thread pointer, based on the TLS model.
4344 switch (model) {
4346 // Load the GOT offset of the tls_index (module ID / per-symbol offset).
4347 SystemZConstantPoolValue *CPV =
4349
4350 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4351 Offset = DAG.getLoad(
4352 PtrVT, DL, DAG.getEntryNode(), Offset,
4354
4355 // Call __tls_get_offset to retrieve the offset.
4356 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
4357 break;
4358 }
4359
4361 // Load the GOT offset of the module ID.
4362 SystemZConstantPoolValue *CPV =
4364
4365 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4366 Offset = DAG.getLoad(
4367 PtrVT, DL, DAG.getEntryNode(), Offset,
4369
4370 // Call __tls_get_offset to retrieve the module base offset.
4371 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
4372
4373 // Note: The SystemZLDCleanupPass will remove redundant computations
4374 // of the module base offset. Count total number of local-dynamic
4375 // accesses to trigger execution of that pass.
4376 SystemZMachineFunctionInfo* MFI =
4377 DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>();
4379
4380 // Add the per-symbol offset.
4382
4383 SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4384 DTPOffset = DAG.getLoad(
4385 PtrVT, DL, DAG.getEntryNode(), DTPOffset,
4387
4388 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
4389 break;
4390 }
4391
4392 case TLSModel::InitialExec: {
4393 // Load the offset from the GOT.
4394 Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
4396 Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
4397 Offset =
4398 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset,
4400 break;
4401 }
4402
4403 case TLSModel::LocalExec: {
4404 // Force the offset into the constant pool and load it from there.
4405 SystemZConstantPoolValue *CPV =
4407
4408 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4409 Offset = DAG.getLoad(
4410 PtrVT, DL, DAG.getEntryNode(), Offset,
4412 break;
4413 }
4414 }
4415
4416 // Add the base and offset together.
4417 return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
4418}
4419
4420SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
4421 SelectionDAG &DAG) const {
4422 SDLoc DL(Node);
4423 const BlockAddress *BA = Node->getBlockAddress();
4424 int64_t Offset = Node->getOffset();
4425 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4426
4427 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
4428 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4429 return Result;
4430}
4431
4432SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
4433 SelectionDAG &DAG) const {
4434 SDLoc DL(JT);
4435 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4436 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
4437
4438 // Use LARL to load the address of the table.
4439 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4440}
4441
4442SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
4443 SelectionDAG &DAG) const {
4444 SDLoc DL(CP);
4445 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4446
4449 Result =
4450 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign());
4451 else
4452 Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign(),
4453 CP->getOffset());
4454
4455 // Use LARL to load the address of the constant pool entry.
4456 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4457}
4458
4459SDValue SystemZTargetLowering::lowerFRAMEADDR(SDValue Op,
4460 SelectionDAG &DAG) const {
4461 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
4463 MachineFrameInfo &MFI = MF.getFrameInfo();
4464 MFI.setFrameAddressIsTaken(true);
4465
4466 SDLoc DL(Op);
4467 unsigned Depth = Op.getConstantOperandVal(0);
4468 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4469
4470 // By definition, the frame address is the address of the back chain. (In
4471 // the case of packed stack without backchain, return the address where the
4472 // backchain would have been stored. This will either be an unused space or
4473 // contain a saved register).
4474 int BackChainIdx = TFL->getOrCreateFramePointerSaveIndex(MF);
4475 SDValue BackChain = DAG.getFrameIndex(BackChainIdx, PtrVT);
4476
4477 if (Depth > 0) {
4478 // FIXME The frontend should detect this case.
4479 if (!MF.getSubtarget<SystemZSubtarget>().hasBackChain())
4480 report_fatal_error("Unsupported stack frame traversal count");
4481
4482 SDValue Offset = DAG.getConstant(TFL->getBackchainOffset(MF), DL, PtrVT);
4483 while (Depth--) {
4484 BackChain = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), BackChain,
4485 MachinePointerInfo());
4486 BackChain = DAG.getNode(ISD::ADD, DL, PtrVT, BackChain, Offset);
4487 }
4488 }
4489
4490 return BackChain;
4491}
4492
4493SDValue SystemZTargetLowering::lowerRETURNADDR(SDValue Op,
4494 SelectionDAG &DAG) const {
4496 MachineFrameInfo &MFI = MF.getFrameInfo();
4497 MFI.setReturnAddressIsTaken(true);
4498
4499 SDLoc DL(Op);
4500 unsigned Depth = Op.getConstantOperandVal(0);
4501 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4502
4503 if (Depth > 0) {
4504 // FIXME The frontend should detect this case.
4505 if (!MF.getSubtarget<SystemZSubtarget>().hasBackChain())
4506 report_fatal_error("Unsupported stack frame traversal count");
4507
4508 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
4509 const auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
4510 int Offset = TFL->getReturnAddressOffset(MF);
4511 SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, FrameAddr,
4512 DAG.getSignedConstant(Offset, DL, PtrVT));
4513 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr,
4514 MachinePointerInfo());
4515 }
4516
4517 // Return R14D (Elf) / R7D (XPLINK), which has the return address. Mark it an
4518 // implicit live-in.
4519 SystemZCallingConventionRegisters *CCR = Subtarget.getSpecialRegisters();
4521 &SystemZ::GR64BitRegClass);
4522 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, LinkReg, PtrVT);
4523}
4524
4525SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
4526 SelectionDAG &DAG) const {
4527 SDLoc DL(Op);
4528 SDValue In = Op.getOperand(0);
4529 EVT InVT = In.getValueType();
4530 EVT ResVT = Op.getValueType();
4531
4532 // Convert loads directly. This is normally done by DAGCombiner,
4533 // but we need this case for bitcasts that are created during lowering
4534 // and which are then lowered themselves.
4535 if (auto *LoadN = dyn_cast<LoadSDNode>(In))
4536 if (ISD::isNormalLoad(LoadN)) {
4537 SDValue NewLoad = DAG.getLoad(ResVT, DL, LoadN->getChain(),
4538 LoadN->getBasePtr(), LoadN->getMemOperand());
4539 // Update the chain uses.
4540 DAG.ReplaceAllUsesOfValueWith(SDValue(LoadN, 1), NewLoad.getValue(1));
4541 return NewLoad;
4542 }
4543
4544 if (InVT == MVT::i32 && ResVT == MVT::f32) {
4545 SDValue In64;
4546 if (Subtarget.hasHighWord()) {
4547 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
4548 MVT::i64);
4549 In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
4550 MVT::i64, SDValue(U64, 0), In);
4551 } else {
4552 In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
4553 In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
4554 DAG.getConstant(32, DL, MVT::i64));
4555 }
4556 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
4557 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32,
4558 DL, MVT::f32, Out64);
4559 }
4560 if (InVT == MVT::f32 && ResVT == MVT::i32) {
4561 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
4562 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
4563 MVT::f64, SDValue(U64, 0), In);
4564 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
4565 if (Subtarget.hasHighWord())
4566 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
4567 MVT::i32, Out64);
4568 SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
4569 DAG.getConstant(32, DL, MVT::i64));
4570 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
4571 }
4572 llvm_unreachable("Unexpected bitcast combination");
4573}
4574
4575SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
4576 SelectionDAG &DAG) const {
4577
4578 if (Subtarget.isTargetXPLINK64())
4579 return lowerVASTART_XPLINK(Op, DAG);
4580 else
4581 return lowerVASTART_ELF(Op, DAG);
4582}
4583
4584SDValue SystemZTargetLowering::lowerVASTART_XPLINK(SDValue Op,
4585 SelectionDAG &DAG) const {
4587 SystemZMachineFunctionInfo *FuncInfo =
4588 MF.getInfo<SystemZMachineFunctionInfo>();
4589
4590 SDLoc DL(Op);
4591
4592 // vastart just stores the address of the VarArgsFrameIndex slot into the
4593 // memory location argument.
4594 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4595 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4596 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4597 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4598 MachinePointerInfo(SV));
4599}
4600
4601SDValue SystemZTargetLowering::lowerVASTART_ELF(SDValue Op,
4602 SelectionDAG &DAG) const {
4604 SystemZMachineFunctionInfo *FuncInfo =
4605 MF.getInfo<SystemZMachineFunctionInfo>();
4606 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4607
4608 SDValue Chain = Op.getOperand(0);
4609 SDValue Addr = Op.getOperand(1);
4610 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4611 SDLoc DL(Op);
4612
4613 // The initial values of each field.
4614 const unsigned NumFields = 4;
4615 SDValue Fields[NumFields] = {
4616 DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
4617 DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
4618 DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
4619 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
4620 };
4621
4622 // Store each field into its respective slot.
4623 SDValue MemOps[NumFields];
4624 unsigned Offset = 0;
4625 for (unsigned I = 0; I < NumFields; ++I) {
4626 SDValue FieldAddr = Addr;
4627 if (Offset != 0)
4628 FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
4630 MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
4631 MachinePointerInfo(SV, Offset));
4632 Offset += 8;
4633 }
4634 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4635}
4636
4637SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
4638 SelectionDAG &DAG) const {
4639 SDValue Chain = Op.getOperand(0);
4640 SDValue DstPtr = Op.getOperand(1);
4641 SDValue SrcPtr = Op.getOperand(2);
4642 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4643 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4644 SDLoc DL(Op);
4645
4646 uint32_t Sz =
4647 Subtarget.isTargetXPLINK64() ? DAG.getDataLayout().getPointerSize(0) : 32;
4648 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(Sz, DL),
4649 Align(8), Align(8), /*isVolatile*/ false,
4650 /*AlwaysInline*/ false,
4651 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(DstSV),
4652 MachinePointerInfo(SrcSV));
4653}
4654
4655SDValue
4656SystemZTargetLowering::lowerDYNAMIC_STACKALLOC(SDValue Op,
4657 SelectionDAG &DAG) const {
4658 if (Subtarget.isTargetXPLINK64())
4659 return lowerDYNAMIC_STACKALLOC_XPLINK(Op, DAG);
4660 else
4661 return lowerDYNAMIC_STACKALLOC_ELF(Op, DAG);
4662}
4663
4664SDValue
4665SystemZTargetLowering::lowerDYNAMIC_STACKALLOC_XPLINK(SDValue Op,
4666 SelectionDAG &DAG) const {
4667 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
4669 bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack");
4670 SDValue Chain = Op.getOperand(0);
4671 SDValue Size = Op.getOperand(1);
4672 SDValue Align = Op.getOperand(2);
4673 SDLoc DL(Op);
4674
4675 // If user has set the no alignment function attribute, ignore
4676 // alloca alignments.
4677 uint64_t AlignVal = (RealignOpt ? Align->getAsZExtVal() : 0);
4678
4679 uint64_t StackAlign = TFI->getStackAlignment();
4680 uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
4681 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
4682
4683 SDValue NeededSpace = Size;
4684
4685 // Add extra space for alignment if needed.
4686 EVT PtrVT = getPointerTy(MF.getDataLayout());
4687 if (ExtraAlignSpace)
4688 NeededSpace = DAG.getNode(ISD::ADD, DL, PtrVT, NeededSpace,
4689 DAG.getConstant(ExtraAlignSpace, DL, PtrVT));
4690
4691 bool IsSigned = false;
4692 bool DoesNotReturn = false;
4693 bool IsReturnValueUsed = false;
4694 EVT VT = Op.getValueType();
4695 SDValue AllocaCall =
4696 makeExternalCall(Chain, DAG, "@@ALCAXP", VT, ArrayRef(NeededSpace),
4697 CallingConv::C, IsSigned, DL, DoesNotReturn,
4698 IsReturnValueUsed)
4699 .first;
4700
4701 // Perform a CopyFromReg from %GPR4 (stack pointer register). Chain and Glue
4702 // to end of call in order to ensure it isn't broken up from the call
4703 // sequence.
4704 auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
4705 Register SPReg = Regs.getStackPointerRegister();
4706 Chain = AllocaCall.getValue(1);
4707 SDValue Glue = AllocaCall.getValue(2);
4708 SDValue NewSPRegNode = DAG.getCopyFromReg(Chain, DL, SPReg, PtrVT, Glue);
4709 Chain = NewSPRegNode.getValue(1);
4710
4711 MVT PtrMVT = getPointerMemTy(MF.getDataLayout());
4712 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, PtrMVT);
4713 SDValue Result = DAG.getNode(ISD::ADD, DL, PtrMVT, NewSPRegNode, ArgAdjust);
4714
4715 // Dynamically realign if needed.
4716 if (ExtraAlignSpace) {
4717 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
4718 DAG.getConstant(ExtraAlignSpace, DL, PtrVT));
4719 Result = DAG.getNode(ISD::AND, DL, PtrVT, Result,
4720 DAG.getConstant(~(RequiredAlign - 1), DL, PtrVT));
4721 }
4722
4723 SDValue Ops[2] = {Result, Chain};
4724 return DAG.getMergeValues(Ops, DL);
4725}
4726
4727SDValue
4728SystemZTargetLowering::lowerDYNAMIC_STACKALLOC_ELF(SDValue Op,
4729 SelectionDAG &DAG) const {
4730 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
4732 bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack");
4733 bool StoreBackchain = MF.getSubtarget<SystemZSubtarget>().hasBackChain();
4734
4735 SDValue Chain = Op.getOperand(0);
4736 SDValue Size = Op.getOperand(1);
4737 SDValue Align = Op.getOperand(2);
4738 SDLoc DL(Op);
4739
4740 // If user has set the no alignment function attribute, ignore
4741 // alloca alignments.
4742 uint64_t AlignVal = (RealignOpt ? Align->getAsZExtVal() : 0);
4743
4744 uint64_t StackAlign = TFI->getStackAlignment();
4745 uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
4746 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
4747
4749 SDValue NeededSpace = Size;
4750
4751 // Get a reference to the stack pointer.
4752 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
4753
4754 // If we need a backchain, save it now.
4755 SDValue Backchain;
4756 if (StoreBackchain)
4757 Backchain = DAG.getLoad(MVT::i64, DL, Chain, getBackchainAddress(OldSP, DAG),
4758 MachinePointerInfo());
4759
4760 // Add extra space for alignment if needed.
4761 if (ExtraAlignSpace)
4762 NeededSpace = DAG.getNode(ISD::ADD, DL, MVT::i64, NeededSpace,
4763 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
4764
4765 // Get the new stack pointer value.
4766 SDValue NewSP;
4767 if (hasInlineStackProbe(MF)) {
4768 NewSP = DAG.getNode(SystemZISD::PROBED_ALLOCA, DL,
4769 DAG.getVTList(MVT::i64, MVT::Other), Chain, OldSP, NeededSpace);
4770 Chain = NewSP.getValue(1);
4771 }
4772 else {
4773 NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, NeededSpace);
4774 // Copy the new stack pointer back.
4775 Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
4776 }
4777
4778 // The allocated data lives above the 160 bytes allocated for the standard
4779 // frame, plus any outgoing stack arguments. We don't know how much that
4780 // amounts to yet, so emit a special ADJDYNALLOC placeholder.
4781 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
4782 SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
4783
4784 // Dynamically realign if needed.
4785 if (RequiredAlign > StackAlign) {
4786 Result =
4787 DAG.getNode(ISD::ADD, DL, MVT::i64, Result,
4788 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
4789 Result =
4790 DAG.getNode(ISD::AND, DL, MVT::i64, Result,
4791 DAG.getConstant(~(RequiredAlign - 1), DL, MVT::i64));
4792 }
4793
4794 if (StoreBackchain)
4795 Chain = DAG.getStore(Chain, DL, Backchain, getBackchainAddress(NewSP, DAG),
4796 MachinePointerInfo());
4797
4798 SDValue Ops[2] = { Result, Chain };
4799 return DAG.getMergeValues(Ops, DL);
4800}
4801
4802SDValue SystemZTargetLowering::lowerGET_DYNAMIC_AREA_OFFSET(
4803 SDValue Op, SelectionDAG &DAG) const {
4804 SDLoc DL(Op);
4805
4806 return DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
4807}
4808
4809SDValue SystemZTargetLowering::lowerMULH(SDValue Op,
4810 SelectionDAG &DAG,
4811 unsigned Opcode) const {
4812 EVT VT = Op.getValueType();
4813 SDLoc DL(Op);
4814 SDValue Even, Odd;
4815
4816 // This custom expander is only used on z17 and later for 64-bit types.
4817 assert(!is32Bit(VT));
4818 assert(Subtarget.hasMiscellaneousExtensions2());
4819
4820 // SystemZISD::xMUL_LOHI returns the low result in the odd register and
4821 // the high result in the even register. Return the latter.
4822 lowerGR128Binary(DAG, DL, VT, Opcode,
4823 Op.getOperand(0), Op.getOperand(1), Even, Odd);
4824 return Even;
4825}
4826
4827SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
4828 SelectionDAG &DAG) const {
4829 EVT VT = Op.getValueType();
4830 SDLoc DL(Op);
4831 SDValue Ops[2];
4832 if (is32Bit(VT))
4833 // Just do a normal 64-bit multiplication and extract the results.
4834 // We define this so that it can be used for constant division.
4835 lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
4836 Op.getOperand(1), Ops[1], Ops[0]);
4837 else if (Subtarget.hasMiscellaneousExtensions2())
4838 // SystemZISD::SMUL_LOHI returns the low result in the odd register and
4839 // the high result in the even register. ISD::SMUL_LOHI is defined to
4840 // return the low half first, so the results are in reverse order.
4841 lowerGR128Binary(DAG, DL, VT, SystemZISD::SMUL_LOHI,
4842 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
4843 else {
4844 // Do a full 128-bit multiplication based on SystemZISD::UMUL_LOHI:
4845 //
4846 // (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
4847 //
4848 // but using the fact that the upper halves are either all zeros
4849 // or all ones:
4850 //
4851 // (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
4852 //
4853 // and grouping the right terms together since they are quicker than the
4854 // multiplication:
4855 //
4856 // (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
4857 SDValue C63 = DAG.getConstant(63, DL, MVT::i64);
4858 SDValue LL = Op.getOperand(0);
4859 SDValue RL = Op.getOperand(1);
4860 SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
4861 SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
4862 // SystemZISD::UMUL_LOHI returns the low result in the odd register and
4863 // the high result in the even register. ISD::SMUL_LOHI is defined to
4864 // return the low half first, so the results are in reverse order.
4865 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
4866 LL, RL, Ops[1], Ops[0]);
4867 SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
4868 SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
4869 SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
4870 Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
4871 }
4872 return DAG.getMergeValues(Ops, DL);
4873}
4874
4875SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
4876 SelectionDAG &DAG) const {
4877 EVT VT = Op.getValueType();
4878 SDLoc DL(Op);
4879 SDValue Ops[2];
4880 if (is32Bit(VT))
4881 // Just do a normal 64-bit multiplication and extract the results.
4882 // We define this so that it can be used for constant division.
4883 lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
4884 Op.getOperand(1), Ops[1], Ops[0]);
4885 else
4886 // SystemZISD::UMUL_LOHI returns the low result in the odd register and
4887 // the high result in the even register. ISD::UMUL_LOHI is defined to
4888 // return the low half first, so the results are in reverse order.
4889 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
4890 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
4891 return DAG.getMergeValues(Ops, DL);
4892}
4893
4894SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
4895 SelectionDAG &DAG) const {
4896 SDValue Op0 = Op.getOperand(0);
4897 SDValue Op1 = Op.getOperand(1);
4898 EVT VT = Op.getValueType();
4899 SDLoc DL(Op);
4900
4901 // We use DSGF for 32-bit division. This means the first operand must
4902 // always be 64-bit, and the second operand should be 32-bit whenever
4903 // that is possible, to improve performance.
4904 if (is32Bit(VT))
4905 Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
4906 else if (DAG.ComputeNumSignBits(Op1) > 32)
4907 Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
4908
4909 // DSG(F) returns the remainder in the even register and the
4910 // quotient in the odd register.
4911 SDValue Ops[2];
4912 lowerGR128Binary(DAG, DL, VT, SystemZISD::SDIVREM, Op0, Op1, Ops[1], Ops[0]);
4913 return DAG.getMergeValues(Ops, DL);
4914}
4915
4916SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
4917 SelectionDAG &DAG) const {
4918 EVT VT = Op.getValueType();
4919 SDLoc DL(Op);
4920
4921 // DL(G) returns the remainder in the even register and the
4922 // quotient in the odd register.
4923 SDValue Ops[2];
4924 lowerGR128Binary(DAG, DL, VT, SystemZISD::UDIVREM,
4925 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
4926 return DAG.getMergeValues(Ops, DL);
4927}
4928
4929SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
4930 assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
4931
4932 // Get the known-zero masks for each operand.
4933 SDValue Ops[] = {Op.getOperand(0), Op.getOperand(1)};
4934 KnownBits Known[2] = {DAG.computeKnownBits(Ops[0]),
4935 DAG.computeKnownBits(Ops[1])};
4936
4937 // See if the upper 32 bits of one operand and the lower 32 bits of the
4938 // other are known zero. They are the low and high operands respectively.
4939 uint64_t Masks[] = { Known[0].Zero.getZExtValue(),
4940 Known[1].Zero.getZExtValue() };
4941 unsigned High, Low;
4942 if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
4943 High = 1, Low = 0;
4944 else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
4945 High = 0, Low = 1;
4946 else
4947 return Op;
4948
4949 SDValue LowOp = Ops[Low];
4950 SDValue HighOp = Ops[High];
4951
4952 // If the high part is a constant, we're better off using IILH.
4953 if (HighOp.getOpcode() == ISD::Constant)
4954 return Op;
4955
4956 // If the low part is a constant that is outside the range of LHI,
4957 // then we're better off using IILF.
4958 if (LowOp.getOpcode() == ISD::Constant) {
4959 int64_t Value = int32_t(LowOp->getAsZExtVal());
4960 if (!isInt<16>(Value))
4961 return Op;
4962 }
4963
4964 // Check whether the high part is an AND that doesn't change the
4965 // high 32 bits and just masks out low bits. We can skip it if so.
4966 if (HighOp.getOpcode() == ISD::AND &&
4967 HighOp.getOperand(1).getOpcode() == ISD::Constant) {
4968 SDValue HighOp0 = HighOp.getOperand(0);
4970 if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
4971 HighOp = HighOp0;
4972 }
4973
4974 // Take advantage of the fact that all GR32 operations only change the
4975 // low 32 bits by truncating Low to an i32 and inserting it directly
4976 // using a subreg. The interesting cases are those where the truncation
4977 // can be folded.
4978 SDLoc DL(Op);
4979 SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
4980 return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
4981 MVT::i64, HighOp, Low32);
4982}
4983
4984// Lower SADDO/SSUBO/UADDO/USUBO nodes.
4985SDValue SystemZTargetLowering::lowerXALUO(SDValue Op,
4986 SelectionDAG &DAG) const {
4987 SDNode *N = Op.getNode();
4988 SDValue LHS = N->getOperand(0);
4989 SDValue RHS = N->getOperand(1);
4990 SDLoc DL(N);
4991
4992 if (N->getValueType(0) == MVT::i128) {
4993 unsigned BaseOp = 0;
4994 unsigned FlagOp = 0;
4995 bool IsBorrow = false;
4996 switch (Op.getOpcode()) {
4997 default: llvm_unreachable("Unknown instruction!");
4998 case ISD::UADDO:
4999 BaseOp = ISD::ADD;
5000 FlagOp = SystemZISD::VACC;
5001 break;
5002 case ISD::USUBO:
5003 BaseOp = ISD::SUB;
5004 FlagOp = SystemZISD::VSCBI;
5005 IsBorrow = true;
5006 break;
5007 }
5008 SDValue Result = DAG.getNode(BaseOp, DL, MVT::i128, LHS, RHS);
5009 SDValue Flag = DAG.getNode(FlagOp, DL, MVT::i128, LHS, RHS);
5010 Flag = DAG.getNode(ISD::AssertZext, DL, MVT::i128, Flag,
5011 DAG.getValueType(MVT::i1));
5012 Flag = DAG.getZExtOrTrunc(Flag, DL, N->getValueType(1));
5013 if (IsBorrow)
5014 Flag = DAG.getNode(ISD::XOR, DL, Flag.getValueType(),
5015 Flag, DAG.getConstant(1, DL, Flag.getValueType()));
5016 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Flag);
5017 }
5018
5019 unsigned BaseOp = 0;
5020 unsigned CCValid = 0;
5021 unsigned CCMask = 0;
5022
5023 switch (Op.getOpcode()) {
5024 default: llvm_unreachable("Unknown instruction!");
5025 case ISD::SADDO:
5026 BaseOp = SystemZISD::SADDO;
5027 CCValid = SystemZ::CCMASK_ARITH;
5029 break;
5030 case ISD::SSUBO:
5031 BaseOp = SystemZISD::SSUBO;
5032 CCValid = SystemZ::CCMASK_ARITH;
5034 break;
5035 case ISD::UADDO:
5036 BaseOp = SystemZISD::UADDO;
5037 CCValid = SystemZ::CCMASK_LOGICAL;
5039 break;
5040 case ISD::USUBO:
5041 BaseOp = SystemZISD::USUBO;
5042 CCValid = SystemZ::CCMASK_LOGICAL;
5044 break;
5045 }
5046
5047 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
5048 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
5049
5050 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
5051 if (N->getValueType(1) == MVT::i1)
5052 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
5053
5054 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
5055}
5056
5057static bool isAddCarryChain(SDValue Carry) {
5058 while (Carry.getOpcode() == ISD::UADDO_CARRY &&
5059 Carry->getValueType(0) != MVT::i128)
5060 Carry = Carry.getOperand(2);
5061 return Carry.getOpcode() == ISD::UADDO &&
5062 Carry->getValueType(0) != MVT::i128;
5063}
5064
5065static bool isSubBorrowChain(SDValue Carry) {
5066 while (Carry.getOpcode() == ISD::USUBO_CARRY &&
5067 Carry->getValueType(0) != MVT::i128)
5068 Carry = Carry.getOperand(2);
5069 return Carry.getOpcode() == ISD::USUBO &&
5070 Carry->getValueType(0) != MVT::i128;
5071}
5072
5073// Lower UADDO_CARRY/USUBO_CARRY nodes.
5074SDValue SystemZTargetLowering::lowerUADDSUBO_CARRY(SDValue Op,
5075 SelectionDAG &DAG) const {
5076
5077 SDNode *N = Op.getNode();
5078 MVT VT = N->getSimpleValueType(0);
5079
5080 // Let legalize expand this if it isn't a legal type yet.
5081 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
5082 return SDValue();
5083
5084 SDValue LHS = N->getOperand(0);
5085 SDValue RHS = N->getOperand(1);
5086 SDValue Carry = Op.getOperand(2);
5087 SDLoc DL(N);
5088
5089 if (VT == MVT::i128) {
5090 unsigned BaseOp = 0;
5091 unsigned FlagOp = 0;
5092 bool IsBorrow = false;
5093 switch (Op.getOpcode()) {
5094 default: llvm_unreachable("Unknown instruction!");
5095 case ISD::UADDO_CARRY:
5096 BaseOp = SystemZISD::VAC;
5097 FlagOp = SystemZISD::VACCC;
5098 break;
5099 case ISD::USUBO_CARRY:
5100 BaseOp = SystemZISD::VSBI;
5101 FlagOp = SystemZISD::VSBCBI;
5102 IsBorrow = true;
5103 break;
5104 }
5105 if (IsBorrow)
5106 Carry = DAG.getNode(ISD::XOR, DL, Carry.getValueType(),
5107 Carry, DAG.getConstant(1, DL, Carry.getValueType()));
5108 Carry = DAG.getZExtOrTrunc(Carry, DL, MVT::i128);
5109 SDValue Result = DAG.getNode(BaseOp, DL, MVT::i128, LHS, RHS, Carry);
5110 SDValue Flag = DAG.getNode(FlagOp, DL, MVT::i128, LHS, RHS, Carry);
5111 Flag = DAG.getNode(ISD::AssertZext, DL, MVT::i128, Flag,
5112 DAG.getValueType(MVT::i1));
5113 Flag = DAG.getZExtOrTrunc(Flag, DL, N->getValueType(1));
5114 if (IsBorrow)
5115 Flag = DAG.getNode(ISD::XOR, DL, Flag.getValueType(),
5116 Flag, DAG.getConstant(1, DL, Flag.getValueType()));
5117 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Flag);
5118 }
5119
5120 unsigned BaseOp = 0;
5121 unsigned CCValid = 0;
5122 unsigned CCMask = 0;
5123
5124 switch (Op.getOpcode()) {
5125 default: llvm_unreachable("Unknown instruction!");
5126 case ISD::UADDO_CARRY:
5127 if (!isAddCarryChain(Carry))
5128 return SDValue();
5129
5130 BaseOp = SystemZISD::ADDCARRY;
5131 CCValid = SystemZ::CCMASK_LOGICAL;
5133 break;
5134 case ISD::USUBO_CARRY:
5135 if (!isSubBorrowChain(Carry))
5136 return SDValue();
5137
5138 BaseOp = SystemZISD::SUBCARRY;
5139 CCValid = SystemZ::CCMASK_LOGICAL;
5141 break;
5142 }
5143
5144 // Set the condition code from the carry flag.
5145 Carry = DAG.getNode(SystemZISD::GET_CCMASK, DL, MVT::i32, Carry,
5146 DAG.getConstant(CCValid, DL, MVT::i32),
5147 DAG.getConstant(CCMask, DL, MVT::i32));
5148
5149 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5150 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS, Carry);
5151
5152 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
5153 if (N->getValueType(1) == MVT::i1)
5154 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
5155
5156 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
5157}
5158
5159SDValue SystemZTargetLowering::lowerPDEP(SDValue Op, SelectionDAG &DAG) const {
5160 SDLoc DL(Op);
5161 assert(Op.getValueType() == MVT::i64 && "Expected i64 PDEP");
5162 SDValue Val = Op.getOperand(0);
5163 SDValue Mask = Op.getOperand(1);
5164
5165 if (auto *MaskC = dyn_cast<ConstantSDNode>(Mask)) {
5166 unsigned PopCount = MaskC->getAPIntValue().popcount();
5167 if (PopCount == 0)
5168 return DAG.getConstant(0, DL, MVT::i64);
5169 if (PopCount == 64)
5170 return Val;
5171 SDValue ShiftedVal =
5172 DAG.getNode(ISD::SHL, DL, MVT::i64, Val,
5173 DAG.getConstant(64 - PopCount, DL, MVT::i64));
5174 return DAG.getNode(
5175 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64,
5176 DAG.getTargetConstant(Intrinsic::s390_bdepg, DL, MVT::i32), ShiftedVal,
5177 Mask);
5178 }
5179
5180 SDValue PopCount = DAG.getNode(ISD::CTPOP, DL, MVT::i64, Mask);
5181 SDValue ShiftAmt = DAG.getNode(ISD::AND, DL, MVT::i64,
5182 DAG.getNegative(PopCount, DL, MVT::i64),
5183 DAG.getConstant(63, DL, MVT::i64));
5184 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, MVT::i64, Val, ShiftAmt);
5185 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64,
5186 DAG.getTargetConstant(Intrinsic::s390_bdepg, DL, MVT::i32),
5187 ShiftedVal, Mask);
5188}
5189
5190SDValue SystemZTargetLowering::lowerPEXT(SDValue Op, SelectionDAG &DAG) const {
5191 SDLoc DL(Op);
5192 assert(Op.getValueType() == MVT::i64 && "Expected i64 PEXT");
5193 SDValue Val = Op.getOperand(0);
5194 SDValue Mask = Op.getOperand(1);
5195
5196 SDValue Bext = DAG.getNode(
5197 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64,
5198 DAG.getTargetConstant(Intrinsic::s390_bextg, DL, MVT::i32), Val, Mask);
5199
5200 if (auto *MaskC = dyn_cast<ConstantSDNode>(Mask)) {
5201 unsigned PopCount = MaskC->getAPIntValue().popcount();
5202 if (PopCount == 0)
5203 return DAG.getConstant(0, DL, MVT::i64);
5204 if (PopCount == 64)
5205 return Val;
5206 return DAG.getNode(ISD::SRL, DL, MVT::i64, Bext,
5207 DAG.getConstant(64 - PopCount, DL, MVT::i64));
5208 }
5209
5210 SDValue PopCount = DAG.getNode(ISD::CTPOP, DL, MVT::i64, Mask);
5211 SDValue ShiftAmt = DAG.getNode(ISD::AND, DL, MVT::i64,
5212 DAG.getNegative(PopCount, DL, MVT::i64),
5213 DAG.getConstant(63, DL, MVT::i64));
5214 return DAG.getNode(ISD::SRL, DL, MVT::i64, Bext, ShiftAmt);
5215}
5216
5217SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op,
5218 SelectionDAG &DAG) const {
5219 EVT VT = Op.getValueType();
5220 SDLoc DL(Op);
5221 Op = Op.getOperand(0);
5222
5223 if (VT.getScalarSizeInBits() == 128) {
5224 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op);
5225 Op = DAG.getNode(ISD::CTPOP, DL, MVT::v2i64, Op);
5226 SDValue Tmp = DAG.getSplatBuildVector(MVT::v2i64, DL,
5227 DAG.getConstant(0, DL, MVT::i64));
5228 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
5229 return Op;
5230 }
5231
5232 // Handle vector types via VPOPCT.
5233 if (VT.isVector()) {
5234 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op);
5235 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op);
5236 switch (VT.getScalarSizeInBits()) {
5237 case 8:
5238 break;
5239 case 16: {
5240 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
5241 SDValue Shift = DAG.getConstant(8, DL, MVT::i32);
5242 SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift);
5243 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
5244 Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift);
5245 break;
5246 }
5247 case 32: {
5248 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
5249 DAG.getConstant(0, DL, MVT::i32));
5250 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
5251 break;
5252 }
5253 case 64: {
5254 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
5255 DAG.getConstant(0, DL, MVT::i32));
5256 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp);
5257 Tmp = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, Tmp);
5258 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
5259 break;
5260 }
5261 default:
5262 llvm_unreachable("Unexpected type");
5263 }
5264 return Op;
5265 }
5266
5267 // Get the known-zero mask for the operand.
5268 KnownBits Known = DAG.computeKnownBits(Op);
5269 unsigned NumSignificantBits = Known.getMaxValue().getActiveBits();
5270 if (NumSignificantBits == 0)
5271 return DAG.getConstant(0, DL, VT);
5272
5273 // Skip known-zero high parts of the operand.
5274 int64_t OrigBitSize = VT.getSizeInBits();
5275 int64_t BitSize = llvm::bit_ceil(NumSignificantBits);
5276 BitSize = std::min(BitSize, OrigBitSize);
5277
5278 // The POPCNT instruction counts the number of bits in each byte.
5279 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op);
5280 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op);
5281 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
5282
5283 // Add up per-byte counts in a binary tree. All bits of Op at
5284 // position larger than BitSize remain zero throughout.
5285 for (int64_t I = BitSize / 2; I >= 8; I = I / 2) {
5286 SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT));
5287 if (BitSize != OrigBitSize)
5288 Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp,
5289 DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT));
5290 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
5291 }
5292
5293 // Extract overall result from high byte.
5294 if (BitSize > 8)
5295 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5296 DAG.getConstant(BitSize - 8, DL, VT));
5297
5298 return Op;
5299}
5300
5301SDValue SystemZTargetLowering::lowerATOMIC_FENCE(SDValue Op,
5302 SelectionDAG &DAG) const {
5303 SDLoc DL(Op);
5304 AtomicOrdering FenceOrdering =
5305 static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
5306 SyncScope::ID FenceSSID =
5307 static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
5308
5309 // The only fence that needs an instruction is a sequentially-consistent
5310 // cross-thread fence.
5311 if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
5312 FenceSSID == SyncScope::System) {
5313 return SDValue(DAG.getMachineNode(SystemZ::Serialize, DL, MVT::Other,
5314 Op.getOperand(0)),
5315 0);
5316 }
5317
5318 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
5319 return DAG.getNode(ISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
5320}
5321
5322SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
5323 SelectionDAG &DAG) const {
5324 EVT RegVT = Op.getValueType();
5325 if (RegVT.getSizeInBits() == 128)
5326 return lowerATOMIC_LDST_I128(Op, DAG);
5327 return lowerLoadF16(Op, DAG);
5328}
5329
5330SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
5331 SelectionDAG &DAG) const {
5332 auto *Node = cast<AtomicSDNode>(Op.getNode());
5333 if (Node->getMemoryVT().getSizeInBits() == 128)
5334 return lowerATOMIC_LDST_I128(Op, DAG);
5335 return lowerStoreF16(Op, DAG);
5336}
5337
5338SDValue SystemZTargetLowering::lowerATOMIC_LDST_I128(SDValue Op,
5339 SelectionDAG &DAG) const {
5340 auto *Node = cast<AtomicSDNode>(Op.getNode());
5341 assert(
5342 (Node->getMemoryVT() == MVT::i128 || Node->getMemoryVT() == MVT::f128) &&
5343 "Only custom lowering i128 or f128.");
5344 // Use same code to handle both legal and non-legal i128 types.
5346 LowerOperationWrapper(Node, Results, DAG);
5347 return DAG.getMergeValues(Results, SDLoc(Op));
5348}
5349
5350// Prepare for a Compare And Swap for a subword operation. This needs to be
5351// done in memory with 4 bytes at natural alignment.
5353 SDValue &AlignedAddr, SDValue &BitShift,
5354 SDValue &NegBitShift) {
5355 EVT PtrVT = Addr.getValueType();
5356 EVT WideVT = MVT::i32;
5357
5358 // Get the address of the containing word.
5359 AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
5360 DAG.getSignedConstant(-4, DL, PtrVT));
5361
5362 // Get the number of bits that the word must be rotated left in order
5363 // to bring the field to the top bits of a GR32.
5364 BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
5365 DAG.getConstant(3, DL, PtrVT));
5366 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
5367
5368 // Get the complementing shift amount, for rotating a field in the top
5369 // bits back to its proper position.
5370 NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
5371 DAG.getConstant(0, DL, WideVT), BitShift);
5372
5373}
5374
5375// N is an 8- or 16-bit ATOMIC_LOAD_* operation. Lower it into the fullword
5376// ATOMIC_LOADW_* operation.
5377void SystemZTargetLowering::lowerATOMIC_LOAD_OP(
5379 unsigned Opcode) const {
5380 auto *Node = cast<AtomicSDNode>(N);
5381
5382 EVT NarrowVT = Node->getMemoryVT();
5383 EVT WideVT = MVT::i32;
5384 int64_t BitSize = NarrowVT.getSizeInBits();
5385 SDValue ChainIn = Node->getChain();
5386 SDValue Addr = Node->getBasePtr();
5387 SDValue Src2 = Node->getVal();
5388 MachineMemOperand *MMO = Node->getMemOperand();
5389 SDLoc DL(Node);
5390
5391 // Convert atomic subtracts of constants into additions.
5392 if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
5393 if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
5394 Opcode = SystemZISD::ATOMIC_LOADW_ADD;
5395 Src2 = DAG.getConstant(-Const->getAPIntValue(), DL, Src2.getValueType());
5396 }
5397
5398 SDValue AlignedAddr, BitShift, NegBitShift;
5399 getCSAddressAndShifts(Addr, DAG, DL, AlignedAddr, BitShift, NegBitShift);
5400
5401 // Extend the source operand to 32 bits and prepare it for the inner loop.
5402 // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
5403 // operations require the source to be shifted in advance. (This shift
5404 // can be folded if the source is constant.) For AND and NAND, the lower
5405 // bits must be set, while for other opcodes they should be left clear.
5406 Src2 = DAG.getNode(ISD::ANY_EXTEND, DL, WideVT, Src2);
5407 if (Opcode != SystemZISD::ATOMIC_SWAPW)
5408 Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
5409 DAG.getConstant(32 - BitSize, DL, WideVT));
5410 if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
5411 Opcode == SystemZISD::ATOMIC_LOADW_NAND)
5412 Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
5413 DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT));
5414
5415 // Construct the ATOMIC_LOADW_* node.
5416 SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
5417 SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
5418 DAG.getConstant(BitSize, DL, WideVT) };
5419 SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
5420 NarrowVT, MMO);
5421
5422 // Rotate the result of the final CS so that the field is in the lower
5423 // bits of a GR32, then truncate it.
5424 SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
5425 DAG.getConstant(BitSize, DL, WideVT));
5426 SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
5427 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, NarrowVT, Result));
5428 Results.push_back(AtomicOp.getValue(1));
5429}
5430
5431// Op is a 32- or 64-bit ATOMIC_LOAD_SUB operation. Convert it into an
5432// addition.
5433SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
5434 SelectionDAG &DAG) const {
5435 auto *Node = cast<AtomicSDNode>(Op.getNode());
5436 EVT MemVT = Node->getMemoryVT();
5437 assert(Op.getValueType() == MemVT && "Mismatched VTs");
5438 assert(Subtarget.hasInterlockedAccess1() &&
5439 "Should have been expanded by AtomicExpand pass.");
5440 SDValue Src2 = Node->getVal();
5441 SDLoc DL(Src2);
5442 SDValue NegSrc2 =
5443 DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT), Src2);
5444 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT, Node->getChain(),
5445 Node->getBasePtr(), NegSrc2, Node->getMemOperand());
5446}
5447
5448// Lower 8/16/32/64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS node.
5449SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
5450 SelectionDAG &DAG) const {
5451 auto *Node = cast<AtomicSDNode>(Op.getNode());
5452 SDValue ChainIn = Node->getOperand(0);
5453 SDValue Addr = Node->getOperand(1);
5454 SDValue CmpVal = Node->getOperand(2);
5455 SDValue SwapVal = Node->getOperand(3);
5456 MachineMemOperand *MMO = Node->getMemOperand();
5457 SDLoc DL(Node);
5458
5459 if (Node->getMemoryVT() == MVT::i128) {
5460 // Use same code to handle both legal and non-legal i128 types.
5462 LowerOperationWrapper(Node, Results, DAG);
5463 return DAG.getMergeValues(Results, DL);
5464 }
5465
5466 // We have native support for 32-bit and 64-bit compare and swap, but we
5467 // still need to expand extracting the "success" result from the CC.
5468 EVT NarrowVT = Node->getMemoryVT();
5469 EVT WideVT = NarrowVT == MVT::i64 ? MVT::i64 : MVT::i32;
5470 if (NarrowVT == WideVT) {
5471 SDVTList Tys = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
5472 SDValue Ops[] = { ChainIn, Addr, CmpVal, SwapVal };
5473 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP,
5474 DL, Tys, Ops, NarrowVT, MMO);
5475 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
5477
5478 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), AtomicOp.getValue(0));
5479 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
5480 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
5481 return SDValue();
5482 }
5483
5484 // Convert 8-bit and 16-bit compare and swap to a loop, implemented
5485 // via a fullword ATOMIC_CMP_SWAPW operation.
5486 int64_t BitSize = NarrowVT.getSizeInBits();
5487
5488 SDValue AlignedAddr, BitShift, NegBitShift;
5489 getCSAddressAndShifts(Addr, DAG, DL, AlignedAddr, BitShift, NegBitShift);
5490
5491 // Construct the ATOMIC_CMP_SWAPW node.
5492 SDVTList VTList = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
5493 SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
5494 NegBitShift, DAG.getConstant(BitSize, DL, WideVT) };
5495 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
5496 VTList, Ops, NarrowVT, MMO);
5497 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
5499
5500 // emitAtomicCmpSwapW() will zero extend the result (original value).
5501 SDValue OrigVal = DAG.getNode(ISD::AssertZext, DL, WideVT, AtomicOp.getValue(0),
5502 DAG.getValueType(NarrowVT));
5503 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), OrigVal);
5504 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
5505 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
5506 return SDValue();
5507}
5508
5510SystemZTargetLowering::getTargetMMOFlags(const Instruction &I) const {
5511 // Because of how we convert atomic_load and atomic_store to normal loads and
5512 // stores in the DAG, we need to ensure that the MMOs are marked volatile
5513 // since DAGCombine hasn't been updated to account for atomic, but non
5514 // volatile loads. (See D57601)
5515 if (auto *SI = dyn_cast<StoreInst>(&I))
5516 if (SI->isAtomic())
5518 if (auto *LI = dyn_cast<LoadInst>(&I))
5519 if (LI->isAtomic())
5521 if (auto *AI = dyn_cast<AtomicRMWInst>(&I))
5522 if (AI->isAtomic())
5524 if (auto *AI = dyn_cast<AtomicCmpXchgInst>(&I))
5525 if (AI->isAtomic())
5528}
5529
5530SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
5531 SelectionDAG &DAG) const {
5533 auto *Regs = Subtarget.getSpecialRegisters();
5535 report_fatal_error("Variable-sized stack allocations are not supported "
5536 "in GHC calling convention");
5537 return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
5538 Regs->getStackPointerRegister(), Op.getValueType());
5539}
5540
5541SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
5542 SelectionDAG &DAG) const {
5544 auto *Regs = Subtarget.getSpecialRegisters();
5545
5547 report_fatal_error("Variable-sized stack allocations are not supported "
5548 "in GHC calling convention");
5549
5550 SDValue Chain = Op.getOperand(0);
5551 SDValue NewSP = Op.getOperand(1);
5552 SDLoc DL(Op);
5553
5554 // XPLINK: @@ALCAXP (lowerDYNAMIC_STACKALLOC_XPLINK) moves the frame header
5555 // (register save area and reserved words at SP + bias) down with the stack
5556 // pointer, and calls made while the stack pointer is lowered place their
5557 // arguments over the old header. The current header must be copied back to
5558 // the restored stack pointer, otherwise the epilogue and the LE stack walk
5559 // use a clobbered header (abend U4083). No signal may be delivered while
5560 // the stack pointer is changed and the header is copied, so this is done in
5561 // a stub routine (emitted once per module by the AsmPrinter), which gets
5562 // the new stack pointer in R1 and is called with BASR 3,3.
5563 if (Subtarget.isTargetXPLINK64()) {
5564 SDValue Glue;
5565 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, NewSP, Glue);
5566 Glue = Chain.getValue(1);
5567 return DAG.getNode(SystemZISD::XPLINK_STACKRESTORE, DL, MVT::Other, Chain,
5568 Glue);
5569 }
5570
5571 bool StoreBackchain = MF.getSubtarget<SystemZSubtarget>().hasBackChain();
5572 SDValue Backchain;
5573 if (StoreBackchain) {
5574 SDValue OldSP = DAG.getCopyFromReg(
5575 Chain, DL, Regs->getStackPointerRegister(), MVT::i64);
5576 Backchain =
5577 DAG.getLoad(MVT::i64, DL, Chain, getBackchainAddress(OldSP, DAG),
5578 MachinePointerInfo());
5579 }
5580
5581 Chain = DAG.getCopyToReg(Chain, DL, Regs->getStackPointerRegister(), NewSP);
5582
5583 if (StoreBackchain)
5584 Chain = DAG.getStore(Chain, DL, Backchain, getBackchainAddress(NewSP, DAG),
5585 MachinePointerInfo());
5586
5587 return Chain;
5588}
5589
5590SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
5591 SelectionDAG &DAG) const {
5592 bool IsData = Op.getConstantOperandVal(4);
5593 if (!IsData)
5594 // Just preserve the chain.
5595 return Op.getOperand(0);
5596
5597 SDLoc DL(Op);
5598 bool IsWrite = Op.getConstantOperandVal(2);
5599 unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
5600 auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
5601 SDValue Ops[] = {Op.getOperand(0), DAG.getTargetConstant(Code, DL, MVT::i32),
5602 Op.getOperand(1)};
5603 return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, DL,
5604 Node->getVTList(), Ops,
5605 Node->getMemoryVT(), Node->getMemOperand());
5606}
5607
5608SDValue
5609SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
5610 SelectionDAG &DAG) const {
5611 unsigned Opcode, CCValid;
5612 if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) {
5613 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
5614 SDNode *Node = emitIntrinsicWithCCAndChain(DAG, Op, Opcode);
5615 SDValue CC = getCCResult(DAG, SDValue(Node, 0));
5616 DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC);
5617 return SDValue();
5618 }
5619
5620 return SDValue();
5621}
5622
5623SDValue
5624SystemZTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
5625 SelectionDAG &DAG) const {
5626 unsigned Opcode, CCValid;
5627 if (isIntrinsicWithCC(Op, Opcode, CCValid)) {
5628 SDNode *Node = emitIntrinsicWithCC(DAG, Op, Opcode);
5629 if (Op->getNumValues() == 1)
5630 return getCCResult(DAG, SDValue(Node, 0));
5631 assert(Op->getNumValues() == 2 && "Expected a CC and non-CC result");
5632 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), Op->getVTList(),
5633 SDValue(Node, 0), getCCResult(DAG, SDValue(Node, 1)));
5634 }
5635
5636 unsigned Id = Op.getConstantOperandVal(0);
5637 switch (Id) {
5638 case Intrinsic::thread_pointer:
5639 return lowerThreadPointer(SDLoc(Op), DAG);
5640
5641 case Intrinsic::s390_vpdi:
5642 return DAG.getNode(SystemZISD::PERMUTE_DWORDS, SDLoc(Op), Op.getValueType(),
5643 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5644
5645 case Intrinsic::s390_vperm:
5646 return DAG.getNode(SystemZISD::PERMUTE, SDLoc(Op), Op.getValueType(),
5647 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5648
5649 case Intrinsic::s390_vuphb:
5650 case Intrinsic::s390_vuphh:
5651 case Intrinsic::s390_vuphf:
5652 case Intrinsic::s390_vuphg:
5653 return DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(Op), Op.getValueType(),
5654 Op.getOperand(1));
5655
5656 case Intrinsic::s390_vuplhb:
5657 case Intrinsic::s390_vuplhh:
5658 case Intrinsic::s390_vuplhf:
5659 case Intrinsic::s390_vuplhg:
5660 return DAG.getNode(SystemZISD::UNPACKL_HIGH, SDLoc(Op), Op.getValueType(),
5661 Op.getOperand(1));
5662
5663 case Intrinsic::s390_vuplb:
5664 case Intrinsic::s390_vuplhw:
5665 case Intrinsic::s390_vuplf:
5666 case Intrinsic::s390_vuplg:
5667 return DAG.getNode(SystemZISD::UNPACK_LOW, SDLoc(Op), Op.getValueType(),
5668 Op.getOperand(1));
5669
5670 case Intrinsic::s390_vupllb:
5671 case Intrinsic::s390_vupllh:
5672 case Intrinsic::s390_vupllf:
5673 case Intrinsic::s390_vupllg:
5674 return DAG.getNode(SystemZISD::UNPACKL_LOW, SDLoc(Op), Op.getValueType(),
5675 Op.getOperand(1));
5676
5677 case Intrinsic::s390_vsumb:
5678 case Intrinsic::s390_vsumh:
5679 case Intrinsic::s390_vsumgh:
5680 case Intrinsic::s390_vsumgf:
5681 case Intrinsic::s390_vsumqf:
5682 case Intrinsic::s390_vsumqg:
5683 return DAG.getNode(SystemZISD::VSUM, SDLoc(Op), Op.getValueType(),
5684 Op.getOperand(1), Op.getOperand(2));
5685
5686 case Intrinsic::s390_vaq:
5687 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5688 Op.getOperand(1), Op.getOperand(2));
5689 case Intrinsic::s390_vaccb:
5690 case Intrinsic::s390_vacch:
5691 case Intrinsic::s390_vaccf:
5692 case Intrinsic::s390_vaccg:
5693 case Intrinsic::s390_vaccq:
5694 return DAG.getNode(SystemZISD::VACC, SDLoc(Op), Op.getValueType(),
5695 Op.getOperand(1), Op.getOperand(2));
5696 case Intrinsic::s390_vacq:
5697 return DAG.getNode(SystemZISD::VAC, SDLoc(Op), Op.getValueType(),
5698 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5699 case Intrinsic::s390_vacccq:
5700 return DAG.getNode(SystemZISD::VACCC, SDLoc(Op), Op.getValueType(),
5701 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5702
5703 case Intrinsic::s390_vsq:
5704 return DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(),
5705 Op.getOperand(1), Op.getOperand(2));
5706 case Intrinsic::s390_vscbib:
5707 case Intrinsic::s390_vscbih:
5708 case Intrinsic::s390_vscbif:
5709 case Intrinsic::s390_vscbig:
5710 case Intrinsic::s390_vscbiq:
5711 return DAG.getNode(SystemZISD::VSCBI, SDLoc(Op), Op.getValueType(),
5712 Op.getOperand(1), Op.getOperand(2));
5713 case Intrinsic::s390_vsbiq:
5714 return DAG.getNode(SystemZISD::VSBI, SDLoc(Op), Op.getValueType(),
5715 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5716 case Intrinsic::s390_vsbcbiq:
5717 return DAG.getNode(SystemZISD::VSBCBI, SDLoc(Op), Op.getValueType(),
5718 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5719
5720 case Intrinsic::s390_vmhb:
5721 case Intrinsic::s390_vmhh:
5722 case Intrinsic::s390_vmhf:
5723 case Intrinsic::s390_vmhg:
5724 case Intrinsic::s390_vmhq:
5725 return DAG.getNode(ISD::MULHS, SDLoc(Op), Op.getValueType(),
5726 Op.getOperand(1), Op.getOperand(2));
5727 case Intrinsic::s390_vmlhb:
5728 case Intrinsic::s390_vmlhh:
5729 case Intrinsic::s390_vmlhf:
5730 case Intrinsic::s390_vmlhg:
5731 case Intrinsic::s390_vmlhq:
5732 return DAG.getNode(ISD::MULHU, SDLoc(Op), Op.getValueType(),
5733 Op.getOperand(1), Op.getOperand(2));
5734
5735 case Intrinsic::s390_vmahb:
5736 case Intrinsic::s390_vmahh:
5737 case Intrinsic::s390_vmahf:
5738 case Intrinsic::s390_vmahg:
5739 case Intrinsic::s390_vmahq:
5740 return DAG.getNode(SystemZISD::VMAH, SDLoc(Op), Op.getValueType(),
5741 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5742 case Intrinsic::s390_vmalhb:
5743 case Intrinsic::s390_vmalhh:
5744 case Intrinsic::s390_vmalhf:
5745 case Intrinsic::s390_vmalhg:
5746 case Intrinsic::s390_vmalhq:
5747 return DAG.getNode(SystemZISD::VMALH, SDLoc(Op), Op.getValueType(),
5748 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5749
5750 case Intrinsic::s390_vmeb:
5751 case Intrinsic::s390_vmeh:
5752 case Intrinsic::s390_vmef:
5753 case Intrinsic::s390_vmeg:
5754 return DAG.getNode(SystemZISD::VME, SDLoc(Op), Op.getValueType(),
5755 Op.getOperand(1), Op.getOperand(2));
5756 case Intrinsic::s390_vmleb:
5757 case Intrinsic::s390_vmleh:
5758 case Intrinsic::s390_vmlef:
5759 case Intrinsic::s390_vmleg:
5760 return DAG.getNode(SystemZISD::VMLE, SDLoc(Op), Op.getValueType(),
5761 Op.getOperand(1), Op.getOperand(2));
5762 case Intrinsic::s390_vmob:
5763 case Intrinsic::s390_vmoh:
5764 case Intrinsic::s390_vmof:
5765 case Intrinsic::s390_vmog:
5766 return DAG.getNode(SystemZISD::VMO, SDLoc(Op), Op.getValueType(),
5767 Op.getOperand(1), Op.getOperand(2));
5768 case Intrinsic::s390_vmlob:
5769 case Intrinsic::s390_vmloh:
5770 case Intrinsic::s390_vmlof:
5771 case Intrinsic::s390_vmlog:
5772 return DAG.getNode(SystemZISD::VMLO, SDLoc(Op), Op.getValueType(),
5773 Op.getOperand(1), Op.getOperand(2));
5774
5775 case Intrinsic::s390_vmaeb:
5776 case Intrinsic::s390_vmaeh:
5777 case Intrinsic::s390_vmaef:
5778 case Intrinsic::s390_vmaeg:
5779 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5780 DAG.getNode(SystemZISD::VME, SDLoc(Op), Op.getValueType(),
5781 Op.getOperand(1), Op.getOperand(2)),
5782 Op.getOperand(3));
5783 case Intrinsic::s390_vmaleb:
5784 case Intrinsic::s390_vmaleh:
5785 case Intrinsic::s390_vmalef:
5786 case Intrinsic::s390_vmaleg:
5787 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5788 DAG.getNode(SystemZISD::VMLE, SDLoc(Op), Op.getValueType(),
5789 Op.getOperand(1), Op.getOperand(2)),
5790 Op.getOperand(3));
5791 case Intrinsic::s390_vmaob:
5792 case Intrinsic::s390_vmaoh:
5793 case Intrinsic::s390_vmaof:
5794 case Intrinsic::s390_vmaog:
5795 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5796 DAG.getNode(SystemZISD::VMO, SDLoc(Op), Op.getValueType(),
5797 Op.getOperand(1), Op.getOperand(2)),
5798 Op.getOperand(3));
5799 case Intrinsic::s390_vmalob:
5800 case Intrinsic::s390_vmaloh:
5801 case Intrinsic::s390_vmalof:
5802 case Intrinsic::s390_vmalog:
5803 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5804 DAG.getNode(SystemZISD::VMLO, SDLoc(Op), Op.getValueType(),
5805 Op.getOperand(1), Op.getOperand(2)),
5806 Op.getOperand(3));
5807 }
5808
5809 return SDValue();
5810}
5811
5812namespace {
5813// Says that SystemZISD operation Opcode can be used to perform the equivalent
5814// of a VPERM with permute vector Bytes. If Opcode takes three operands,
5815// Operand is the constant third operand, otherwise it is the number of
5816// bytes in each element of the result.
5817struct Permute {
5818 unsigned Opcode;
5819 unsigned Operand;
5820 unsigned char Bytes[SystemZ::VectorBytes];
5821};
5822}
5823
5824static const Permute PermuteForms[] = {
5825 // VMRHG
5826 { SystemZISD::MERGE_HIGH, 8,
5827 { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } },
5828 // VMRHF
5829 { SystemZISD::MERGE_HIGH, 4,
5830 { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } },
5831 // VMRHH
5832 { SystemZISD::MERGE_HIGH, 2,
5833 { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } },
5834 // VMRHB
5835 { SystemZISD::MERGE_HIGH, 1,
5836 { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } },
5837 // VMRLG
5838 { SystemZISD::MERGE_LOW, 8,
5839 { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } },
5840 // VMRLF
5841 { SystemZISD::MERGE_LOW, 4,
5842 { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
5843 // VMRLH
5844 { SystemZISD::MERGE_LOW, 2,
5845 { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
5846 // VMRLB
5847 { SystemZISD::MERGE_LOW, 1,
5848 { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
5849 // VPKG
5850 { SystemZISD::PACK, 4,
5851 { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } },
5852 // VPKF
5853 { SystemZISD::PACK, 2,
5854 { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
5855 // VPKH
5856 { SystemZISD::PACK, 1,
5857 { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
5858 // VPDI V1, V2, 4 (low half of V1, high half of V2)
5859 { SystemZISD::PERMUTE_DWORDS, 4,
5860 { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } },
5861 // VPDI V1, V2, 1 (high half of V1, low half of V2)
5862 { SystemZISD::PERMUTE_DWORDS, 1,
5863 { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } }
5864};
5865
5866// Called after matching a vector shuffle against a particular pattern.
5867// Both the original shuffle and the pattern have two vector operands.
5868// OpNos[0] is the operand of the original shuffle that should be used for
5869// operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything.
5870// OpNos[1] is the same for operand 1 of the pattern. Resolve these -1s and
5871// set OpNo0 and OpNo1 to the shuffle operands that should actually be used
5872// for operands 0 and 1 of the pattern.
5873static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) {
5874 if (OpNos[0] < 0) {
5875 if (OpNos[1] < 0)
5876 return false;
5877 OpNo0 = OpNo1 = OpNos[1];
5878 } else if (OpNos[1] < 0) {
5879 OpNo0 = OpNo1 = OpNos[0];
5880 } else {
5881 OpNo0 = OpNos[0];
5882 OpNo1 = OpNos[1];
5883 }
5884 return true;
5885}
5886
5887// Bytes is a VPERM-like permute vector, except that -1 is used for
5888// undefined bytes. Return true if the VPERM can be implemented using P.
5889// When returning true set OpNo0 to the VPERM operand that should be
5890// used for operand 0 of P and likewise OpNo1 for operand 1 of P.
5891//
5892// For example, if swapping the VPERM operands allows P to match, OpNo0
5893// will be 1 and OpNo1 will be 0. If instead Bytes only refers to one
5894// operand, but rewriting it to use two duplicated operands allows it to
5895// match P, then OpNo0 and OpNo1 will be the same.
5896static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P,
5897 unsigned &OpNo0, unsigned &OpNo1) {
5898 int OpNos[] = { -1, -1 };
5899 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
5900 int Elt = Bytes[I];
5901 if (Elt >= 0) {
5902 // Make sure that the two permute vectors use the same suboperand
5903 // byte number. Only the operand numbers (the high bits) are
5904 // allowed to differ.
5905 if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1))
5906 return false;
5907 int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes;
5908 int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes;
5909 // Make sure that the operand mappings are consistent with previous
5910 // elements.
5911 if (OpNos[ModelOpNo] == 1 - RealOpNo)
5912 return false;
5913 OpNos[ModelOpNo] = RealOpNo;
5914 }
5915 }
5916 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
5917}
5918
5919// As above, but search for a matching permute.
5920static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes,
5921 unsigned &OpNo0, unsigned &OpNo1) {
5922 for (auto &P : PermuteForms)
5923 if (matchPermute(Bytes, P, OpNo0, OpNo1))
5924 return &P;
5925 return nullptr;
5926}
5927
5928// Bytes is a VPERM-like permute vector, except that -1 is used for
5929// undefined bytes. This permute is an operand of an outer permute.
5930// See whether redistributing the -1 bytes gives a shuffle that can be
5931// implemented using P. If so, set Transform to a VPERM-like permute vector
5932// that, when applied to the result of P, gives the original permute in Bytes.
5934 const Permute &P,
5935 SmallVectorImpl<int> &Transform) {
5936 unsigned To = 0;
5937 for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) {
5938 int Elt = Bytes[From];
5939 if (Elt < 0)
5940 // Byte number From of the result is undefined.
5941 Transform[From] = -1;
5942 else {
5943 while (P.Bytes[To] != Elt) {
5944 To += 1;
5945 if (To == SystemZ::VectorBytes)
5946 return false;
5947 }
5948 Transform[From] = To;
5949 }
5950 }
5951 return true;
5952}
5953
5954// As above, but search for a matching permute.
5955static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes,
5956 SmallVectorImpl<int> &Transform) {
5957 for (auto &P : PermuteForms)
5958 if (matchDoublePermute(Bytes, P, Transform))
5959 return &P;
5960 return nullptr;
5961}
5962
5963// Convert the mask of the given shuffle op into a byte-level mask,
5964// as if it had type vNi8.
5965static bool getVPermMask(SDValue ShuffleOp,
5966 SmallVectorImpl<int> &Bytes) {
5967 EVT VT = ShuffleOp.getValueType();
5968 unsigned NumElements = VT.getVectorNumElements();
5969 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
5970
5971 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(ShuffleOp)) {
5972 Bytes.resize(NumElements * BytesPerElement, -1);
5973 for (unsigned I = 0; I < NumElements; ++I) {
5974 int Index = VSN->getMaskElt(I);
5975 if (Index >= 0)
5976 for (unsigned J = 0; J < BytesPerElement; ++J)
5977 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
5978 }
5979 return true;
5980 }
5981 if (SystemZISD::SPLAT == ShuffleOp.getOpcode() &&
5982 isa<ConstantSDNode>(ShuffleOp.getOperand(1))) {
5983 unsigned Index = ShuffleOp.getConstantOperandVal(1);
5984 Bytes.resize(NumElements * BytesPerElement, -1);
5985 for (unsigned I = 0; I < NumElements; ++I)
5986 for (unsigned J = 0; J < BytesPerElement; ++J)
5987 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
5988 return true;
5989 }
5990 return false;
5991}
5992
5993// Bytes is a VPERM-like permute vector, except that -1 is used for
5994// undefined bytes. See whether bytes [Start, Start + BytesPerElement) of
5995// the result come from a contiguous sequence of bytes from one input.
5996// Set Base to the selector for the first byte if so.
5997static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start,
5998 unsigned BytesPerElement, int &Base) {
5999 Base = -1;
6000 for (unsigned I = 0; I < BytesPerElement; ++I) {
6001 if (Bytes[Start + I] >= 0) {
6002 unsigned Elem = Bytes[Start + I];
6003 if (Base < 0) {
6004 Base = Elem - I;
6005 // Make sure the bytes would come from one input operand.
6006 if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size())
6007 return false;
6008 } else if (unsigned(Base) != Elem - I)
6009 return false;
6010 }
6011 }
6012 return true;
6013}
6014
6015// Bytes is a VPERM-like permute vector, except that -1 is used for
6016// undefined bytes. Return true if it can be performed using VSLDB.
6017// When returning true, set StartIndex to the shift amount and OpNo0
6018// and OpNo1 to the VPERM operands that should be used as the first
6019// and second shift operand respectively.
6021 unsigned &StartIndex, unsigned &OpNo0,
6022 unsigned &OpNo1) {
6023 int OpNos[] = { -1, -1 };
6024 int Shift = -1;
6025 for (unsigned I = 0; I < 16; ++I) {
6026 int Index = Bytes[I];
6027 if (Index >= 0) {
6028 int ExpectedShift = (Index - I) % SystemZ::VectorBytes;
6029 int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes;
6030 int RealOpNo = unsigned(Index) / SystemZ::VectorBytes;
6031 if (Shift < 0)
6032 Shift = ExpectedShift;
6033 else if (Shift != ExpectedShift)
6034 return false;
6035 // Make sure that the operand mappings are consistent with previous
6036 // elements.
6037 if (OpNos[ModelOpNo] == 1 - RealOpNo)
6038 return false;
6039 OpNos[ModelOpNo] = RealOpNo;
6040 }
6041 }
6042 StartIndex = Shift;
6043 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
6044}
6045
6046// Create a node that performs P on operands Op0 and Op1, casting the
6047// operands to the appropriate type. The type of the result is determined by P.
6049 const Permute &P, SDValue Op0, SDValue Op1) {
6050 // VPDI (PERMUTE_DWORDS) always operates on v2i64s. The input
6051 // elements of a PACK are twice as wide as the outputs.
6052 unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 :
6053 P.Opcode == SystemZISD::PACK ? P.Operand * 2 :
6054 P.Operand);
6055 // Cast both operands to the appropriate type.
6056 MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8),
6057 SystemZ::VectorBytes / InBytes);
6058 Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0);
6059 Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1);
6060 SDValue Op;
6061 if (P.Opcode == SystemZISD::PERMUTE_DWORDS) {
6062 SDValue Op2 = DAG.getTargetConstant(P.Operand, DL, MVT::i32);
6063 Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2);
6064 } else if (P.Opcode == SystemZISD::PACK) {
6065 MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8),
6066 SystemZ::VectorBytes / P.Operand);
6067 Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1);
6068 } else {
6069 Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1);
6070 }
6071 return Op;
6072}
6073
6074static bool isZeroVector(SDValue N) {
6075 if (N->getOpcode() == ISD::BITCAST)
6076 N = N->getOperand(0);
6077 if (N->getOpcode() == ISD::SPLAT_VECTOR)
6078 if (auto *Op = dyn_cast<ConstantSDNode>(N->getOperand(0)))
6079 return Op->getZExtValue() == 0;
6081}
6082
6083// Return the index of the zero/undef vector, or UINT32_MAX if not found.
6084static uint32_t findZeroVectorIdx(SDValue *Ops, unsigned Num) {
6085 for (unsigned I = 0; I < Num ; I++)
6086 if (isZeroVector(Ops[I]))
6087 return I;
6088 return UINT32_MAX;
6089}
6090
6091// Bytes is a VPERM-like permute vector, except that -1 is used for
6092// undefined bytes. Implement it on operands Ops[0] and Ops[1] using
6093// VSLDB or VPERM.
6095 SDValue *Ops,
6096 const SmallVectorImpl<int> &Bytes) {
6097 for (unsigned I = 0; I < 2; ++I)
6098 Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]);
6099
6100 // First see whether VSLDB can be used.
6101 unsigned StartIndex, OpNo0, OpNo1;
6102 if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1))
6103 return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0],
6104 Ops[OpNo1],
6105 DAG.getTargetConstant(StartIndex, DL, MVT::i32));
6106
6107 // Fall back on VPERM. Construct an SDNode for the permute vector. Try to
6108 // eliminate a zero vector by reusing any zero index in the permute vector.
6109 unsigned ZeroVecIdx = findZeroVectorIdx(&Ops[0], 2);
6110 if (ZeroVecIdx != UINT32_MAX) {
6111 bool MaskFirst = true;
6112 int ZeroIdx = -1;
6113 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
6114 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
6115 unsigned Byte = unsigned(Bytes[I]) % SystemZ::VectorBytes;
6116 if (OpNo == ZeroVecIdx && I == 0) {
6117 // If the first byte is zero, use mask as first operand.
6118 ZeroIdx = 0;
6119 break;
6120 }
6121 if (OpNo != ZeroVecIdx && Byte == 0) {
6122 // If mask contains a zero, use it by placing that vector first.
6123 ZeroIdx = I + SystemZ::VectorBytes;
6124 MaskFirst = false;
6125 break;
6126 }
6127 }
6128 if (ZeroIdx != -1) {
6129 SDValue IndexNodes[SystemZ::VectorBytes];
6130 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
6131 if (Bytes[I] >= 0) {
6132 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
6133 unsigned Byte = unsigned(Bytes[I]) % SystemZ::VectorBytes;
6134 if (OpNo == ZeroVecIdx)
6135 IndexNodes[I] = DAG.getConstant(ZeroIdx, DL, MVT::i32);
6136 else {
6137 unsigned BIdx = MaskFirst ? Byte + SystemZ::VectorBytes : Byte;
6138 IndexNodes[I] = DAG.getConstant(BIdx, DL, MVT::i32);
6139 }
6140 } else
6141 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
6142 }
6143 SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
6144 SDValue Src = ZeroVecIdx == 0 ? Ops[1] : Ops[0];
6145 if (MaskFirst)
6146 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Mask, Src,
6147 Mask);
6148 else
6149 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Src, Mask,
6150 Mask);
6151 }
6152 }
6153
6154 SDValue IndexNodes[SystemZ::VectorBytes];
6155 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
6156 if (Bytes[I] >= 0)
6157 IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32);
6158 else
6159 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
6160 SDValue Op2 = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
6161 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0],
6162 (!Ops[1].isUndef() ? Ops[1] : Ops[0]), Op2);
6163}
6164
6165namespace {
6166// Describes a general N-operand vector shuffle.
6167struct GeneralShuffle {
6168 GeneralShuffle(EVT vt)
6169 : VT(vt), UnpackFromEltSize(UINT_MAX), UnpackLow(false) {}
6170 void addUndef();
6171 bool add(SDValue, unsigned);
6172 SDValue getNode(SelectionDAG &, const SDLoc &);
6173 void tryPrepareForUnpack();
6174 bool unpackWasPrepared() { return UnpackFromEltSize <= 4; }
6175 SDValue insertUnpackIfPrepared(SelectionDAG &DAG, const SDLoc &DL, SDValue Op);
6176
6177 // The operands of the shuffle.
6179
6180 // Index I is -1 if byte I of the result is undefined. Otherwise the
6181 // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand
6182 // Bytes[I] / SystemZ::VectorBytes.
6184
6185 // The type of the shuffle result.
6186 EVT VT;
6187
6188 // Holds a value of 1, 2 or 4 if a final unpack has been prepared for.
6189 unsigned UnpackFromEltSize;
6190 // True if the final unpack uses the low half.
6191 bool UnpackLow;
6192};
6193} // namespace
6194
6195// Add an extra undefined element to the shuffle.
6196void GeneralShuffle::addUndef() {
6197 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
6198 for (unsigned I = 0; I < BytesPerElement; ++I)
6199 Bytes.push_back(-1);
6200}
6201
6202// Add an extra element to the shuffle, taking it from element Elem of Op.
6203// A null Op indicates a vector input whose value will be calculated later;
6204// there is at most one such input per shuffle and it always has the same
6205// type as the result. Aborts and returns false if the source vector elements
6206// of an EXTRACT_VECTOR_ELT are smaller than the destination elements. Per
6207// LLVM they become implicitly extended, but this is rare and not optimized.
6208bool GeneralShuffle::add(SDValue Op, unsigned Elem) {
6209 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
6210
6211 // The source vector can have wider elements than the result,
6212 // either through an explicit TRUNCATE or because of type legalization.
6213 // We want the least significant part.
6214 EVT FromVT = Op.getNode() ? Op.getValueType() : VT;
6215 unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize();
6216
6217 // Return false if the source elements are smaller than their destination
6218 // elements.
6219 if (FromBytesPerElement < BytesPerElement)
6220 return false;
6221
6222 unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes +
6223 (FromBytesPerElement - BytesPerElement));
6224
6225 // Look through things like shuffles and bitcasts.
6226 while (Op.getNode()) {
6227 if (Op.getOpcode() == ISD::BITCAST)
6228 Op = Op.getOperand(0);
6229 else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) {
6230 // See whether the bytes we need come from a contiguous part of one
6231 // operand.
6233 if (!getVPermMask(Op, OpBytes))
6234 break;
6235 int NewByte;
6236 if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte))
6237 break;
6238 if (NewByte < 0) {
6239 addUndef();
6240 return true;
6241 }
6242 Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes);
6243 Byte = unsigned(NewByte) % SystemZ::VectorBytes;
6244 } else if (Op.isUndef()) {
6245 addUndef();
6246 return true;
6247 } else
6248 break;
6249 }
6250
6251 // Make sure that the source of the extraction is in Ops.
6252 unsigned OpNo = 0;
6253 for (; OpNo < Ops.size(); ++OpNo)
6254 if (Ops[OpNo] == Op)
6255 break;
6256 if (OpNo == Ops.size())
6257 Ops.push_back(Op);
6258
6259 // Add the element to Bytes.
6260 unsigned Base = OpNo * SystemZ::VectorBytes + Byte;
6261 for (unsigned I = 0; I < BytesPerElement; ++I)
6262 Bytes.push_back(Base + I);
6263
6264 return true;
6265}
6266
6267// Return SDNodes for the completed shuffle.
6268SDValue GeneralShuffle::getNode(SelectionDAG &DAG, const SDLoc &DL) {
6269 assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector");
6270
6271 if (Ops.size() == 0)
6272 return DAG.getUNDEF(VT);
6273
6274 // Use a single unpack if possible as the last operation.
6275 tryPrepareForUnpack();
6276
6277 // Make sure that there are at least two shuffle operands.
6278 if (Ops.size() == 1)
6279 Ops.push_back(DAG.getUNDEF(MVT::v16i8));
6280
6281 // Create a tree of shuffles, deferring root node until after the loop.
6282 // Try to redistribute the undefined elements of non-root nodes so that
6283 // the non-root shuffles match something like a pack or merge, then adjust
6284 // the parent node's permute vector to compensate for the new order.
6285 // Among other things, this copes with vectors like <2 x i16> that were
6286 // padded with undefined elements during type legalization.
6287 //
6288 // In the best case this redistribution will lead to the whole tree
6289 // using packs and merges. It should rarely be a loss in other cases.
6290 unsigned Stride = 1;
6291 for (; Stride * 2 < Ops.size(); Stride *= 2) {
6292 for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) {
6293 SDValue SubOps[] = { Ops[I], Ops[I + Stride] };
6294
6295 // Create a mask for just these two operands.
6297 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
6298 unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes;
6299 unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes;
6300 if (OpNo == I)
6301 NewBytes[J] = Byte;
6302 else if (OpNo == I + Stride)
6303 NewBytes[J] = SystemZ::VectorBytes + Byte;
6304 else
6305 NewBytes[J] = -1;
6306 }
6307 // See if it would be better to reorganize NewMask to avoid using VPERM.
6309 if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) {
6310 Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]);
6311 // Applying NewBytesMap to Ops[I] gets back to NewBytes.
6312 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
6313 if (NewBytes[J] >= 0) {
6314 assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
6315 "Invalid double permute");
6316 Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J];
6317 } else
6318 assert(NewBytesMap[J] < 0 && "Invalid double permute");
6319 }
6320 } else {
6321 // Just use NewBytes on the operands.
6322 Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes);
6323 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J)
6324 if (NewBytes[J] >= 0)
6325 Bytes[J] = I * SystemZ::VectorBytes + J;
6326 }
6327 }
6328 }
6329
6330 // Now we just have 2 inputs. Put the second operand in Ops[1].
6331 if (Stride > 1) {
6332 Ops[1] = Ops[Stride];
6333 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
6334 if (Bytes[I] >= int(SystemZ::VectorBytes))
6335 Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes;
6336 }
6337
6338 // Look for an instruction that can do the permute without resorting
6339 // to VPERM.
6340 unsigned OpNo0, OpNo1;
6341 SDValue Op;
6342 if (unpackWasPrepared() && Ops[1].isUndef())
6343 Op = Ops[0];
6344 else if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1))
6345 Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]);
6346 else
6347 Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes);
6348
6349 Op = insertUnpackIfPrepared(DAG, DL, Op);
6350
6351 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
6352}
6353
6354#ifndef NDEBUG
6355static void dumpBytes(const SmallVectorImpl<int> &Bytes, std::string Msg) {
6356 dbgs() << Msg.c_str() << " { ";
6357 for (unsigned I = 0; I < Bytes.size(); I++)
6358 dbgs() << Bytes[I] << " ";
6359 dbgs() << "}\n";
6360}
6361#endif
6362
6363// If the Bytes vector matches an unpack operation, prepare to do the unpack
6364// after all else by removing the zero vector and the effect of the unpack on
6365// Bytes.
6366void GeneralShuffle::tryPrepareForUnpack() {
6367 uint32_t ZeroVecOpNo = findZeroVectorIdx(&Ops[0], Ops.size());
6368 if (ZeroVecOpNo == UINT32_MAX || Ops.size() == 1)
6369 return;
6370
6371 // Only do this if removing the zero vector reduces the depth, otherwise
6372 // the critical path will increase with the final unpack.
6373 if (Ops.size() > 2 &&
6374 Log2_32_Ceil(Ops.size()) == Log2_32_Ceil(Ops.size() - 1))
6375 return;
6376
6377 // Find an unpack that would allow removing the zero vector from Ops.
6378 UnpackFromEltSize = 1;
6379 for (; UnpackFromEltSize <= 4; UnpackFromEltSize *= 2) {
6380 bool MatchUnpack = true;
6382 for (unsigned Elt = 0; Elt < SystemZ::VectorBytes; Elt++) {
6383 unsigned ToEltSize = UnpackFromEltSize * 2;
6384 bool IsZextByte = (Elt % ToEltSize) < UnpackFromEltSize;
6385 if (!IsZextByte)
6386 SrcBytes.push_back(Bytes[Elt]);
6387 if (Bytes[Elt] != -1) {
6388 unsigned OpNo = unsigned(Bytes[Elt]) / SystemZ::VectorBytes;
6389 if (IsZextByte != (OpNo == ZeroVecOpNo)) {
6390 MatchUnpack = false;
6391 break;
6392 }
6393 }
6394 }
6395 if (MatchUnpack) {
6396 if (Ops.size() == 2) {
6397 // Don't use unpack if a single source operand needs rearrangement.
6398 bool CanUseUnpackLow = true, CanUseUnpackHigh = true;
6399 for (unsigned i = 0; i < SystemZ::VectorBytes / 2; i++) {
6400 if (SrcBytes[i] == -1)
6401 continue;
6402 if (SrcBytes[i] % 16 != int(i))
6403 CanUseUnpackHigh = false;
6404 if (SrcBytes[i] % 16 != int(i + SystemZ::VectorBytes / 2))
6405 CanUseUnpackLow = false;
6406 if (!CanUseUnpackLow && !CanUseUnpackHigh) {
6407 UnpackFromEltSize = UINT_MAX;
6408 return;
6409 }
6410 }
6411 if (!CanUseUnpackHigh)
6412 UnpackLow = true;
6413 }
6414 break;
6415 }
6416 }
6417 if (UnpackFromEltSize > 4)
6418 return;
6419
6420 LLVM_DEBUG(dbgs() << "Preparing for final unpack of element size "
6421 << UnpackFromEltSize << ". Zero vector is Op#" << ZeroVecOpNo
6422 << ".\n";
6423 dumpBytes(Bytes, "Original Bytes vector:"););
6424
6425 // Apply the unpack in reverse to the Bytes array.
6426 unsigned B = 0;
6427 if (UnpackLow) {
6428 while (B < SystemZ::VectorBytes / 2)
6429 Bytes[B++] = -1;
6430 }
6431 for (unsigned Elt = 0; Elt < SystemZ::VectorBytes;) {
6432 Elt += UnpackFromEltSize;
6433 for (unsigned i = 0; i < UnpackFromEltSize; i++, Elt++, B++)
6434 Bytes[B] = Bytes[Elt];
6435 }
6436 if (!UnpackLow) {
6437 while (B < SystemZ::VectorBytes)
6438 Bytes[B++] = -1;
6439 }
6440
6441 // Remove the zero vector from Ops
6442 Ops.erase(&Ops[ZeroVecOpNo]);
6443 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
6444 if (Bytes[I] >= 0) {
6445 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
6446 if (OpNo > ZeroVecOpNo)
6447 Bytes[I] -= SystemZ::VectorBytes;
6448 }
6449
6450 LLVM_DEBUG(dumpBytes(Bytes, "Resulting Bytes vector, zero vector removed:");
6451 dbgs() << "\n";);
6452}
6453
6454SDValue GeneralShuffle::insertUnpackIfPrepared(SelectionDAG &DAG,
6455 const SDLoc &DL,
6456 SDValue Op) {
6457 if (!unpackWasPrepared())
6458 return Op;
6459 unsigned InBits = UnpackFromEltSize * 8;
6460 EVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBits),
6461 SystemZ::VectorBits / InBits);
6462 SDValue PackedOp = DAG.getNode(ISD::BITCAST, DL, InVT, Op);
6463 unsigned OutBits = InBits * 2;
6464 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(OutBits),
6465 SystemZ::VectorBits / OutBits);
6466 return DAG.getNode(UnpackLow ? SystemZISD::UNPACKL_LOW
6467 : SystemZISD::UNPACKL_HIGH,
6468 DL, OutVT, PackedOp);
6469}
6470
6471// Return true if the given BUILD_VECTOR is a scalar-to-vector conversion.
6473 for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I)
6474 if (!Op.getOperand(I).isUndef())
6475 return false;
6476 return true;
6477}
6478
6479// Return a vector of type VT that contains Value in the first element.
6480// The other elements don't matter.
6482 SDValue Value) {
6483 // If we have a constant, replicate it to all elements and let the
6484 // BUILD_VECTOR lowering take care of it.
6485 if (Value.getOpcode() == ISD::Constant ||
6486 Value.getOpcode() == ISD::ConstantFP) {
6488 return DAG.getBuildVector(VT, DL, Ops);
6489 }
6490 if (Value.isUndef())
6491 return DAG.getUNDEF(VT);
6492 return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
6493}
6494
6495// Return a vector of type VT in which Op0 is in element 0 and Op1 is in
6496// element 1. Used for cases in which replication is cheap.
6498 SDValue Op0, SDValue Op1) {
6499 if (Op0.isUndef()) {
6500 if (Op1.isUndef())
6501 return DAG.getUNDEF(VT);
6502 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1);
6503 }
6504 if (Op1.isUndef())
6505 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0);
6506 return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT,
6507 buildScalarToVector(DAG, DL, VT, Op0),
6508 buildScalarToVector(DAG, DL, VT, Op1));
6509}
6510
6511// Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64
6512// vector for them.
6514 SDValue Op1) {
6515 if (Op0.isUndef() && Op1.isUndef())
6516 return DAG.getUNDEF(MVT::v2i64);
6517 // If one of the two inputs is undefined then replicate the other one,
6518 // in order to avoid using another register unnecessarily.
6519 if (Op0.isUndef())
6520 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
6521 else if (Op1.isUndef())
6522 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
6523 else {
6524 Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
6525 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
6526 }
6527 return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1);
6528}
6529
6530// If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually
6531// better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for
6532// the non-EXTRACT_VECTOR_ELT elements. See if the given BUILD_VECTOR
6533// would benefit from this representation and return it if so.
6535 BuildVectorSDNode *BVN) {
6536 EVT VT = BVN->getValueType(0);
6537 unsigned NumElements = VT.getVectorNumElements();
6538
6539 // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation
6540 // on byte vectors. If there are non-EXTRACT_VECTOR_ELT elements that still
6541 // need a BUILD_VECTOR, add an additional placeholder operand for that
6542 // BUILD_VECTOR and store its operands in ResidueOps.
6543 GeneralShuffle GS(VT);
6545 bool FoundOne = false;
6546 for (unsigned I = 0; I < NumElements; ++I) {
6547 SDValue Op = BVN->getOperand(I);
6548 if (Op.getOpcode() == ISD::TRUNCATE)
6549 Op = Op.getOperand(0);
6550 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6551 Op.getOperand(1).getOpcode() == ISD::Constant) {
6552 unsigned Elem = Op.getConstantOperandVal(1);
6553 if (!GS.add(Op.getOperand(0), Elem))
6554 return SDValue();
6555 FoundOne = true;
6556 } else if (Op.isUndef()) {
6557 GS.addUndef();
6558 } else {
6559 if (!GS.add(SDValue(), ResidueOps.size()))
6560 return SDValue();
6561 ResidueOps.push_back(BVN->getOperand(I));
6562 }
6563 }
6564
6565 // Nothing to do if there are no EXTRACT_VECTOR_ELTs.
6566 if (!FoundOne)
6567 return SDValue();
6568
6569 // Create the BUILD_VECTOR for the remaining elements, if any.
6570 if (!ResidueOps.empty()) {
6571 while (ResidueOps.size() < NumElements)
6572 ResidueOps.push_back(DAG.getUNDEF(ResidueOps[0].getValueType()));
6573 for (auto &Op : GS.Ops) {
6574 if (!Op.getNode()) {
6575 Op = DAG.getBuildVector(VT, SDLoc(BVN), ResidueOps);
6576 break;
6577 }
6578 }
6579 }
6580 return GS.getNode(DAG, SDLoc(BVN));
6581}
6582
6583bool SystemZTargetLowering::isVectorElementLoad(SDValue Op) const {
6584 if (Op.getOpcode() == ISD::LOAD && cast<LoadSDNode>(Op)->isUnindexed())
6585 return true;
6586 if (auto *AL = dyn_cast<AtomicSDNode>(Op))
6587 if (AL->getOpcode() == ISD::ATOMIC_LOAD)
6588 return true;
6589 if (Subtarget.hasVectorEnhancements2() && Op.getOpcode() == SystemZISD::LRV)
6590 return true;
6591 return false;
6592}
6593
6595 unsigned MergedBits, EVT VT, SDValue Op0,
6596 SDValue Op1) {
6597 MVT IntVecVT = MVT::getVectorVT(MVT::getIntegerVT(MergedBits),
6598 SystemZ::VectorBits / MergedBits);
6599 assert(VT.getSizeInBits() == 128 && IntVecVT.getSizeInBits() == 128 &&
6600 "Handling full vectors only.");
6601 Op0 = DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0);
6602 Op1 = DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op1);
6603 SDValue Op = DAG.getNode(SystemZISD::MERGE_HIGH, DL, IntVecVT, Op0, Op1);
6604 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
6605}
6606
6608 EVT VT, SmallVectorImpl<SDValue> &Elems,
6609 unsigned Pos) {
6610 SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[Pos + 0], Elems[Pos + 1]);
6611 SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[Pos + 2], Elems[Pos + 3]);
6612 // Avoid unnecessary undefs by reusing the other operand.
6613 if (Op01.isUndef()) {
6614 if (Op23.isUndef())
6615 return Op01;
6616 Op01 = Op23;
6617 } else if (Op23.isUndef())
6618 Op23 = Op01;
6619 // Merging identical replications is a no-op.
6620 if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23)
6621 return Op01;
6622 unsigned MergedBits = VT.getSimpleVT().getScalarSizeInBits() * 2;
6623 return mergeHighParts(DAG, DL, MergedBits, VT, Op01, Op23);
6624}
6625
6626// Combine GPR scalar values Elems into a vector of type VT.
6627SDValue
6628SystemZTargetLowering::buildVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
6629 SmallVectorImpl<SDValue> &Elems) const {
6630 // See whether there is a single replicated value.
6632 unsigned int NumElements = Elems.size();
6633 unsigned int Count = 0;
6634 for (auto Elem : Elems) {
6635 if (!Elem.isUndef()) {
6636 if (!Single.getNode())
6637 Single = Elem;
6638 else if (Elem != Single) {
6639 Single = SDValue();
6640 break;
6641 }
6642 Count += 1;
6643 }
6644 }
6645 // There are three cases here:
6646 //
6647 // - if the only defined element is a loaded one, the best sequence
6648 // is a replicating load.
6649 //
6650 // - otherwise, if the only defined element is an i64 value, we will
6651 // end up with the same VLVGP sequence regardless of whether we short-cut
6652 // for replication or fall through to the later code.
6653 //
6654 // - otherwise, if the only defined element is an i32 or smaller value,
6655 // we would need 2 instructions to replicate it: VLVGP followed by VREPx.
6656 // This is only a win if the single defined element is used more than once.
6657 // In other cases we're better off using a single VLVGx.
6658 if (Single.getNode() && (Count > 1 || isVectorElementLoad(Single)))
6659 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single);
6660
6661 // If all elements are loads, use VLREP/VLEs (below).
6662 bool AllLoads = true;
6663 for (auto Elem : Elems)
6664 if (!isVectorElementLoad(Elem)) {
6665 AllLoads = false;
6666 break;
6667 }
6668
6669 // The best way of building a v2i64 from two i64s is to use VLVGP.
6670 if (VT == MVT::v2i64 && !AllLoads)
6671 return joinDwords(DAG, DL, Elems[0], Elems[1]);
6672
6673 // Use a 64-bit merge high to combine two doubles.
6674 if (VT == MVT::v2f64 && !AllLoads)
6675 return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
6676
6677 // Build v4f32 values directly from the FPRs:
6678 //
6679 // <Axxx> <Bxxx> <Cxxxx> <Dxxx>
6680 // V V VMRHF
6681 // <ABxx> <CDxx>
6682 // V VMRHG
6683 // <ABCD>
6684 if (VT == MVT::v4f32 && !AllLoads)
6685 return buildFPVecFromScalars4(DAG, DL, VT, Elems, 0);
6686
6687 // Same for v8f16.
6688 if (VT == MVT::v8f16 && !AllLoads) {
6689 SDValue Op0123 = buildFPVecFromScalars4(DAG, DL, VT, Elems, 0);
6690 SDValue Op4567 = buildFPVecFromScalars4(DAG, DL, VT, Elems, 4);
6691 // Avoid unnecessary undefs by reusing the other operand.
6692 if (Op0123.isUndef())
6693 Op0123 = Op4567;
6694 else if (Op4567.isUndef())
6695 Op4567 = Op0123;
6696 // Merging identical replications is a no-op.
6697 if (Op0123.getOpcode() == SystemZISD::REPLICATE && Op0123 == Op4567)
6698 return Op0123;
6699 return mergeHighParts(DAG, DL, 64, VT, Op0123, Op4567);
6700 }
6701
6702 // Collect the constant terms.
6705
6706 unsigned NumConstants = 0;
6707 for (unsigned I = 0; I < NumElements; ++I) {
6708 SDValue Elem = Elems[I];
6709 if (Elem.getOpcode() == ISD::Constant ||
6710 Elem.getOpcode() == ISD::ConstantFP) {
6711 NumConstants += 1;
6712 Constants[I] = Elem;
6713 Done[I] = true;
6714 }
6715 }
6716 // If there was at least one constant, fill in the other elements of
6717 // Constants with undefs to get a full vector constant and use that
6718 // as the starting point.
6720 SDValue ReplicatedVal;
6721 if (NumConstants > 0) {
6722 for (unsigned I = 0; I < NumElements; ++I)
6723 if (!Constants[I].getNode())
6724 Constants[I] = DAG.getUNDEF(Elems[I].getValueType());
6725 Result = DAG.getBuildVector(VT, DL, Constants);
6726 } else {
6727 // Otherwise try to use VLREP or VLVGP to start the sequence in order to
6728 // avoid a false dependency on any previous contents of the vector
6729 // register.
6730
6731 // Use a VLREP if at least one element is a load. Make sure to replicate
6732 // the load with the most elements having its value.
6733 std::map<const SDNode*, unsigned> UseCounts;
6734 SDNode *LoadMaxUses = nullptr;
6735 for (unsigned I = 0; I < NumElements; ++I)
6736 if (isVectorElementLoad(Elems[I])) {
6737 SDNode *Ld = Elems[I].getNode();
6738 unsigned Count = ++UseCounts[Ld];
6739 if (LoadMaxUses == nullptr || UseCounts[LoadMaxUses] < Count)
6740 LoadMaxUses = Ld;
6741 }
6742 if (LoadMaxUses != nullptr) {
6743 ReplicatedVal = SDValue(LoadMaxUses, 0);
6744 Result = DAG.getNode(SystemZISD::REPLICATE, DL, VT, ReplicatedVal);
6745 } else {
6746 // Try to use VLVGP.
6747 unsigned I1 = NumElements / 2 - 1;
6748 unsigned I2 = NumElements - 1;
6749 bool Def1 = !Elems[I1].isUndef();
6750 bool Def2 = !Elems[I2].isUndef();
6751 if (Def1 || Def2) {
6752 SDValue Elem1 = Elems[Def1 ? I1 : I2];
6753 SDValue Elem2 = Elems[Def2 ? I2 : I1];
6754 Result = DAG.getNode(ISD::BITCAST, DL, VT,
6755 joinDwords(DAG, DL, Elem1, Elem2));
6756 Done[I1] = true;
6757 Done[I2] = true;
6758 } else
6759 Result = DAG.getUNDEF(VT);
6760 }
6761 }
6762
6763 // Use VLVGx to insert the other elements.
6764 for (unsigned I = 0; I < NumElements; ++I)
6765 if (!Done[I] && !Elems[I].isUndef() && Elems[I] != ReplicatedVal)
6766 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I],
6767 DAG.getConstant(I, DL, MVT::i32));
6768 return Result;
6769}
6770
6771SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op,
6772 SelectionDAG &DAG) const {
6773 auto *BVN = cast<BuildVectorSDNode>(Op.getNode());
6774 SDLoc DL(Op);
6775 EVT VT = Op.getValueType();
6776
6777 if (BVN->isConstant()) {
6778 if (SystemZVectorConstantInfo(BVN).isVectorConstantLegal(Subtarget))
6779 return Op;
6780
6781 // Fall back to loading it from memory.
6782 return SDValue();
6783 }
6784
6785 // See if we should use shuffles to construct the vector from other vectors.
6786 if (SDValue Res = tryBuildVectorShuffle(DAG, BVN))
6787 return Res;
6788
6789 // Detect SCALAR_TO_VECTOR conversions.
6791 return buildScalarToVector(DAG, DL, VT, Op.getOperand(0));
6792
6793 // Otherwise use buildVector to build the vector up from GPRs.
6794 unsigned NumElements = Op.getNumOperands();
6796 for (unsigned I = 0; I < NumElements; ++I)
6797 Ops[I] = Op.getOperand(I);
6798 return buildVector(DAG, DL, VT, Ops);
6799}
6800
6801SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
6802 SelectionDAG &DAG) const {
6803 auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode());
6804 SDLoc DL(Op);
6805 EVT VT = Op.getValueType();
6806 unsigned NumElements = VT.getVectorNumElements();
6807
6808 if (VSN->isSplat()) {
6809 SDValue Op0 = Op.getOperand(0);
6810 unsigned Index = VSN->getSplatIndex();
6811 assert(Index < VT.getVectorNumElements() &&
6812 "Splat index should be defined and in first operand");
6813 // See whether the value we're splatting is directly available as a scalar.
6814 if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
6816 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index));
6817 // Otherwise keep it as a vector-to-vector operation.
6818 return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0),
6819 DAG.getTargetConstant(Index, DL, MVT::i32));
6820 }
6821
6822 GeneralShuffle GS(VT);
6823 for (unsigned I = 0; I < NumElements; ++I) {
6824 int Elt = VSN->getMaskElt(I);
6825 if (Elt < 0)
6826 GS.addUndef();
6827 else if (!GS.add(Op.getOperand(unsigned(Elt) / NumElements),
6828 unsigned(Elt) % NumElements))
6829 return SDValue();
6830 }
6831 return GS.getNode(DAG, SDLoc(VSN));
6832}
6833
6834SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
6835 SelectionDAG &DAG) const {
6836 SDLoc DL(Op);
6837 // Just insert the scalar into element 0 of an undefined vector.
6838 return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL,
6839 Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
6840 Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32));
6841}
6842
6843// Shift the lower 2 bytes of Op to the left in order to insert into the
6844// upper 2 bytes of the FP register.
6846 assert(Op.getSimpleValueType() == MVT::i64 &&
6847 "Expexted to convert i64 to f16.");
6848 SDLoc DL(Op);
6849 SDValue Shft = DAG.getNode(ISD::SHL, DL, MVT::i64, Op,
6850 DAG.getConstant(48, DL, MVT::i64));
6851 SDValue BCast = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Shft);
6852 SDValue F16Val =
6853 DAG.getTargetExtractSubreg(SystemZ::subreg_h16, DL, MVT::f16, BCast);
6854 return F16Val;
6855}
6856
6857// Extract Op into GPR and shift the 2 f16 bytes to the right.
6859 assert(Op.getSimpleValueType() == MVT::f16 &&
6860 "Expected to convert f16 to i64.");
6861 SDNode *U32 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
6862 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h16, DL, MVT::f64,
6863 SDValue(U32, 0), Op);
6864 SDValue BCast = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
6865 SDValue Shft = DAG.getNode(ISD::SRL, DL, MVT::i64, BCast,
6866 DAG.getConstant(48, DL, MVT::i32));
6867 return Shft;
6868}
6869
6871 auto *CIdx = dyn_cast<ConstantSDNode>(Idx);
6872 return CIdx && CIdx->getZExtValue() < VecVT.getVectorNumElements();
6873}
6874
6875SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
6876 SelectionDAG &DAG) const {
6877 // Handle insertions of floating-point values.
6878 SDLoc DL(Op);
6879 SDValue Op0 = Op.getOperand(0);
6880 SDValue Op1 = Op.getOperand(1);
6881 SDValue Op2 = Op.getOperand(2);
6882 EVT VT = Op.getValueType();
6883
6884 // A constant index selects a GR128 subregister.
6885 if (!Subtarget.hasVector())
6886 return isInBoundsConstantVectorIndex(VT, Op2) ? Op : SDValue();
6887
6888 // Insertions into constant indices of a v2f64 can be done using VPDI.
6889 // However, if the inserted value is a bitcast or a constant then it's
6890 // better to use GPRs, as below.
6891 if (VT == MVT::v2f64 && Op1.getOpcode() != ISD::BITCAST &&
6892 Op1.getOpcode() != ISD::ConstantFP &&
6894 return Op;
6895
6896 // Otherwise bitcast to the equivalent integer form and insert via a GPR.
6897 MVT IntVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
6898 MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements());
6899 SDValue IntOp1 =
6900 VT == MVT::v8f16
6901 ? DAG.getZExtOrTrunc(convertFromF16(Op1, DL, DAG), DL, MVT::i32)
6902 : DAG.getNode(ISD::BITCAST, DL, IntVT, Op1);
6903 SDValue Res =
6904 DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT,
6905 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), IntOp1, Op2);
6906 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
6907}
6908
6909SDValue
6910SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
6911 SelectionDAG &DAG) const {
6912 // Handle extractions of floating-point values.
6913 SDLoc DL(Op);
6914 SDValue Op0 = Op.getOperand(0);
6915 SDValue Op1 = Op.getOperand(1);
6916 EVT VT = Op.getValueType();
6917 EVT VecVT = Op0.getValueType();
6918
6919 // Extractions of constant indices can be done directly.
6920 if (isInBoundsConstantVectorIndex(VecVT, Op1))
6921 return Op;
6922
6923 if (!Subtarget.hasVector())
6924 return SDValue();
6925
6926 // Otherwise bitcast to the equivalent integer form and extract via a GPR.
6927 MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
6928 MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements());
6929 MVT ExtrVT = IntVT == MVT::i16 ? MVT::i32 : IntVT;
6930 SDValue Extr = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrVT,
6931 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1);
6932 if (VT == MVT::f16)
6933 return convertToF16(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Extr), DAG);
6934 return DAG.getNode(ISD::BITCAST, DL, VT, Extr);
6935}
6936
6937SDValue SystemZTargetLowering::
6938lowerSIGN_EXTEND_VECTOR_INREG(SDValue Op, SelectionDAG &DAG) const {
6939 SDValue PackedOp = Op.getOperand(0);
6940 EVT OutVT = Op.getValueType();
6941 EVT InVT = PackedOp.getValueType();
6942 unsigned ToBits = OutVT.getScalarSizeInBits();
6943 unsigned FromBits = InVT.getScalarSizeInBits();
6944 unsigned StartOffset = 0;
6945
6946 // If the input is a VECTOR_SHUFFLE, there are a number of important
6947 // cases where we can directly implement the sign-extension of the
6948 // original input lanes of the shuffle.
6949 if (PackedOp.getOpcode() == ISD::VECTOR_SHUFFLE) {
6950 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(PackedOp.getNode());
6951 ArrayRef<int> ShuffleMask = SVN->getMask();
6952 int OutNumElts = OutVT.getVectorNumElements();
6953
6954 // Recognize the special case where the sign-extension can be done
6955 // by the VSEG instruction. Handled via the default expander.
6956 if (ToBits == 64 && OutNumElts == 2) {
6957 int NumElem = ToBits / FromBits;
6958 if (ShuffleMask[0] == NumElem - 1 && ShuffleMask[1] == 2 * NumElem - 1)
6959 return SDValue();
6960 }
6961
6962 // Recognize the special case where we can fold the shuffle by
6963 // replacing some of the UNPACK_HIGH with UNPACK_LOW.
6964 int StartOffsetCandidate = -1;
6965 for (int Elt = 0; Elt < OutNumElts; Elt++) {
6966 if (ShuffleMask[Elt] == -1)
6967 continue;
6968 if (ShuffleMask[Elt] % OutNumElts == Elt) {
6969 if (StartOffsetCandidate == -1)
6970 StartOffsetCandidate = ShuffleMask[Elt] - Elt;
6971 if (StartOffsetCandidate == ShuffleMask[Elt] - Elt)
6972 continue;
6973 }
6974 StartOffsetCandidate = -1;
6975 break;
6976 }
6977 if (StartOffsetCandidate != -1) {
6978 // The mask indexes the concatenation of both shuffle operands: an offset
6979 // past the first operand's lanes selects lanes of the second.
6980 unsigned InNumElts = InVT.getVectorNumElements();
6981 unsigned Offset = StartOffsetCandidate;
6982 unsigned OpNo = Offset >= InNumElts ? 1 : 0;
6983 StartOffset = Offset - OpNo * InNumElts;
6984 PackedOp = PackedOp.getOperand(OpNo);
6985 }
6986 }
6987
6988 do {
6989 FromBits *= 2;
6990 unsigned OutNumElts = SystemZ::VectorBits / FromBits;
6991 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(FromBits), OutNumElts);
6992 unsigned Opcode = SystemZISD::UNPACK_HIGH;
6993 if (StartOffset >= OutNumElts) {
6994 Opcode = SystemZISD::UNPACK_LOW;
6995 StartOffset -= OutNumElts;
6996 }
6997 PackedOp = DAG.getNode(Opcode, SDLoc(PackedOp), OutVT, PackedOp);
6998 } while (FromBits != ToBits);
6999 return PackedOp;
7000}
7001
7002// Lower a ZERO_EXTEND_VECTOR_INREG to a vector shuffle with a zero vector.
7003SDValue SystemZTargetLowering::
7004lowerZERO_EXTEND_VECTOR_INREG(SDValue Op, SelectionDAG &DAG) const {
7005 SDValue PackedOp = Op.getOperand(0);
7006 SDLoc DL(Op);
7007 EVT OutVT = Op.getValueType();
7008 EVT InVT = PackedOp.getValueType();
7009 unsigned InNumElts = InVT.getVectorNumElements();
7010 unsigned OutNumElts = OutVT.getVectorNumElements();
7011 unsigned NumInPerOut = InNumElts / OutNumElts;
7012
7013 SDValue ZeroVec =
7014 DAG.getSplatVector(InVT, DL, DAG.getConstant(0, DL, InVT.getScalarType()));
7015
7016 SmallVector<int, 16> Mask(InNumElts);
7017 unsigned ZeroVecElt = InNumElts;
7018 for (unsigned PackedElt = 0; PackedElt < OutNumElts; PackedElt++) {
7019 unsigned MaskElt = PackedElt * NumInPerOut;
7020 unsigned End = MaskElt + NumInPerOut - 1;
7021 for (; MaskElt < End; MaskElt++)
7022 Mask[MaskElt] = ZeroVecElt++;
7023 Mask[MaskElt] = PackedElt;
7024 }
7025 SDValue Shuf = DAG.getVectorShuffle(InVT, DL, PackedOp, ZeroVec, Mask);
7026 return DAG.getNode(ISD::BITCAST, DL, OutVT, Shuf);
7027}
7028
7029SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG,
7030 unsigned ByScalar) const {
7031 // Look for cases where a vector shift can use the *_BY_SCALAR form.
7032 SDValue Op0 = Op.getOperand(0);
7033 SDValue Op1 = Op.getOperand(1);
7034 SDLoc DL(Op);
7035 EVT VT = Op.getValueType();
7036 unsigned ElemBitSize = VT.getScalarSizeInBits();
7037
7038 // See whether the shift vector is a splat represented as BUILD_VECTOR.
7039 if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) {
7040 APInt SplatBits, SplatUndef;
7041 unsigned SplatBitSize;
7042 bool HasAnyUndefs;
7043 // Check for constant splats. Use ElemBitSize as the minimum element
7044 // width and reject splats that need wider elements.
7045 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
7046 ElemBitSize, true) &&
7047 SplatBitSize == ElemBitSize) {
7048 SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff,
7049 DL, MVT::i32);
7050 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
7051 }
7052 // Check for variable splats.
7053 BitVector UndefElements;
7054 SDValue Splat = BVN->getSplatValue(&UndefElements);
7055 if (Splat) {
7056 // Since i32 is the smallest legal type, we either need a no-op
7057 // or a truncation.
7058 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat);
7059 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
7060 }
7061 }
7062
7063 // See whether the shift vector is a splat represented as SHUFFLE_VECTOR,
7064 // and the shift amount is directly available in a GPR.
7065 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) {
7066 if (VSN->isSplat()) {
7067 SDValue VSNOp0 = VSN->getOperand(0);
7068 unsigned Index = VSN->getSplatIndex();
7069 assert(Index < VT.getVectorNumElements() &&
7070 "Splat index should be defined and in first operand");
7071 if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
7072 VSNOp0.getOpcode() == ISD::BUILD_VECTOR) {
7073 // Since i32 is the smallest legal type, we either need a no-op
7074 // or a truncation.
7075 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
7076 VSNOp0.getOperand(Index));
7077 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
7078 }
7079 }
7080 }
7081
7082 // Otherwise just treat the current form as legal.
7083 return Op;
7084}
7085
7086SDValue SystemZTargetLowering::lowerFSHL(SDValue Op, SelectionDAG &DAG) const {
7087 SDLoc DL(Op);
7088
7089 // i128 FSHL with a constant amount that is a multiple of 8 can be
7090 // implemented via VECTOR_SHUFFLE. If we have the vector-enhancements-2
7091 // facility, FSHL with a constant amount less than 8 can be implemented
7092 // via SHL_DOUBLE_BIT, and FSHL with other constant amounts by a
7093 // combination of the two.
7094 if (auto *ShiftAmtNode = dyn_cast<ConstantSDNode>(Op.getOperand(2))) {
7095 uint64_t ShiftAmt = ShiftAmtNode->getZExtValue() & 127;
7096 if ((ShiftAmt & 7) == 0 || Subtarget.hasVectorEnhancements2()) {
7097 SDValue Op0 = DAG.getBitcast(MVT::v16i8, Op.getOperand(0));
7098 SDValue Op1 = DAG.getBitcast(MVT::v16i8, Op.getOperand(1));
7099 if (ShiftAmt > 120) {
7100 // For N in 121..128, fshl N == fshr (128 - N), and for 1 <= N < 8
7101 // SHR_DOUBLE_BIT emits fewer instructions.
7102 SDValue Val =
7103 DAG.getNode(SystemZISD::SHR_DOUBLE_BIT, DL, MVT::v16i8, Op0, Op1,
7104 DAG.getTargetConstant(128 - ShiftAmt, DL, MVT::i32));
7105 return DAG.getBitcast(MVT::i128, Val);
7106 }
7107 SmallVector<int, 16> Mask(16);
7108 for (unsigned Elt = 0; Elt < 16; Elt++)
7109 Mask[Elt] = (ShiftAmt >> 3) + Elt;
7110 SDValue Shuf1 = DAG.getVectorShuffle(MVT::v16i8, DL, Op0, Op1, Mask);
7111 if ((ShiftAmt & 7) == 0)
7112 return DAG.getBitcast(MVT::i128, Shuf1);
7113 SDValue Shuf2 = DAG.getVectorShuffle(MVT::v16i8, DL, Op1, Op1, Mask);
7114 SDValue Val =
7115 DAG.getNode(SystemZISD::SHL_DOUBLE_BIT, DL, MVT::v16i8, Shuf1, Shuf2,
7116 DAG.getTargetConstant(ShiftAmt & 7, DL, MVT::i32));
7117 return DAG.getBitcast(MVT::i128, Val);
7118 }
7119 }
7120
7121 return SDValue();
7122}
7123
7124SDValue SystemZTargetLowering::lowerFSHR(SDValue Op, SelectionDAG &DAG) const {
7125 SDLoc DL(Op);
7126
7127 // i128 FSHR with a constant amount that is a multiple of 8 can be
7128 // implemented via VECTOR_SHUFFLE. If we have the vector-enhancements-2
7129 // facility, FSHR with a constant amount less than 8 can be implemented
7130 // via SHR_DOUBLE_BIT, and FSHR with other constant amounts by a
7131 // combination of the two.
7132 if (auto *ShiftAmtNode = dyn_cast<ConstantSDNode>(Op.getOperand(2))) {
7133 uint64_t ShiftAmt = ShiftAmtNode->getZExtValue() & 127;
7134 if ((ShiftAmt & 7) == 0 || Subtarget.hasVectorEnhancements2()) {
7135 SDValue Op0 = DAG.getBitcast(MVT::v16i8, Op.getOperand(0));
7136 SDValue Op1 = DAG.getBitcast(MVT::v16i8, Op.getOperand(1));
7137 if (ShiftAmt > 120) {
7138 // For N in 121..128, fshr N == fshl (128 - N), and for 1 <= N < 8
7139 // SHL_DOUBLE_BIT emits fewer instructions.
7140 SDValue Val =
7141 DAG.getNode(SystemZISD::SHL_DOUBLE_BIT, DL, MVT::v16i8, Op0, Op1,
7142 DAG.getTargetConstant(128 - ShiftAmt, DL, MVT::i32));
7143 return DAG.getBitcast(MVT::i128, Val);
7144 }
7145 SmallVector<int, 16> Mask(16);
7146 for (unsigned Elt = 0; Elt < 16; Elt++)
7147 Mask[Elt] = 16 - (ShiftAmt >> 3) + Elt;
7148 SDValue Shuf1 = DAG.getVectorShuffle(MVT::v16i8, DL, Op0, Op1, Mask);
7149 if ((ShiftAmt & 7) == 0)
7150 return DAG.getBitcast(MVT::i128, Shuf1);
7151 SDValue Shuf2 = DAG.getVectorShuffle(MVT::v16i8, DL, Op0, Op0, Mask);
7152 SDValue Val =
7153 DAG.getNode(SystemZISD::SHR_DOUBLE_BIT, DL, MVT::v16i8, Shuf2, Shuf1,
7154 DAG.getTargetConstant(ShiftAmt & 7, DL, MVT::i32));
7155 return DAG.getBitcast(MVT::i128, Val);
7156 }
7157 }
7158
7159 return SDValue();
7160}
7161
7163 SDLoc DL(Op);
7164 SDValue Src = Op.getOperand(0);
7165 MVT DstVT = Op.getSimpleValueType();
7166
7168 unsigned SrcAS = N->getSrcAddressSpace();
7169
7170 assert(SrcAS != N->getDestAddressSpace() &&
7171 "addrspacecast must be between different address spaces");
7172
7173 // addrspacecast [0 <- 1] : Assinging a ptr32 value to a 64-bit pointer.
7174 // addrspacecast [1 <- 0] : Assigining a 64-bit pointer to a ptr32 value.
7175 if (SrcAS == SYSTEMZAS::PTR32 && DstVT == MVT::i64) {
7176 Op = DAG.getNode(ISD::AND, DL, MVT::i32, Src,
7177 DAG.getConstant(0x7fffffff, DL, MVT::i32));
7178 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, DstVT, Op);
7179 } else if (DstVT == MVT::i32) {
7180 Op = DAG.getNode(ISD::TRUNCATE, DL, DstVT, Src);
7181 Op = DAG.getNode(ISD::AND, DL, MVT::i32, Op,
7182 DAG.getConstant(0x7fffffff, DL, MVT::i32));
7183 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, DstVT, Op);
7184 } else {
7185 report_fatal_error("Bad address space in addrspacecast");
7186 }
7187 return Op;
7188}
7189
7190SDValue SystemZTargetLowering::lowerFP_EXTEND(SDValue Op,
7191 SelectionDAG &DAG) const {
7192 SDValue In = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
7193 if (In.getSimpleValueType() != MVT::f16)
7194 return Op; // Legal
7195 return SDValue(); // Let legalizer emit the libcall.
7196}
7197
7199 MVT VT, SDValue Arg, SDLoc DL,
7200 SDValue Chain, bool IsStrict) const {
7201 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected request for libcall!");
7202 MakeLibCallOptions CallOptions;
7203 SDValue Result;
7204 std::tie(Result, Chain) =
7205 makeLibCall(DAG, LC, VT, Arg, CallOptions, DL, Chain);
7206 return IsStrict ? DAG.getMergeValues({Result, Chain}, DL) : Result;
7207}
7208
7209SDValue SystemZTargetLowering::lower_FP_TO_INT(SDValue Op,
7210 SelectionDAG &DAG) const {
7211 bool IsSigned = (Op->getOpcode() == ISD::FP_TO_SINT ||
7212 Op->getOpcode() == ISD::STRICT_FP_TO_SINT);
7213 bool IsStrict = Op->isStrictFPOpcode();
7214 SDLoc DL(Op);
7215 MVT VT = Op.getSimpleValueType();
7216 SDValue InOp = Op.getOperand(IsStrict ? 1 : 0);
7217 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
7218 EVT InVT = InOp.getValueType();
7219
7220 // FP to unsigned is not directly supported on z10. Promoting an i32
7221 // result to (signed) i64 doesn't generate an inexact condition (fp
7222 // exception) for values that are outside the i32 range but in the i64
7223 // range, so use the default expansion.
7224 if (!Subtarget.hasFPExtension() && !IsSigned)
7225 // Expand i32/i64. F16 values will be recognized to fit and extended.
7226 return SDValue();
7227
7228 // Conversion from f16 is done via f32.
7229 if (InOp.getSimpleValueType() == MVT::f16) {
7231 LowerOperationWrapper(Op.getNode(), Results, DAG);
7232 return DAG.getMergeValues(Results, DL);
7233 }
7234
7235 if (VT == MVT::i128) {
7236 RTLIB::Libcall LC =
7237 IsSigned ? RTLIB::getFPTOSINT(InVT, VT) : RTLIB::getFPTOUINT(InVT, VT);
7238 return useLibCall(DAG, LC, VT, InOp, DL, Chain, IsStrict);
7239 }
7240
7241 return Op; // Legal
7242}
7243
7244SDValue SystemZTargetLowering::lower_INT_TO_FP(SDValue Op,
7245 SelectionDAG &DAG) const {
7246 bool IsSigned = (Op->getOpcode() == ISD::SINT_TO_FP ||
7247 Op->getOpcode() == ISD::STRICT_SINT_TO_FP);
7248 bool IsStrict = Op->isStrictFPOpcode();
7249 SDLoc DL(Op);
7250 MVT VT = Op.getSimpleValueType();
7251 SDValue InOp = Op.getOperand(IsStrict ? 1 : 0);
7252 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
7253 EVT InVT = InOp.getValueType();
7254
7255 // Conversion to f16 is done via f32.
7256 if (VT == MVT::f16) {
7258 LowerOperationWrapper(Op.getNode(), Results, DAG);
7259 return DAG.getMergeValues(Results, DL);
7260 }
7261
7262 // Unsigned to fp is not directly supported on z10.
7263 if (!Subtarget.hasFPExtension() && !IsSigned)
7264 return SDValue(); // Expand i64.
7265
7266 if (InVT == MVT::i128) {
7267 RTLIB::Libcall LC =
7268 IsSigned ? RTLIB::getSINTTOFP(InVT, VT) : RTLIB::getUINTTOFP(InVT, VT);
7269 return useLibCall(DAG, LC, VT, InOp, DL, Chain, IsStrict);
7270 }
7271
7272 return Op; // Legal
7273}
7274
7275// Lower an f16 LOAD in case of no vector support.
7276SDValue SystemZTargetLowering::lowerLoadF16(SDValue Op,
7277 SelectionDAG &DAG) const {
7278 EVT RegVT = Op.getValueType();
7279 assert(RegVT == MVT::f16 && "Expected to lower an f16 load.");
7280 (void)RegVT;
7281
7282 // Load as integer.
7283 SDLoc DL(Op);
7284 SDValue NewLd;
7285 if (auto *AtomicLd = dyn_cast<AtomicSDNode>(Op.getNode())) {
7286 assert(EVT(RegVT) == AtomicLd->getMemoryVT() && "Unhandled f16 load");
7287 NewLd = DAG.getAtomicLoad(ISD::EXTLOAD, DL, MVT::i16, MVT::i64,
7288 AtomicLd->getChain(), AtomicLd->getBasePtr(),
7289 AtomicLd->getMemOperand());
7290 } else {
7291 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
7292 assert(EVT(RegVT) == Ld->getMemoryVT() && "Unhandled f16 load");
7293 NewLd = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i64, Ld->getChain(),
7294 Ld->getBasePtr(), Ld->getPointerInfo(), MVT::i16,
7295 Ld->getBaseAlign(), Ld->getMemOperand()->getFlags());
7296 }
7297 SDValue F16Val = convertToF16(NewLd, DAG);
7298 return DAG.getMergeValues({F16Val, NewLd.getValue(1)}, DL);
7299}
7300
7301// Lower an f16 STORE in case of no vector support.
7302SDValue SystemZTargetLowering::lowerStoreF16(SDValue Op,
7303 SelectionDAG &DAG) const {
7304 SDLoc DL(Op);
7305 SDValue Shft = convertFromF16(Op->getOperand(1), DL, DAG);
7306
7307 if (auto *AtomicSt = dyn_cast<AtomicSDNode>(Op.getNode()))
7308 return DAG.getAtomic(ISD::ATOMIC_STORE, DL, MVT::i16, AtomicSt->getChain(),
7309 Shft, AtomicSt->getBasePtr(),
7310 AtomicSt->getMemOperand());
7311
7312 StoreSDNode *St = cast<StoreSDNode>(Op.getNode());
7313 return DAG.getTruncStore(St->getChain(), DL, Shft, St->getBasePtr(), MVT::i16,
7314 St->getMemOperand());
7315}
7316
7317SDValue SystemZTargetLowering::lowerIS_FPCLASS(SDValue Op,
7318 SelectionDAG &DAG) const {
7319 SDLoc DL(Op);
7320 MVT ResultVT = Op.getSimpleValueType();
7321 SDValue Arg = Op.getOperand(0);
7322 unsigned Check = Op.getConstantOperandVal(1);
7323
7324 unsigned TDCMask = 0;
7325 if (Check & fcSNan)
7327 if (Check & fcQNan)
7329 if (Check & fcPosInf)
7331 if (Check & fcNegInf)
7333 if (Check & fcPosNormal)
7335 if (Check & fcNegNormal)
7337 if (Check & fcPosSubnormal)
7339 if (Check & fcNegSubnormal)
7341 if (Check & fcPosZero)
7342 TDCMask |= SystemZ::TDCMASK_ZERO_PLUS;
7343 if (Check & fcNegZero)
7344 TDCMask |= SystemZ::TDCMASK_ZERO_MINUS;
7345 SDValue TDCMaskV = DAG.getConstant(TDCMask, DL, MVT::i64);
7346
7347 SDValue Intr = DAG.getNode(SystemZISD::TDC, DL, ResultVT, Arg, TDCMaskV);
7348 return getCCResult(DAG, Intr);
7349}
7350
7351SDValue SystemZTargetLowering::lowerREADCYCLECOUNTER(SDValue Op,
7352 SelectionDAG &DAG) const {
7353 SDLoc DL(Op);
7354 SDValue Chain = Op.getOperand(0);
7355
7356 // STCKF only supports a memory operand, so we have to use a temporary.
7357 SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
7358 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
7359 MachinePointerInfo MPI =
7361
7362 // Use STCFK to store the TOD clock into the temporary.
7363 SDValue StoreOps[] = {Chain, StackPtr};
7364 Chain = DAG.getMemIntrinsicNode(
7365 SystemZISD::STCKF, DL, DAG.getVTList(MVT::Other), StoreOps, MVT::i64,
7366 MPI, MaybeAlign(), MachineMemOperand::MOStore);
7367
7368 // And read it back from there.
7369 return DAG.getLoad(MVT::i64, DL, Chain, StackPtr, MPI);
7370}
7371
7373 SelectionDAG &DAG) const {
7374 switch (Op.getOpcode()) {
7375 case ISD::FRAMEADDR:
7376 return lowerFRAMEADDR(Op, DAG);
7377 case ISD::RETURNADDR:
7378 return lowerRETURNADDR(Op, DAG);
7379 case ISD::BR_CC:
7380 return lowerBR_CC(Op, DAG);
7381 case ISD::SELECT_CC:
7382 return lowerSELECT_CC(Op, DAG);
7383 case ISD::SETCC:
7384 return lowerSETCC(Op, DAG);
7385 case ISD::STRICT_FSETCC:
7386 return lowerSTRICT_FSETCC(Op, DAG, false);
7388 return lowerSTRICT_FSETCC(Op, DAG, true);
7389 case ISD::GlobalAddress:
7390 return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
7392 return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
7393 case ISD::BlockAddress:
7394 return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
7395 case ISD::JumpTable:
7396 return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
7397 case ISD::ConstantPool:
7398 return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
7399 case ISD::BITCAST:
7400 return lowerBITCAST(Op, DAG);
7401 case ISD::VASTART:
7402 return lowerVASTART(Op, DAG);
7403 case ISD::VACOPY:
7404 return lowerVACOPY(Op, DAG);
7406 return lowerDYNAMIC_STACKALLOC(Op, DAG);
7408 return lowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
7409 case ISD::MULHS:
7410 return lowerMULH(Op, DAG, SystemZISD::SMUL_LOHI);
7411 case ISD::MULHU:
7412 return lowerMULH(Op, DAG, SystemZISD::UMUL_LOHI);
7413 case ISD::SMUL_LOHI:
7414 return lowerSMUL_LOHI(Op, DAG);
7415 case ISD::UMUL_LOHI:
7416 return lowerUMUL_LOHI(Op, DAG);
7417 case ISD::SDIVREM:
7418 return lowerSDIVREM(Op, DAG);
7419 case ISD::UDIVREM:
7420 return lowerUDIVREM(Op, DAG);
7421 case ISD::SADDO:
7422 case ISD::SSUBO:
7423 case ISD::UADDO:
7424 case ISD::USUBO:
7425 return lowerXALUO(Op, DAG);
7426 case ISD::UADDO_CARRY:
7427 case ISD::USUBO_CARRY:
7428 return lowerUADDSUBO_CARRY(Op, DAG);
7429 case ISD::OR:
7430 return lowerOR(Op, DAG);
7431 case ISD::CTPOP:
7432 return lowerCTPOP(Op, DAG);
7433 case ISD::PDEP:
7434 return lowerPDEP(Op, DAG);
7435 case ISD::PEXT:
7436 return lowerPEXT(Op, DAG);
7437 case ISD::VECREDUCE_ADD:
7438 return lowerVECREDUCE_ADD(Op, DAG);
7439 case ISD::ATOMIC_FENCE:
7440 return lowerATOMIC_FENCE(Op, DAG);
7441 case ISD::ATOMIC_STORE:
7442 return lowerATOMIC_STORE(Op, DAG);
7443 case ISD::ATOMIC_LOAD:
7444 return lowerATOMIC_LOAD(Op, DAG);
7446 return lowerATOMIC_LOAD_SUB(Op, DAG);
7448 return lowerATOMIC_CMP_SWAP(Op, DAG);
7449 case ISD::STACKSAVE:
7450 return lowerSTACKSAVE(Op, DAG);
7451 case ISD::STACKRESTORE:
7452 return lowerSTACKRESTORE(Op, DAG);
7453 case ISD::PREFETCH:
7454 return lowerPREFETCH(Op, DAG);
7456 return lowerINTRINSIC_W_CHAIN(Op, DAG);
7458 return lowerINTRINSIC_WO_CHAIN(Op, DAG);
7459 case ISD::BUILD_VECTOR:
7460 return lowerBUILD_VECTOR(Op, DAG);
7462 return lowerVECTOR_SHUFFLE(Op, DAG);
7464 return lowerSCALAR_TO_VECTOR(Op, DAG);
7466 return lowerINSERT_VECTOR_ELT(Op, DAG);
7468 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
7470 return lowerSIGN_EXTEND_VECTOR_INREG(Op, DAG);
7472 return lowerZERO_EXTEND_VECTOR_INREG(Op, DAG);
7473 case ISD::SHL:
7474 return lowerShift(Op, DAG, SystemZISD::VSHL_BY_SCALAR);
7475 case ISD::SRL:
7476 return lowerShift(Op, DAG, SystemZISD::VSRL_BY_SCALAR);
7477 case ISD::SRA:
7478 return lowerShift(Op, DAG, SystemZISD::VSRA_BY_SCALAR);
7479 case ISD::ADDRSPACECAST:
7480 return lowerAddrSpaceCast(Op, DAG);
7481 case ISD::ROTL:
7482 return lowerShift(Op, DAG, SystemZISD::VROTL_BY_SCALAR);
7483 case ISD::FSHL:
7484 return lowerFSHL(Op, DAG);
7485 case ISD::FSHR:
7486 return lowerFSHR(Op, DAG);
7487 case ISD::FP_EXTEND:
7489 return lowerFP_EXTEND(Op, DAG);
7490 case ISD::FP_TO_UINT:
7491 case ISD::FP_TO_SINT:
7494 return lower_FP_TO_INT(Op, DAG);
7495 case ISD::UINT_TO_FP:
7496 case ISD::SINT_TO_FP:
7499 return lower_INT_TO_FP(Op, DAG);
7500 case ISD::LOAD:
7501 return lowerLoadF16(Op, DAG);
7502 case ISD::STORE:
7503 return lowerStoreF16(Op, DAG);
7504 case ISD::IS_FPCLASS:
7505 return lowerIS_FPCLASS(Op, DAG);
7506 case ISD::GET_ROUNDING:
7507 return lowerGET_ROUNDING(Op, DAG);
7509 return lowerREADCYCLECOUNTER(Op, DAG);
7512 // These operations are legal on our platform, but we cannot actually
7513 // set the operation action to Legal as common code would treat this
7514 // as equivalent to Expand. Instead, we keep the operation action to
7515 // Custom and just leave them unchanged here.
7516 return Op;
7517
7518 default:
7519 llvm_unreachable("Unexpected node to lower");
7520 }
7521}
7522
7524 const SDLoc &SL) {
7525 // If i128 is legal, just use a normal bitcast.
7526 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128))
7527 return DAG.getBitcast(MVT::f128, Src);
7528
7529 // Otherwise, f128 must live in FP128, so do a partwise move.
7531 &SystemZ::FP128BitRegClass);
7532
7533 SDValue Hi, Lo;
7534 std::tie(Lo, Hi) = DAG.SplitScalar(Src, SL, MVT::i64, MVT::i64);
7535
7536 Hi = DAG.getBitcast(MVT::f64, Hi);
7537 Lo = DAG.getBitcast(MVT::f64, Lo);
7538
7539 SDNode *Pair = DAG.getMachineNode(
7540 SystemZ::REG_SEQUENCE, SL, MVT::f128,
7541 {DAG.getTargetConstant(SystemZ::FP128BitRegClassID, SL, MVT::i32), Lo,
7542 DAG.getTargetConstant(SystemZ::subreg_l64, SL, MVT::i32), Hi,
7543 DAG.getTargetConstant(SystemZ::subreg_h64, SL, MVT::i32)});
7544 return SDValue(Pair, 0);
7545}
7546
7548 const SDLoc &SL) {
7549 // If i128 is legal, just use a normal bitcast.
7550 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128))
7551 return DAG.getBitcast(MVT::i128, Src);
7552
7553 // Otherwise, f128 must live in FP128, so do a partwise move.
7555 &SystemZ::FP128BitRegClass);
7556
7557 SDValue LoFP =
7558 DAG.getTargetExtractSubreg(SystemZ::subreg_l64, SL, MVT::f64, Src);
7559 SDValue HiFP =
7560 DAG.getTargetExtractSubreg(SystemZ::subreg_h64, SL, MVT::f64, Src);
7561 SDValue Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i64, LoFP);
7562 SDValue Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i64, HiFP);
7563
7564 return DAG.getNode(ISD::BUILD_PAIR, SL, MVT::i128, Lo, Hi);
7565}
7566
7567// Lower operations with invalid operand or result types.
7568void
7571 SelectionDAG &DAG) const {
7572 switch (N->getOpcode()) {
7573 case ISD::ATOMIC_LOAD: {
7574 SDLoc DL(N);
7575 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
7576 SDValue Ops[] = { N->getOperand(0), N->getOperand(1) };
7577 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
7578 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_LOAD_128,
7579 DL, Tys, Ops, MVT::i128, MMO);
7580
7581 SDValue Lowered = lowerGR128ToI128(DAG, Res);
7582 if (N->getValueType(0) == MVT::f128)
7583 Lowered = expandBitCastI128ToF128(DAG, Lowered, DL);
7584 Results.push_back(Lowered);
7585 Results.push_back(Res.getValue(1));
7586 break;
7587 }
7588 case ISD::ATOMIC_STORE: {
7589 SDLoc DL(N);
7590 SDVTList Tys = DAG.getVTList(MVT::Other);
7591 SDValue Val = N->getOperand(1);
7592 if (Val.getValueType() == MVT::f128)
7593 Val = expandBitCastF128ToI128(DAG, Val, DL);
7594 Val = lowerI128ToGR128(DAG, Val);
7595
7596 SDValue Ops[] = {N->getOperand(0), Val, N->getOperand(2)};
7597 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
7598 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_STORE_128,
7599 DL, Tys, Ops, MVT::i128, MMO);
7600 // We have to enforce sequential consistency by performing a
7601 // serialization operation after the store.
7602 if (cast<AtomicSDNode>(N)->getSuccessOrdering() ==
7604 Res = SDValue(DAG.getMachineNode(SystemZ::Serialize, DL,
7605 MVT::Other, Res), 0);
7606 Results.push_back(Res);
7607 break;
7608 }
7610 SDLoc DL(N);
7611 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::i32, MVT::Other);
7612 SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
7613 lowerI128ToGR128(DAG, N->getOperand(2)),
7614 lowerI128ToGR128(DAG, N->getOperand(3)) };
7615 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
7616 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP_128,
7617 DL, Tys, Ops, MVT::i128, MMO);
7618 SDValue Success = emitSETCC(DAG, DL, Res.getValue(1),
7620 Success = DAG.getZExtOrTrunc(Success, DL, N->getValueType(1));
7621 Results.push_back(lowerGR128ToI128(DAG, Res));
7622 Results.push_back(Success);
7623 Results.push_back(Res.getValue(2));
7624 break;
7625 }
7626 case ISD::BITCAST: {
7627 if (useSoftFloat())
7628 return;
7629 SDLoc DL(N);
7630 SDValue Src = N->getOperand(0);
7631 EVT SrcVT = Src.getValueType();
7632 EVT ResVT = N->getValueType(0);
7633 if (ResVT == MVT::i128 && SrcVT == MVT::f128)
7634 Results.push_back(expandBitCastF128ToI128(DAG, Src, DL));
7635 else if (SrcVT == MVT::i16 && ResVT == MVT::f16) {
7636 if (Subtarget.hasVector()) {
7637 SDValue In32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Src);
7638 Results.push_back(SDValue(
7639 DAG.getMachineNode(SystemZ::LEFR_16, DL, MVT::f16, In32), 0));
7640 } else {
7641 SDValue In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Src);
7642 Results.push_back(convertToF16(In64, DAG));
7643 }
7644 } else if (SrcVT == MVT::f16 && ResVT == MVT::i16) {
7645 SDValue ExtractedVal =
7646 Subtarget.hasVector()
7647 ? SDValue(DAG.getMachineNode(SystemZ::LFER_16, DL, MVT::i32, Src),
7648 0)
7649 : convertFromF16(Src, DL, DAG);
7650 Results.push_back(DAG.getZExtOrTrunc(ExtractedVal, DL, ResVT));
7651 }
7652 break;
7653 }
7654 case ISD::UINT_TO_FP:
7655 case ISD::SINT_TO_FP:
7658 if (useSoftFloat())
7659 return;
7660 bool IsStrict = N->isStrictFPOpcode();
7661 SDLoc DL(N);
7662 SDValue InOp = N->getOperand(IsStrict ? 1 : 0);
7663 EVT ResVT = N->getValueType(0);
7664 SDValue Chain = IsStrict ? N->getOperand(0) : DAG.getEntryNode();
7665 if (ResVT == MVT::f16) {
7666 if (!IsStrict) {
7667 SDValue OpF32 = DAG.getNode(N->getOpcode(), DL, MVT::f32, InOp);
7668 Results.push_back(DAG.getFPExtendOrRound(OpF32, DL, MVT::f16));
7669 } else {
7670 SDValue OpF32 =
7671 DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::f32, MVT::Other),
7672 {Chain, InOp});
7673 SDValue F16Res;
7674 std::tie(F16Res, Chain) = DAG.getStrictFPExtendOrRound(
7675 OpF32, OpF32.getValue(1), DL, MVT::f16);
7676 Results.push_back(F16Res);
7677 Results.push_back(Chain);
7678 }
7679 }
7680 break;
7681 }
7682 case ISD::FP_TO_UINT:
7683 case ISD::FP_TO_SINT:
7686 if (useSoftFloat())
7687 return;
7688 bool IsStrict = N->isStrictFPOpcode();
7689 SDLoc DL(N);
7690 EVT ResVT = N->getValueType(0);
7691 SDValue InOp = N->getOperand(IsStrict ? 1 : 0);
7692 EVT InVT = InOp->getValueType(0);
7693 SDValue Chain = IsStrict ? N->getOperand(0) : DAG.getEntryNode();
7694 if (InVT == MVT::f16) {
7695 if (!IsStrict) {
7696 SDValue InF32 = DAG.getFPExtendOrRound(InOp, DL, MVT::f32);
7697 Results.push_back(DAG.getNode(N->getOpcode(), DL, ResVT, InF32));
7698 } else {
7699 SDValue InF32;
7700 std::tie(InF32, Chain) =
7701 DAG.getStrictFPExtendOrRound(InOp, Chain, DL, MVT::f32);
7702 SDValue OpF32 =
7703 DAG.getNode(N->getOpcode(), DL, DAG.getVTList(ResVT, MVT::Other),
7704 {Chain, InF32});
7705 Results.push_back(OpF32);
7706 Results.push_back(OpF32.getValue(1));
7707 }
7708 }
7709 break;
7710 }
7711 case ISD::ATOMIC_SWAP:
7712 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_SWAPW);
7713 break;
7715 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_ADD);
7716 break;
7718 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_SUB);
7719 break;
7721 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_AND);
7722 break;
7724 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_OR);
7725 break;
7727 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_XOR);
7728 break;
7730 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_NAND);
7731 break;
7733 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_MIN);
7734 break;
7736 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_MAX);
7737 break;
7739 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
7740 break;
7742 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
7743 break;
7744 default:
7745 llvm_unreachable("Unexpected node to lower");
7746 }
7747}
7748
7749void
7755
7756// Return true if VT is a vector whose elements are a whole number of bytes
7757// in width. Also check for presence of vector support.
7758bool SystemZTargetLowering::canTreatAsByteVector(EVT VT) const {
7759 if (!Subtarget.hasVector())
7760 return false;
7761
7762 return VT.isVector() && VT.getScalarSizeInBits() % 8 == 0 && VT.isSimple();
7763}
7764
7765// Try to simplify an EXTRACT_VECTOR_ELT from a vector of type VecVT
7766// producing a result of type ResVT. Op is a possibly bitcast version
7767// of the input vector and Index is the index (based on type VecVT) that
7768// should be extracted. Return the new extraction if a simplification
7769// was possible or if Force is true.
7770SDValue SystemZTargetLowering::combineExtract(const SDLoc &DL, EVT ResVT,
7771 EVT VecVT, SDValue Op,
7772 unsigned Index,
7773 DAGCombinerInfo &DCI,
7774 bool Force) const {
7775 SelectionDAG &DAG = DCI.DAG;
7776
7777 // The number of bytes being extracted.
7778 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
7779
7780 for (;;) {
7781 unsigned Opcode = Op.getOpcode();
7782 if (Opcode == ISD::BITCAST)
7783 // Look through bitcasts.
7784 Op = Op.getOperand(0);
7785 else if ((Opcode == ISD::VECTOR_SHUFFLE || Opcode == SystemZISD::SPLAT) &&
7786 canTreatAsByteVector(Op.getValueType())) {
7787 // Get a VPERM-like permute mask and see whether the bytes covered
7788 // by the extracted element are a contiguous sequence from one
7789 // source operand.
7791 if (!getVPermMask(Op, Bytes))
7792 break;
7793 int First;
7794 if (!getShuffleInput(Bytes, Index * BytesPerElement,
7795 BytesPerElement, First))
7796 break;
7797 if (First < 0)
7798 return DAG.getUNDEF(ResVT);
7799 // Make sure the contiguous sequence starts at a multiple of the
7800 // original element size.
7801 unsigned Byte = unsigned(First) % Bytes.size();
7802 if (Byte % BytesPerElement != 0)
7803 break;
7804 // We can get the extracted value directly from an input.
7805 Index = Byte / BytesPerElement;
7806 Op = Op.getOperand(unsigned(First) / Bytes.size());
7807 Force = true;
7808 } else if (Opcode == ISD::BUILD_VECTOR &&
7809 canTreatAsByteVector(Op.getValueType())) {
7810 // We can only optimize this case if the BUILD_VECTOR elements are
7811 // at least as wide as the extracted value.
7812 EVT OpVT = Op.getValueType();
7813 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
7814 if (OpBytesPerElement < BytesPerElement)
7815 break;
7816 // Make sure that the least-significant bit of the extracted value
7817 // is the least significant bit of an input.
7818 unsigned End = (Index + 1) * BytesPerElement;
7819 if (End % OpBytesPerElement != 0)
7820 break;
7821 // We're extracting the low part of one operand of the BUILD_VECTOR.
7822 Op = Op.getOperand(End / OpBytesPerElement - 1);
7823 EVT ResIntVT = MVT::getIntegerVT(ResVT.getSizeInBits());
7824 if (!isTypeLegal(ResIntVT))
7825 break;
7826 if (!Op.getValueType().isInteger()) {
7827 EVT OpIntVT = MVT::getIntegerVT(Op.getValueSizeInBits());
7828 if (!isTypeLegal(OpIntVT))
7829 break;
7830 Op = DAG.getNode(ISD::BITCAST, DL, OpIntVT, Op);
7831 DCI.AddToWorklist(Op.getNode());
7832 }
7833 Op = DAG.getNode(ISD::TRUNCATE, DL, ResIntVT, Op);
7834 if (ResIntVT != ResVT) {
7835 DCI.AddToWorklist(Op.getNode());
7836 Op = DAG.getNode(ISD::BITCAST, DL, ResVT, Op);
7837 }
7838 return Op;
7839 } else if ((Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
7841 Opcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
7842 canTreatAsByteVector(Op.getValueType()) &&
7843 canTreatAsByteVector(Op.getOperand(0).getValueType())) {
7844 // Make sure that only the unextended bits are significant.
7845 EVT ExtVT = Op.getValueType();
7846 EVT OpVT = Op.getOperand(0).getValueType();
7847 unsigned ExtBytesPerElement = ExtVT.getVectorElementType().getStoreSize();
7848 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
7849 unsigned Byte = Index * BytesPerElement;
7850 unsigned SubByte = Byte % ExtBytesPerElement;
7851 unsigned MinSubByte = ExtBytesPerElement - OpBytesPerElement;
7852 if (SubByte < MinSubByte ||
7853 SubByte + BytesPerElement > ExtBytesPerElement)
7854 break;
7855 // Get the byte offset of the unextended element
7856 Byte = Byte / ExtBytesPerElement * OpBytesPerElement;
7857 // ...then add the byte offset relative to that element.
7858 Byte += SubByte - MinSubByte;
7859 if (Byte % BytesPerElement != 0)
7860 break;
7861 Op = Op.getOperand(0);
7862 Index = Byte / BytesPerElement;
7863 Force = true;
7864 } else
7865 break;
7866 }
7867 if (Force) {
7868 if (Op.getValueType() != VecVT) {
7869 Op = DAG.getNode(ISD::BITCAST, DL, VecVT, Op);
7870 DCI.AddToWorklist(Op.getNode());
7871 }
7872 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Op,
7873 DAG.getConstant(Index, DL, MVT::i32));
7874 }
7875 return SDValue();
7876}
7877
7878// Optimize vector operations in scalar value Op on the basis that Op
7879// is truncated to TruncVT.
7880SDValue SystemZTargetLowering::combineTruncateExtract(
7881 const SDLoc &DL, EVT TruncVT, SDValue Op, DAGCombinerInfo &DCI) const {
7882 // If we have (trunc (extract_vector_elt X, Y)), try to turn it into
7883 // (extract_vector_elt (bitcast X), Y'), where (bitcast X) has elements
7884 // of type TruncVT.
7885 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7886 TruncVT.getSizeInBits() % 8 == 0) {
7887 SDValue Vec = Op.getOperand(0);
7888 EVT VecVT = Vec.getValueType();
7889 if (canTreatAsByteVector(VecVT)) {
7890 if (auto *IndexN = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7891 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
7892 unsigned TruncBytes = TruncVT.getStoreSize();
7893 if (BytesPerElement % TruncBytes == 0) {
7894 // Calculate the value of Y' in the above description. We are
7895 // splitting the original elements into Scale equal-sized pieces
7896 // and for truncation purposes want the last (least-significant)
7897 // of these pieces for IndexN. This is easiest to do by calculating
7898 // the start index of the following element and then subtracting 1.
7899 unsigned Scale = BytesPerElement / TruncBytes;
7900 unsigned NewIndex = (IndexN->getZExtValue() + 1) * Scale - 1;
7901
7902 // Defer the creation of the bitcast from X to combineExtract,
7903 // which might be able to optimize the extraction.
7904 VecVT = EVT::getVectorVT(*DCI.DAG.getContext(),
7905 MVT::getIntegerVT(TruncBytes * 8),
7906 VecVT.getStoreSize() / TruncBytes);
7907 EVT ResVT = (TruncBytes < 4 ? MVT::i32 : TruncVT);
7908 return combineExtract(DL, ResVT, VecVT, Vec, NewIndex, DCI, true);
7909 }
7910 }
7911 }
7912 }
7913 return SDValue();
7914}
7915
7916SDValue SystemZTargetLowering::combineZERO_EXTEND(
7917 SDNode *N, DAGCombinerInfo &DCI) const {
7918 // Convert (zext (select_ccmask C1, C2)) into (select_ccmask C1', C2')
7919 SelectionDAG &DAG = DCI.DAG;
7920 SDValue N0 = N->getOperand(0);
7921 EVT VT = N->getValueType(0);
7922 if (N0.getOpcode() == SystemZISD::SELECT_CCMASK) {
7923 auto *TrueOp = dyn_cast<ConstantSDNode>(N0.getOperand(0));
7924 auto *FalseOp = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7925 if (TrueOp && FalseOp) {
7926 SDLoc DL(N0);
7927 SDValue Ops[] = { DAG.getConstant(TrueOp->getZExtValue(), DL, VT),
7928 DAG.getConstant(FalseOp->getZExtValue(), DL, VT),
7929 N0.getOperand(2), N0.getOperand(3), N0.getOperand(4) };
7930 SDValue NewSelect = DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VT, Ops);
7931 // If N0 has multiple uses, change other uses as well.
7932 if (!N0.hasOneUse()) {
7933 SDValue TruncSelect =
7934 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), NewSelect);
7935 DCI.CombineTo(N0.getNode(), TruncSelect);
7936 }
7937 return NewSelect;
7938 }
7939 }
7940 // Convert (zext (xor (trunc X), C)) into (xor (trunc X), C') if the size
7941 // of the result is smaller than the size of X and all the truncated bits
7942 // of X are already zero.
7943 if (N0.getOpcode() == ISD::XOR &&
7944 N0.hasOneUse() && N0.getOperand(0).hasOneUse() &&
7945 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7946 N0.getOperand(1).getOpcode() == ISD::Constant) {
7947 SDValue X = N0.getOperand(0).getOperand(0);
7948 if (VT.isScalarInteger() && VT.getSizeInBits() < X.getValueSizeInBits()) {
7949 KnownBits Known = DAG.computeKnownBits(X);
7950 APInt TruncatedBits = APInt::getBitsSet(X.getValueSizeInBits(),
7951 N0.getValueSizeInBits(),
7952 VT.getSizeInBits());
7953 if (TruncatedBits.isSubsetOf(Known.Zero)) {
7954 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7955 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
7956 return DAG.getNode(ISD::XOR, SDLoc(N0), VT,
7957 X, DAG.getConstant(Mask, SDLoc(N0), VT));
7958 }
7959 }
7960 }
7961 // Recognize patterns for VECTOR SUBTRACT COMPUTE BORROW INDICATION
7962 // and VECTOR ADD COMPUTE CARRY for i128:
7963 // (zext (setcc_uge X Y)) --> (VSCBI X Y)
7964 // (zext (setcc_ule Y X)) --> (VSCBI X Y)
7965 // (zext (setcc_ult (add X Y) X/Y) -> (VACC X Y)
7966 // (zext (setcc_ugt X/Y (add X Y)) -> (VACC X Y)
7967 // For vector types, these patterns are recognized in the .td file.
7968 if (N0.getOpcode() == ISD::SETCC && isTypeLegal(VT) && VT == MVT::i128 &&
7969 N0.getOperand(0).getValueType() == VT) {
7970 SDValue Op0 = N0.getOperand(0);
7971 SDValue Op1 = N0.getOperand(1);
7972 const ISD::CondCode CC = N0.getOperandCondCode(2);
7973 switch (CC) {
7974 case ISD::SETULE:
7975 std::swap(Op0, Op1);
7976 [[fallthrough]];
7977 case ISD::SETUGE:
7978 return DAG.getNode(SystemZISD::VSCBI, SDLoc(N0), VT, Op0, Op1);
7979 case ISD::SETUGT:
7980 std::swap(Op0, Op1);
7981 [[fallthrough]];
7982 case ISD::SETULT:
7983 if (Op0->hasOneUse() && Op0->getOpcode() == ISD::ADD &&
7984 (Op0->getOperand(0) == Op1 || Op0->getOperand(1) == Op1))
7985 return DAG.getNode(SystemZISD::VACC, SDLoc(N0), VT, Op0->getOperand(0),
7986 Op0->getOperand(1));
7987 break;
7988 default:
7989 break;
7990 }
7991 }
7992
7993 return SDValue();
7994}
7995
7996SDValue SystemZTargetLowering::combineSIGN_EXTEND_INREG(
7997 SDNode *N, DAGCombinerInfo &DCI) const {
7998 // Convert (sext_in_reg (setcc LHS, RHS, COND), i1)
7999 // and (sext_in_reg (any_extend (setcc LHS, RHS, COND)), i1)
8000 // into (select_cc LHS, RHS, -1, 0, COND)
8001 SelectionDAG &DAG = DCI.DAG;
8002 SDValue N0 = N->getOperand(0);
8003 EVT VT = N->getValueType(0);
8004 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8005 if (N0.hasOneUse() && N0.getOpcode() == ISD::ANY_EXTEND)
8006 N0 = N0.getOperand(0);
8007 if (EVT == MVT::i1 && N0.hasOneUse() && N0.getOpcode() == ISD::SETCC) {
8008 SDLoc DL(N0);
8009 SDValue Ops[] = { N0.getOperand(0), N0.getOperand(1),
8010 DAG.getAllOnesConstant(DL, VT),
8011 DAG.getConstant(0, DL, VT), N0.getOperand(2) };
8012 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8013 }
8014 return SDValue();
8015}
8016
8017SDValue SystemZTargetLowering::combineSIGN_EXTEND(
8018 SDNode *N, DAGCombinerInfo &DCI) const {
8019 // Convert (sext (ashr (shl X, C1), C2)) to
8020 // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
8021 // cheap as narrower ones.
8022 SelectionDAG &DAG = DCI.DAG;
8023 SDValue N0 = N->getOperand(0);
8024 EVT VT = N->getValueType(0);
8025 if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
8026 auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8027 SDValue Inner = N0.getOperand(0);
8028 if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
8029 if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
8030 unsigned Extra = (VT.getSizeInBits() - N0.getValueSizeInBits());
8031 unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
8032 unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
8033 EVT ShiftVT = N0.getOperand(1).getValueType();
8034 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
8035 Inner.getOperand(0));
8036 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
8037 DAG.getConstant(NewShlAmt, SDLoc(Inner),
8038 ShiftVT));
8039 return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
8040 DAG.getConstant(NewSraAmt, SDLoc(N0), ShiftVT));
8041 }
8042 }
8043 }
8044
8045 return SDValue();
8046}
8047
8048SDValue SystemZTargetLowering::combineMERGE(
8049 SDNode *N, DAGCombinerInfo &DCI) const {
8050 SelectionDAG &DAG = DCI.DAG;
8051 unsigned Opcode = N->getOpcode();
8052 SDValue Op0 = N->getOperand(0);
8053 SDValue Op1 = N->getOperand(1);
8054 if (Op0.getOpcode() == ISD::BITCAST)
8055 Op0 = Op0.getOperand(0);
8056 if (ISD::isBuildVectorAllZeros(Op0)) {
8057 // (z_merge_* 0, 0) -> 0. This is mostly useful for using VLLEZF
8058 // for v4f32.
8059 if (Op1 == N->getOperand(0))
8060 return Op1;
8061 // (z_merge_? 0, X) -> (z_unpackl_? 0, X).
8062 EVT VT = Op1.getValueType();
8063 unsigned ElemBytes = VT.getVectorElementType().getStoreSize();
8064 if (ElemBytes <= 4) {
8065 Opcode = (Opcode == SystemZISD::MERGE_HIGH ?
8066 SystemZISD::UNPACKL_HIGH : SystemZISD::UNPACKL_LOW);
8067 EVT InVT = VT.changeVectorElementTypeToInteger();
8068 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(ElemBytes * 16),
8069 SystemZ::VectorBytes / ElemBytes / 2);
8070 if (VT != InVT) {
8071 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), InVT, Op1);
8072 DCI.AddToWorklist(Op1.getNode());
8073 }
8074 SDValue Op = DAG.getNode(Opcode, SDLoc(N), OutVT, Op1);
8075 DCI.AddToWorklist(Op.getNode());
8076 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
8077 }
8078 }
8079 return SDValue();
8080}
8081
8082static bool isI128MovedToParts(LoadSDNode *LD, SDNode *&LoPart,
8083 SDNode *&HiPart) {
8084 LoPart = HiPart = nullptr;
8085
8086 // Scan through all users.
8087 for (SDUse &Use : LD->uses()) {
8088 // Skip the uses of the chain.
8089 if (Use.getResNo() != 0)
8090 continue;
8091
8092 // Verify every user is a TRUNCATE to i64 of the low or high half.
8093 SDNode *User = Use.getUser();
8094 bool IsLoPart = true;
8095 if (User->getOpcode() == ISD::SRL &&
8096 User->getOperand(1).getOpcode() == ISD::Constant &&
8097 User->getConstantOperandVal(1) == 64 && User->hasOneUse()) {
8098 User = *User->user_begin();
8099 IsLoPart = false;
8100 }
8101 if (User->getOpcode() != ISD::TRUNCATE || User->getValueType(0) != MVT::i64)
8102 return false;
8103
8104 if (IsLoPart) {
8105 if (LoPart)
8106 return false;
8107 LoPart = User;
8108 } else {
8109 if (HiPart)
8110 return false;
8111 HiPart = User;
8112 }
8113 }
8114 return true;
8115}
8116
8117static bool isF128MovedToParts(LoadSDNode *LD, SDNode *&LoPart,
8118 SDNode *&HiPart) {
8119 LoPart = HiPart = nullptr;
8120
8121 // Scan through all users.
8122 for (SDUse &Use : LD->uses()) {
8123 // Skip the uses of the chain.
8124 if (Use.getResNo() != 0)
8125 continue;
8126
8127 // Verify every user is an EXTRACT_SUBREG of the low or high half.
8128 SDNode *User = Use.getUser();
8129 if (!User->hasOneUse() || !User->isMachineOpcode() ||
8130 User->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
8131 return false;
8132
8133 switch (User->getConstantOperandVal(1)) {
8134 case SystemZ::subreg_l64:
8135 if (LoPart)
8136 return false;
8137 LoPart = User;
8138 break;
8139 case SystemZ::subreg_h64:
8140 if (HiPart)
8141 return false;
8142 HiPart = User;
8143 break;
8144 default:
8145 return false;
8146 }
8147 }
8148 return true;
8149}
8150
8151SDValue SystemZTargetLowering::combineLOAD(
8152 SDNode *N, DAGCombinerInfo &DCI) const {
8153 SelectionDAG &DAG = DCI.DAG;
8154 EVT LdVT = N->getValueType(0);
8155 if (auto *LN = dyn_cast<LoadSDNode>(N)) {
8156 if (LN->getAddressSpace() == SYSTEMZAS::PTR32) {
8157 MVT PtrVT = getPointerTy(DAG.getDataLayout());
8158 MVT LoadNodeVT = LN->getBasePtr().getSimpleValueType();
8159 if (PtrVT != LoadNodeVT) {
8160 SDLoc DL(LN);
8161 SDValue AddrSpaceCast = DAG.getAddrSpaceCast(
8162 DL, PtrVT, LN->getBasePtr(), SYSTEMZAS::PTR32, 0);
8163 return DAG.getExtLoad(LN->getExtensionType(), DL, LN->getValueType(0),
8164 LN->getChain(), AddrSpaceCast, LN->getMemoryVT(),
8165 LN->getMemOperand());
8166 }
8167 }
8168 }
8169 SDLoc DL(N);
8170
8171 // Replace a 128-bit load that is used solely to move its value into GPRs
8172 // by separate loads of both halves.
8173 LoadSDNode *LD = cast<LoadSDNode>(N);
8174 if (LD->isSimple() && ISD::isNormalLoad(LD)) {
8175 SDNode *LoPart, *HiPart;
8176 if ((LdVT == MVT::i128 && isI128MovedToParts(LD, LoPart, HiPart)) ||
8177 (LdVT == MVT::f128 && isF128MovedToParts(LD, LoPart, HiPart))) {
8178 // Rewrite each extraction as an independent load.
8179 SmallVector<SDValue, 2> ArgChains;
8180 if (HiPart) {
8181 SDValue EltLoad = DAG.getLoad(
8182 HiPart->getValueType(0), DL, LD->getChain(), LD->getBasePtr(),
8183 LD->getPointerInfo(), LD->getBaseAlign(),
8184 LD->getMemOperand()->getFlags(), LD->getAAInfo());
8185
8186 DCI.CombineTo(HiPart, EltLoad, true);
8187 ArgChains.push_back(EltLoad.getValue(1));
8188 }
8189 if (LoPart) {
8190 SDValue EltLoad = DAG.getLoad(
8191 LoPart->getValueType(0), DL, LD->getChain(),
8192 DAG.getObjectPtrOffset(DL, LD->getBasePtr(), TypeSize::getFixed(8)),
8193 LD->getPointerInfo().getWithOffset(8), LD->getBaseAlign(),
8194 LD->getMemOperand()->getFlags(), LD->getAAInfo());
8195
8196 DCI.CombineTo(LoPart, EltLoad, true);
8197 ArgChains.push_back(EltLoad.getValue(1));
8198 }
8199
8200 // Collect all chains via TokenFactor.
8201 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, ArgChains);
8202 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8203 DCI.AddToWorklist(Chain.getNode());
8204 return SDValue(N, 0);
8205 }
8206 }
8207
8208 if (LdVT.isVector() || LdVT.isInteger())
8209 return SDValue();
8210 // Transform a scalar load that is REPLICATEd as well as having other
8211 // use(s) to the form where the other use(s) use the first element of the
8212 // REPLICATE instead of the load. Otherwise instruction selection will not
8213 // produce a VLREP. Avoid extracting to a GPR, so only do this for floating
8214 // point loads.
8215
8216 SDValue Replicate;
8217 SmallVector<SDNode*, 8> OtherUses;
8218 for (SDUse &Use : N->uses()) {
8219 if (Use.getUser()->getOpcode() == SystemZISD::REPLICATE) {
8220 if (Replicate)
8221 return SDValue(); // Should never happen
8222 Replicate = SDValue(Use.getUser(), 0);
8223 } else if (Use.getResNo() == 0)
8224 OtherUses.push_back(Use.getUser());
8225 }
8226 if (!Replicate || OtherUses.empty())
8227 return SDValue();
8228
8229 SDValue Extract0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, LdVT,
8230 Replicate, DAG.getConstant(0, DL, MVT::i32));
8231 // Update uses of the loaded Value while preserving old chains.
8232 for (SDNode *U : OtherUses) {
8234 for (SDValue Op : U->ops())
8235 Ops.push_back((Op.getNode() == N && Op.getResNo() == 0) ? Extract0 : Op);
8236 DAG.UpdateNodeOperands(U, Ops);
8237 }
8238 return SDValue(N, 0);
8239}
8240
8241bool SystemZTargetLowering::canLoadStoreByteSwapped(EVT VT) const {
8242 if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)
8243 return true;
8244 if (Subtarget.hasVectorEnhancements2())
8245 if (VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v2i64 || VT == MVT::i128)
8246 return true;
8247 return false;
8248}
8249
8251 if (!VT.isVector() || !VT.isSimple() ||
8252 VT.getSizeInBits() != 128 ||
8253 VT.getScalarSizeInBits() % 8 != 0)
8254 return false;
8255
8256 unsigned NumElts = VT.getVectorNumElements();
8257 for (unsigned i = 0; i < NumElts; ++i) {
8258 if (M[i] < 0) continue; // ignore UNDEF indices
8259 if ((unsigned) M[i] != NumElts - 1 - i)
8260 return false;
8261 }
8262
8263 return true;
8264}
8265
8266static bool isOnlyUsedByStores(SDValue StoredVal, SelectionDAG &DAG) {
8267 for (auto *U : StoredVal->users()) {
8268 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(U)) {
8269 EVT CurrMemVT = ST->getMemoryVT().getScalarType();
8270 if (CurrMemVT.isRound() && CurrMemVT.getStoreSize() <= 16)
8271 continue;
8272 } else if (isa<BuildVectorSDNode>(U)) {
8273 SDValue BuildVector = SDValue(U, 0);
8274 if (DAG.isSplatValue(BuildVector, true/*AllowUndefs*/) &&
8275 isOnlyUsedByStores(BuildVector, DAG))
8276 continue;
8277 }
8278 return false;
8279 }
8280 return true;
8281}
8282
8283static bool isI128MovedFromParts(SDValue Val, SDValue &LoPart,
8284 SDValue &HiPart) {
8285 if (Val.getOpcode() != ISD::OR || !Val.getNode()->hasOneUse())
8286 return false;
8287
8288 SDValue Op0 = Val.getOperand(0);
8289 SDValue Op1 = Val.getOperand(1);
8290
8291 if (Op0.getOpcode() == ISD::SHL)
8292 std::swap(Op0, Op1);
8293 if (Op1.getOpcode() != ISD::SHL || !Op1.getNode()->hasOneUse() ||
8294 Op1.getOperand(1).getOpcode() != ISD::Constant ||
8295 Op1.getConstantOperandVal(1) != 64)
8296 return false;
8297 Op1 = Op1.getOperand(0);
8298
8299 if (Op0.getOpcode() != ISD::ZERO_EXTEND || !Op0.getNode()->hasOneUse() ||
8300 Op0.getOperand(0).getValueType() != MVT::i64)
8301 return false;
8302 if (Op1.getOpcode() != ISD::ANY_EXTEND || !Op1.getNode()->hasOneUse() ||
8303 Op1.getOperand(0).getValueType() != MVT::i64)
8304 return false;
8305
8306 LoPart = Op0.getOperand(0);
8307 HiPart = Op1.getOperand(0);
8308 return true;
8309}
8310
8311static bool isF128MovedFromParts(SDValue Val, SDValue &LoPart,
8312 SDValue &HiPart) {
8313 if (!Val.getNode()->hasOneUse() || !Val.isMachineOpcode() ||
8314 Val.getMachineOpcode() != TargetOpcode::REG_SEQUENCE)
8315 return false;
8316
8317 if (Val->getNumOperands() != 5 ||
8318 Val->getOperand(0)->getAsZExtVal() != SystemZ::FP128BitRegClassID ||
8319 Val->getOperand(2)->getAsZExtVal() != SystemZ::subreg_l64 ||
8320 Val->getOperand(4)->getAsZExtVal() != SystemZ::subreg_h64)
8321 return false;
8322
8323 LoPart = Val->getOperand(1);
8324 HiPart = Val->getOperand(3);
8325 return true;
8326}
8327
8328SDValue SystemZTargetLowering::combineSTORE(
8329 SDNode *N, DAGCombinerInfo &DCI) const {
8330 SelectionDAG &DAG = DCI.DAG;
8331 auto *SN = cast<StoreSDNode>(N);
8332 auto &Op1 = N->getOperand(1);
8333 EVT MemVT = SN->getMemoryVT();
8334
8335 if (SN->getAddressSpace() == SYSTEMZAS::PTR32) {
8336 MVT PtrVT = getPointerTy(DAG.getDataLayout());
8337 MVT StoreNodeVT = SN->getBasePtr().getSimpleValueType();
8338 if (PtrVT != StoreNodeVT) {
8339 SDLoc DL(SN);
8340 SDValue AddrSpaceCast = DAG.getAddrSpaceCast(DL, PtrVT, SN->getBasePtr(),
8341 SYSTEMZAS::PTR32, 0);
8342 return DAG.getStore(SN->getChain(), DL, SN->getValue(), AddrSpaceCast,
8343 SN->getPointerInfo(), SN->getBaseAlign(),
8344 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8345 }
8346 }
8347
8348 // If we have (truncstoreiN (extract_vector_elt X, Y), Z) then it is better
8349 // for the extraction to be done on a vMiN value, so that we can use VSTE.
8350 // If X has wider elements then convert it to:
8351 // (truncstoreiN (extract_vector_elt (bitcast X), Y2), Z).
8352 if (MemVT.isInteger() && SN->isTruncatingStore()) {
8353 if (SDValue Value =
8354 combineTruncateExtract(SDLoc(N), MemVT, SN->getValue(), DCI)) {
8355 DCI.AddToWorklist(Value.getNode());
8356
8357 // Rewrite the store with the new form of stored value.
8358 return DAG.getTruncStore(SN->getChain(), SDLoc(SN), Value,
8359 SN->getBasePtr(), SN->getMemoryVT(),
8360 SN->getMemOperand());
8361 }
8362 }
8363
8364 // combine STORE (LOAD_STACK_GUARD) into MOV_STACKGUARD_DAG
8365 if (Op1->isMachineOpcode() &&
8366 (Op1->getMachineOpcode() == SystemZ::LOAD_STACK_GUARD)) {
8367 // Obtain the frame index the store was targeting.
8368 int FI = cast<FrameIndexSDNode>(SN->getOperand(2))->getIndex();
8369 // Prepare operands of the MOV_STACKGUARD ISD Node - Chain and FrameIndex.
8370 SDValue Ops[] = {SN->getChain(), DAG.getTargetFrameIndex(FI, MVT::i64)};
8371 return DAG.getNode(SystemZISD::MOV_STACKGUARD, SDLoc(SN), MVT::Other, Ops);
8372 }
8373
8374 // Combine STORE (BSWAP) into STRVH/STRV/STRVG/VSTBR
8375 if (!SN->isTruncatingStore() &&
8376 Op1.getOpcode() == ISD::BSWAP &&
8377 Op1.getNode()->hasOneUse() &&
8378 canLoadStoreByteSwapped(Op1.getValueType())) {
8379
8380 SDValue BSwapOp = Op1.getOperand(0);
8381
8382 if (BSwapOp.getValueType() == MVT::i16)
8383 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), MVT::i32, BSwapOp);
8384
8385 SDValue Ops[] = {
8386 N->getOperand(0), BSwapOp, N->getOperand(2)
8387 };
8388
8389 return
8390 DAG.getMemIntrinsicNode(SystemZISD::STRV, SDLoc(N), DAG.getVTList(MVT::Other),
8391 Ops, MemVT, SN->getMemOperand());
8392 }
8393 // Combine STORE (element-swap) into VSTER
8394 if (!SN->isTruncatingStore() &&
8395 Op1.getOpcode() == ISD::VECTOR_SHUFFLE &&
8396 Op1.getNode()->hasOneUse() &&
8397 Subtarget.hasVectorEnhancements2()) {
8398 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op1.getNode());
8399 ArrayRef<int> ShuffleMask = SVN->getMask();
8400 if (isVectorElementSwap(ShuffleMask, Op1.getValueType())) {
8401 SDValue Ops[] = {
8402 N->getOperand(0), Op1.getOperand(0), N->getOperand(2)
8403 };
8404
8405 return DAG.getMemIntrinsicNode(SystemZISD::VSTER, SDLoc(N),
8406 DAG.getVTList(MVT::Other),
8407 Ops, MemVT, SN->getMemOperand());
8408 }
8409 }
8410
8411 // Combine STORE (READCYCLECOUNTER) into STCKF.
8412 if (!SN->isTruncatingStore() &&
8414 Op1.hasOneUse() &&
8415 N->getOperand(0).reachesChainWithoutSideEffects(SDValue(Op1.getNode(), 1))) {
8416 SDValue Ops[] = { Op1.getOperand(0), N->getOperand(2) };
8417 return DAG.getMemIntrinsicNode(SystemZISD::STCKF, SDLoc(N),
8418 DAG.getVTList(MVT::Other),
8419 Ops, MemVT, SN->getMemOperand());
8420 }
8421
8422 // Transform a store of a 128-bit value moved from parts into two stores.
8423 if (SN->isSimple() && ISD::isNormalStore(SN)) {
8424 SDValue LoPart, HiPart;
8425 if ((MemVT == MVT::i128 && isI128MovedFromParts(Op1, LoPart, HiPart)) ||
8426 (MemVT == MVT::f128 && isF128MovedFromParts(Op1, LoPart, HiPart))) {
8427 SDLoc DL(SN);
8428 SDValue Chain0 = DAG.getStore(
8429 SN->getChain(), DL, HiPart, SN->getBasePtr(), SN->getPointerInfo(),
8430 SN->getBaseAlign(), SN->getMemOperand()->getFlags(), SN->getAAInfo());
8431 SDValue Chain1 = DAG.getStore(
8432 SN->getChain(), DL, LoPart,
8433 DAG.getObjectPtrOffset(DL, SN->getBasePtr(), TypeSize::getFixed(8)),
8434 SN->getPointerInfo().getWithOffset(8), SN->getBaseAlign(),
8435 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8436
8437 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chain0, Chain1);
8438 }
8439 }
8440
8441 // Replicate a reg or immediate with VREP instead of scalar multiply or
8442 // immediate load. It seems best to do this during the first DAGCombine as
8443 // it is straight-forward to handle the zero-extend node in the initial
8444 // DAG, and also not worry about the keeping the new MemVT legal (e.g. when
8445 // extracting an i16 element from a v16i8 vector).
8446 if (Subtarget.hasVector() && DCI.Level == BeforeLegalizeTypes &&
8447 isOnlyUsedByStores(Op1, DAG)) {
8448 SDValue Word = SDValue();
8449 EVT WordVT;
8450
8451 // Find a replicated immediate and return it if found in Word and its
8452 // type in WordVT.
8453 auto FindReplicatedImm = [&](ConstantSDNode *C, unsigned TotBytes) {
8454 // Some constants are better handled with a scalar store.
8455 if (C->getAPIntValue().getBitWidth() > 64 || C->isAllOnes() ||
8456 isInt<16>(C->getSExtValue()) || MemVT.getStoreSize() <= 2)
8457 return;
8458
8459 APInt Val = C->getAPIntValue();
8460 // Truncate Val in case of a truncating store.
8461 if (!llvm::isUIntN(TotBytes * 8, Val.getZExtValue())) {
8462 assert(SN->isTruncatingStore() &&
8463 "Non-truncating store and immediate value does not fit?");
8464 Val = Val.trunc(TotBytes * 8);
8465 }
8466
8467 SystemZVectorConstantInfo VCI(APInt(TotBytes * 8, Val.getZExtValue()));
8468 if (VCI.isVectorConstantLegal(Subtarget) &&
8469 VCI.Opcode == SystemZISD::REPLICATE) {
8470 Word = DAG.getConstant(VCI.OpVals[0], SDLoc(SN), MVT::i32);
8471 WordVT = VCI.VecVT.getScalarType();
8472 }
8473 };
8474
8475 // Find a replicated register and return it if found in Word and its type
8476 // in WordVT.
8477 auto FindReplicatedReg = [&](SDValue MulOp) {
8478 EVT MulVT = MulOp.getValueType();
8479 if (MulOp->getOpcode() == ISD::MUL &&
8480 (MulVT == MVT::i16 || MulVT == MVT::i32 || MulVT == MVT::i64)) {
8481 // Find a zero extended value and its type.
8482 SDValue LHS = MulOp->getOperand(0);
8483 if (LHS->getOpcode() == ISD::ZERO_EXTEND)
8484 WordVT = LHS->getOperand(0).getValueType();
8485 else if (LHS->getOpcode() == ISD::AssertZext)
8486 WordVT = cast<VTSDNode>(LHS->getOperand(1))->getVT();
8487 else
8488 return;
8489 // Find a replicating constant, e.g. 0x00010001.
8490 if (auto *C = dyn_cast<ConstantSDNode>(MulOp->getOperand(1))) {
8491 SystemZVectorConstantInfo VCI(
8492 APInt(MulVT.getSizeInBits(), C->getZExtValue()));
8493 if (VCI.isVectorConstantLegal(Subtarget) &&
8494 VCI.Opcode == SystemZISD::REPLICATE && VCI.OpVals[0] == 1 &&
8495 WordVT == VCI.VecVT.getScalarType())
8496 Word = DAG.getZExtOrTrunc(LHS->getOperand(0), SDLoc(SN), WordVT);
8497 }
8498 }
8499 };
8500
8501 if (isa<BuildVectorSDNode>(Op1) &&
8502 DAG.isSplatValue(Op1, true/*AllowUndefs*/)) {
8503 SDValue SplatVal = Op1->getOperand(0);
8504 if (auto *C = dyn_cast<ConstantSDNode>(SplatVal))
8505 FindReplicatedImm(C, SplatVal.getValueType().getStoreSize());
8506 else
8507 FindReplicatedReg(SplatVal);
8508 } else {
8509 if (auto *C = dyn_cast<ConstantSDNode>(Op1))
8510 FindReplicatedImm(C, MemVT.getStoreSize());
8511 else
8512 FindReplicatedReg(Op1);
8513 }
8514
8515 if (Word != SDValue()) {
8516 assert(MemVT.getSizeInBits() % WordVT.getSizeInBits() == 0 &&
8517 "Bad type handling");
8518 unsigned NumElts = MemVT.getSizeInBits() / WordVT.getSizeInBits();
8519 EVT SplatVT = EVT::getVectorVT(*DAG.getContext(), WordVT, NumElts);
8520 SDValue SplatVal = DAG.getSplatVector(SplatVT, SDLoc(SN), Word);
8521 return DAG.getStore(SN->getChain(), SDLoc(SN), SplatVal,
8522 SN->getBasePtr(), SN->getMemOperand());
8523 }
8524 }
8525
8526 return SDValue();
8527}
8528
8529SDValue SystemZTargetLowering::combineVECTOR_SHUFFLE(
8530 SDNode *N, DAGCombinerInfo &DCI) const {
8531 SelectionDAG &DAG = DCI.DAG;
8532 // Combine element-swap (LOAD) into VLER
8533 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8534 N->getOperand(0).hasOneUse() &&
8535 Subtarget.hasVectorEnhancements2()) {
8536 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8537 ArrayRef<int> ShuffleMask = SVN->getMask();
8538 if (isVectorElementSwap(ShuffleMask, N->getValueType(0))) {
8539 SDValue Load = N->getOperand(0);
8540 LoadSDNode *LD = cast<LoadSDNode>(Load);
8541
8542 // Create the element-swapping load.
8543 SDValue Ops[] = {
8544 LD->getChain(), // Chain
8545 LD->getBasePtr() // Ptr
8546 };
8547 SDValue ESLoad =
8548 DAG.getMemIntrinsicNode(SystemZISD::VLER, SDLoc(N),
8549 DAG.getVTList(LD->getValueType(0), MVT::Other),
8550 Ops, LD->getMemoryVT(), LD->getMemOperand());
8551
8552 // First, combine the VECTOR_SHUFFLE away. This makes the value produced
8553 // by the load dead.
8554 DCI.CombineTo(N, ESLoad);
8555
8556 // Next, combine the load away, we give it a bogus result value but a real
8557 // chain result. The result value is dead because the shuffle is dead.
8558 DCI.CombineTo(Load.getNode(), ESLoad, ESLoad.getValue(1));
8559
8560 // Return N so it doesn't get rechecked!
8561 return SDValue(N, 0);
8562 }
8563 }
8564
8565 return SDValue();
8566}
8567
8568SDValue SystemZTargetLowering::combineEXTRACT_VECTOR_ELT(
8569 SDNode *N, DAGCombinerInfo &DCI) const {
8570 SelectionDAG &DAG = DCI.DAG;
8571
8572 if (!Subtarget.hasVector())
8573 return SDValue();
8574
8575 // Look through bitcasts that retain the number of vector elements.
8576 SDValue Op = N->getOperand(0);
8577 if (Op.getOpcode() == ISD::BITCAST &&
8578 Op.getValueType().isVector() &&
8579 Op.getOperand(0).getValueType().isVector() &&
8580 Op.getValueType().getVectorNumElements() ==
8581 Op.getOperand(0).getValueType().getVectorNumElements())
8582 Op = Op.getOperand(0);
8583
8584 // Pull BSWAP out of a vector extraction.
8585 if (Op.getOpcode() == ISD::BSWAP && Op.hasOneUse()) {
8586 EVT VecVT = Op.getValueType();
8587 EVT EltVT = VecVT.getVectorElementType();
8588 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), EltVT,
8589 Op.getOperand(0), N->getOperand(1));
8590 DCI.AddToWorklist(Op.getNode());
8591 Op = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Op);
8592 if (EltVT != N->getValueType(0)) {
8593 DCI.AddToWorklist(Op.getNode());
8594 Op = DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Op);
8595 }
8596 return Op;
8597 }
8598
8599 // Try to simplify a vector extraction.
8600 if (auto *IndexN = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8601 SDValue Op0 = N->getOperand(0);
8602 EVT VecVT = Op0.getValueType();
8603 if (canTreatAsByteVector(VecVT))
8604 return combineExtract(SDLoc(N), N->getValueType(0), VecVT, Op0,
8605 IndexN->getZExtValue(), DCI, false);
8606 }
8607 return SDValue();
8608}
8609
8610SDValue SystemZTargetLowering::combineJOIN_DWORDS(
8611 SDNode *N, DAGCombinerInfo &DCI) const {
8612 SelectionDAG &DAG = DCI.DAG;
8613 // (join_dwords X, X) == (replicate X)
8614 if (N->getOperand(0) == N->getOperand(1))
8615 return DAG.getNode(SystemZISD::REPLICATE, SDLoc(N), N->getValueType(0),
8616 N->getOperand(0));
8617 return SDValue();
8618}
8619
8621 SDValue Chain1 = N1->getOperand(0);
8622 SDValue Chain2 = N2->getOperand(0);
8623
8624 // Trivial case: both nodes take the same chain.
8625 if (Chain1 == Chain2)
8626 return Chain1;
8627
8628 // FIXME - we could handle more complex cases via TokenFactor,
8629 // assuming we can verify that this would not create a cycle.
8630 return SDValue();
8631}
8632
8633SDValue SystemZTargetLowering::combineFP_ROUND(
8634 SDNode *N, DAGCombinerInfo &DCI) const {
8635
8636 if (!Subtarget.hasVector())
8637 return SDValue();
8638
8639 // (fpround (extract_vector_elt X 0))
8640 // (fpround (extract_vector_elt X 1)) ->
8641 // (extract_vector_elt (VROUND X) 0)
8642 // (extract_vector_elt (VROUND X) 2)
8643 //
8644 // This is a special case since the target doesn't really support v2f32s.
8645 unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0;
8646 SelectionDAG &DAG = DCI.DAG;
8647 SDValue Op0 = N->getOperand(OpNo);
8648 if (N->getValueType(0) == MVT::f32 && Op0.hasOneUse() &&
8650 Op0.getOperand(0).getValueType() == MVT::v2f64 &&
8651 Op0.getOperand(1).getOpcode() == ISD::Constant &&
8652 Op0.getConstantOperandVal(1) == 0) {
8653 SDValue Vec = Op0.getOperand(0);
8654 for (auto *U : Vec->users()) {
8655 if (U != Op0.getNode() && U->hasOneUse() &&
8656 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8657 U->getOperand(0) == Vec &&
8658 U->getOperand(1).getOpcode() == ISD::Constant &&
8659 U->getConstantOperandVal(1) == 1) {
8660 SDValue OtherRound = SDValue(*U->user_begin(), 0);
8661 if (OtherRound.getOpcode() == N->getOpcode() &&
8662 OtherRound.getOperand(OpNo) == SDValue(U, 0) &&
8663 OtherRound.getValueType() == MVT::f32) {
8664 SDValue VRound, Chain;
8665 if (N->isStrictFPOpcode()) {
8666 Chain = MergeInputChains(N, OtherRound.getNode());
8667 if (!Chain)
8668 continue;
8669 VRound = DAG.getNode(SystemZISD::STRICT_VROUND, SDLoc(N),
8670 {MVT::v4f32, MVT::Other}, {Chain, Vec});
8671 Chain = VRound.getValue(1);
8672 } else
8673 VRound = DAG.getNode(SystemZISD::VROUND, SDLoc(N),
8674 MVT::v4f32, Vec);
8675 DCI.AddToWorklist(VRound.getNode());
8676 SDValue Extract1 =
8677 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f32,
8678 VRound, DAG.getConstant(2, SDLoc(U), MVT::i32));
8679 DCI.AddToWorklist(Extract1.getNode());
8680 DAG.ReplaceAllUsesOfValueWith(OtherRound, Extract1);
8681 if (Chain)
8682 DAG.ReplaceAllUsesOfValueWith(OtherRound.getValue(1), Chain);
8683 SDValue Extract0 =
8684 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f32,
8685 VRound, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
8686 if (Chain)
8687 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0),
8688 N->getVTList(), Extract0, Chain);
8689 return Extract0;
8690 }
8691 }
8692 }
8693 }
8694 return SDValue();
8695}
8696
8697SDValue SystemZTargetLowering::combineFP_EXTEND(
8698 SDNode *N, DAGCombinerInfo &DCI) const {
8699
8700 if (!Subtarget.hasVector())
8701 return SDValue();
8702
8703 // (fpextend (extract_vector_elt X 0))
8704 // (fpextend (extract_vector_elt X 2)) ->
8705 // (extract_vector_elt (VEXTEND X) 0)
8706 // (extract_vector_elt (VEXTEND X) 1)
8707 //
8708 // This is a special case since the target doesn't really support v2f32s.
8709 unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0;
8710 SelectionDAG &DAG = DCI.DAG;
8711 SDValue Op0 = N->getOperand(OpNo);
8712 if (N->getValueType(0) == MVT::f64 && Op0.hasOneUse() &&
8714 Op0.getOperand(0).getValueType() == MVT::v4f32 &&
8715 Op0.getOperand(1).getOpcode() == ISD::Constant &&
8716 Op0.getConstantOperandVal(1) == 0) {
8717 SDValue Vec = Op0.getOperand(0);
8718 for (auto *U : Vec->users()) {
8719 if (U != Op0.getNode() && U->hasOneUse() &&
8720 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8721 U->getOperand(0) == Vec &&
8722 U->getOperand(1).getOpcode() == ISD::Constant &&
8723 U->getConstantOperandVal(1) == 2) {
8724 SDValue OtherExtend = SDValue(*U->user_begin(), 0);
8725 if (OtherExtend.getOpcode() == N->getOpcode() &&
8726 OtherExtend.getOperand(OpNo) == SDValue(U, 0) &&
8727 OtherExtend.getValueType() == MVT::f64) {
8728 SDValue VExtend, Chain;
8729 if (N->isStrictFPOpcode()) {
8730 Chain = MergeInputChains(N, OtherExtend.getNode());
8731 if (!Chain)
8732 continue;
8733 VExtend = DAG.getNode(SystemZISD::STRICT_VEXTEND, SDLoc(N),
8734 {MVT::v2f64, MVT::Other}, {Chain, Vec});
8735 Chain = VExtend.getValue(1);
8736 } else
8737 VExtend = DAG.getNode(SystemZISD::VEXTEND, SDLoc(N),
8738 MVT::v2f64, Vec);
8739 DCI.AddToWorklist(VExtend.getNode());
8740 SDValue Extract1 =
8741 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f64,
8742 VExtend, DAG.getConstant(1, SDLoc(U), MVT::i32));
8743 DCI.AddToWorklist(Extract1.getNode());
8744 DAG.ReplaceAllUsesOfValueWith(OtherExtend, Extract1);
8745 if (Chain)
8746 DAG.ReplaceAllUsesOfValueWith(OtherExtend.getValue(1), Chain);
8747 SDValue Extract0 =
8748 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f64,
8749 VExtend, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
8750 if (Chain)
8751 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0),
8752 N->getVTList(), Extract0, Chain);
8753 return Extract0;
8754 }
8755 }
8756 }
8757 }
8758 return SDValue();
8759}
8760
8761SDValue SystemZTargetLowering::combineINT_TO_FP(
8762 SDNode *N, DAGCombinerInfo &DCI) const {
8763 if (DCI.Level != BeforeLegalizeTypes)
8764 return SDValue();
8765 SelectionDAG &DAG = DCI.DAG;
8766 LLVMContext &Ctx = *DAG.getContext();
8767 unsigned Opcode = N->getOpcode();
8768 EVT OutVT = N->getValueType(0);
8769 Type *OutLLVMTy = OutVT.getTypeForEVT(Ctx);
8770 SDValue Op = N->getOperand(0);
8771 unsigned OutScalarBits = OutLLVMTy->getScalarSizeInBits();
8772 unsigned InScalarBits = Op->getValueType(0).getScalarSizeInBits();
8773
8774 // Insert an extension before type-legalization to avoid scalarization, e.g.:
8775 // v2f64 = uint_to_fp v2i16
8776 // =>
8777 // v2f64 = uint_to_fp (v2i64 zero_extend v2i16)
8778 if (OutLLVMTy->isVectorTy() && OutScalarBits > InScalarBits &&
8779 OutScalarBits <= 64) {
8780 unsigned NumElts = cast<FixedVectorType>(OutLLVMTy)->getNumElements();
8781 EVT ExtVT = EVT::getVectorVT(
8782 Ctx, EVT::getIntegerVT(Ctx, OutLLVMTy->getScalarSizeInBits()), NumElts);
8783 unsigned ExtOpcode =
8785 SDValue ExtOp = DAG.getNode(ExtOpcode, SDLoc(N), ExtVT, Op);
8786 return DAG.getNode(Opcode, SDLoc(N), OutVT, ExtOp);
8787 }
8788 return SDValue();
8789}
8790
8791SDValue SystemZTargetLowering::combineFCOPYSIGN(
8792 SDNode *N, DAGCombinerInfo &DCI) const {
8793 SelectionDAG &DAG = DCI.DAG;
8794 EVT VT = N->getValueType(0);
8795 SDValue ValOp = N->getOperand(0);
8796 SDValue SignOp = N->getOperand(1);
8797
8798 // Remove the rounding which is not needed.
8799 if (SignOp.getOpcode() == ISD::FP_ROUND) {
8800 SDValue WideOp = SignOp.getOperand(0);
8801 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, ValOp, WideOp);
8802 }
8803
8804 return SDValue();
8805}
8806
8807SDValue SystemZTargetLowering::combineBSWAP(
8808 SDNode *N, DAGCombinerInfo &DCI) const {
8809 SelectionDAG &DAG = DCI.DAG;
8810 // Combine BSWAP (LOAD) into LRVH/LRV/LRVG/VLBR
8811 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8812 N->getOperand(0).hasOneUse() &&
8813 canLoadStoreByteSwapped(N->getValueType(0))) {
8814 SDValue Load = N->getOperand(0);
8815 LoadSDNode *LD = cast<LoadSDNode>(Load);
8816
8817 // Create the byte-swapping load.
8818 SDValue Ops[] = {
8819 LD->getChain(), // Chain
8820 LD->getBasePtr() // Ptr
8821 };
8822 EVT LoadVT = N->getValueType(0);
8823 if (LoadVT == MVT::i16)
8824 LoadVT = MVT::i32;
8825 SDValue BSLoad =
8826 DAG.getMemIntrinsicNode(SystemZISD::LRV, SDLoc(N),
8827 DAG.getVTList(LoadVT, MVT::Other),
8828 Ops, LD->getMemoryVT(), LD->getMemOperand());
8829
8830 // If this is an i16 load, insert the truncate.
8831 SDValue ResVal = BSLoad;
8832 if (N->getValueType(0) == MVT::i16)
8833 ResVal = DAG.getNode(ISD::TRUNCATE, SDLoc(N), MVT::i16, BSLoad);
8834
8835 // First, combine the bswap away. This makes the value produced by the
8836 // load dead.
8837 DCI.CombineTo(N, ResVal);
8838
8839 // Next, combine the load away, we give it a bogus result value but a real
8840 // chain result. The result value is dead because the bswap is dead.
8841 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8842
8843 // Return N so it doesn't get rechecked!
8844 return SDValue(N, 0);
8845 }
8846
8847 // Look through bitcasts that retain the number of vector elements.
8848 SDValue Op = N->getOperand(0);
8849 if (Op.getOpcode() == ISD::BITCAST &&
8850 Op.getValueType().isVector() &&
8851 Op.getOperand(0).getValueType().isVector() &&
8852 Op.getValueType().getVectorNumElements() ==
8853 Op.getOperand(0).getValueType().getVectorNumElements())
8854 Op = Op.getOperand(0);
8855
8856 // Push BSWAP into a vector insertion if at least one side then simplifies.
8857 if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT && Op.hasOneUse()) {
8858 SDValue Vec = Op.getOperand(0);
8859 SDValue Elt = Op.getOperand(1);
8860 SDValue Idx = Op.getOperand(2);
8861
8863 Vec.getOpcode() == ISD::BSWAP || Vec.isUndef() ||
8865 Elt.getOpcode() == ISD::BSWAP || Elt.isUndef() ||
8866 (canLoadStoreByteSwapped(N->getValueType(0)) &&
8867 ISD::isNON_EXTLoad(Elt.getNode()) && Elt.hasOneUse())) {
8868 EVT VecVT = N->getValueType(0);
8869 EVT EltVT = N->getValueType(0).getVectorElementType();
8870 if (VecVT != Vec.getValueType()) {
8871 Vec = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Vec);
8872 DCI.AddToWorklist(Vec.getNode());
8873 }
8874 if (EltVT != Elt.getValueType()) {
8875 Elt = DAG.getNode(ISD::BITCAST, SDLoc(N), EltVT, Elt);
8876 DCI.AddToWorklist(Elt.getNode());
8877 }
8878 Vec = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Vec);
8879 DCI.AddToWorklist(Vec.getNode());
8880 Elt = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Elt);
8881 DCI.AddToWorklist(Elt.getNode());
8882 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VecVT,
8883 Vec, Elt, Idx);
8884 }
8885 }
8886
8887 // Push BSWAP into a vector shuffle if at least one side then simplifies.
8888 ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(Op);
8889 if (SV && Op.hasOneUse()) {
8890 SDValue Op0 = Op.getOperand(0);
8891 SDValue Op1 = Op.getOperand(1);
8892
8894 Op0.getOpcode() == ISD::BSWAP || Op0.isUndef() ||
8896 Op1.getOpcode() == ISD::BSWAP || Op1.isUndef()) {
8897 EVT VecVT = N->getValueType(0);
8898 if (VecVT != Op0.getValueType()) {
8899 Op0 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op0);
8900 DCI.AddToWorklist(Op0.getNode());
8901 }
8902 if (VecVT != Op1.getValueType()) {
8903 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op1);
8904 DCI.AddToWorklist(Op1.getNode());
8905 }
8906 Op0 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op0);
8907 DCI.AddToWorklist(Op0.getNode());
8908 Op1 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op1);
8909 DCI.AddToWorklist(Op1.getNode());
8910 return DAG.getVectorShuffle(VecVT, SDLoc(N), Op0, Op1, SV->getMask());
8911 }
8912 }
8913
8914 return SDValue();
8915}
8916
8917SDValue SystemZTargetLowering::combineSETCC(
8918 SDNode *N, DAGCombinerInfo &DCI) const {
8919 SelectionDAG &DAG = DCI.DAG;
8920 const ISD::CondCode CC = N->getOperandCondCode(2);
8921 const SDValue LHS = N->getOperand(0);
8922 const SDValue RHS = N->getOperand(1);
8923 bool CmpNull = isNullConstant(RHS);
8924 bool CmpAllOnes = isAllOnesConstant(RHS);
8925 EVT VT = N->getValueType(0);
8926 SDLoc DL(N);
8927
8928 // Match icmp_eq/ne(bitcast(icmp(X,Y)),0/-1) reduction patterns, and
8929 // change the outer compare to a i128 compare. This will normally
8930 // allow the reduction to be recognized in adjustICmp128, and even if
8931 // not, the i128 compare will still generate better code.
8932 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && (CmpNull || CmpAllOnes)) {
8934 if (Src.getOpcode() == ISD::SETCC &&
8935 Src.getValueType().isFixedLengthVector() &&
8936 Src.getValueType().getScalarType() == MVT::i1) {
8937 EVT CmpVT = Src.getOperand(0).getValueType();
8938 if (CmpVT.getSizeInBits() == 128) {
8939 EVT IntVT = CmpVT.changeVectorElementTypeToInteger();
8940 SDValue LHS =
8941 DAG.getBitcast(MVT::i128, DAG.getSExtOrTrunc(Src, DL, IntVT));
8942 SDValue RHS = CmpNull ? DAG.getConstant(0, DL, MVT::i128)
8943 : DAG.getAllOnesConstant(DL, MVT::i128);
8944 return DAG.getNode(ISD::SETCC, DL, VT, LHS, RHS, N->getOperand(2),
8945 N->getFlags());
8946 }
8947 }
8948 }
8949
8950 return SDValue();
8951}
8952
8953static std::pair<SDValue, int> findCCUse(const SDValue &Val,
8954 unsigned Depth = 0) {
8955 // Limit depth of potentially exponential walk.
8956 if (Depth > 5)
8957 return std::make_pair(SDValue(), SystemZ::CCMASK_NONE);
8958
8959 switch (Val.getOpcode()) {
8960 default:
8961 return std::make_pair(SDValue(), SystemZ::CCMASK_NONE);
8962 case SystemZISD::IPM:
8963 if (Val.getOperand(0).getOpcode() == SystemZISD::CLC ||
8964 Val.getOperand(0).getOpcode() == SystemZISD::STRCMP)
8965 return std::make_pair(Val.getOperand(0), SystemZ::CCMASK_ICMP);
8966 return std::make_pair(Val.getOperand(0), SystemZ::CCMASK_ANY);
8967 case SystemZISD::SELECT_CCMASK: {
8968 SDValue Op4CCReg = Val.getOperand(4);
8969 if (Op4CCReg.getOpcode() == SystemZISD::ICMP ||
8970 Op4CCReg.getOpcode() == SystemZISD::TM) {
8971 auto [OpCC, OpCCValid] = findCCUse(Op4CCReg.getOperand(0), Depth + 1);
8972 if (OpCC != SDValue())
8973 return std::make_pair(OpCC, OpCCValid);
8974 }
8975 auto *CCValid = dyn_cast<ConstantSDNode>(Val.getOperand(2));
8976 if (!CCValid)
8977 return std::make_pair(SDValue(), SystemZ::CCMASK_NONE);
8978 int CCValidVal = CCValid->getZExtValue();
8979 return std::make_pair(Op4CCReg, CCValidVal);
8980 }
8981 case ISD::ADD:
8982 case ISD::AND:
8983 case ISD::OR:
8984 case ISD::XOR:
8985 case ISD::SHL:
8986 case ISD::SRA:
8987 case ISD::SRL:
8988 auto [Op0CC, Op0CCValid] = findCCUse(Val.getOperand(0), Depth + 1);
8989 if (Op0CC != SDValue())
8990 return std::make_pair(Op0CC, Op0CCValid);
8991 return findCCUse(Val.getOperand(1), Depth + 1);
8992 }
8993}
8994
8995static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask,
8996 SelectionDAG &DAG);
8997
8999 SelectionDAG &DAG) {
9000 SDLoc DL(Val);
9001 auto Opcode = Val.getOpcode();
9002 switch (Opcode) {
9003 default:
9004 return {};
9005 case ISD::Constant:
9006 return {Val, Val, Val, Val};
9007 case SystemZISD::IPM: {
9008 SDValue IPMOp0 = Val.getOperand(0);
9009 if (IPMOp0 != CC)
9010 return {};
9011 SmallVector<SDValue, 4> ShiftedCCVals;
9012 for (auto CC : {0, 1, 2, 3})
9013 ShiftedCCVals.emplace_back(
9014 DAG.getConstant((CC << SystemZ::IPM_CC), DL, MVT::i32));
9015 return ShiftedCCVals;
9016 }
9017 case SystemZISD::SELECT_CCMASK: {
9018 SDValue TrueVal = Val.getOperand(0), FalseVal = Val.getOperand(1);
9019 auto *CCValid = dyn_cast<ConstantSDNode>(Val.getOperand(2));
9020 auto *CCMask = dyn_cast<ConstantSDNode>(Val.getOperand(3));
9021 if (!CCValid || !CCMask)
9022 return {};
9023
9024 int CCValidVal = CCValid->getZExtValue();
9025 int CCMaskVal = CCMask->getZExtValue();
9026 // Pruning search tree early - Moving CC test and combineCCMask ahead of
9027 // recursive call to simplifyAssumingCCVal.
9028 SDValue Op4CCReg = Val.getOperand(4);
9029 if (Op4CCReg != CC)
9030 combineCCMask(Op4CCReg, CCValidVal, CCMaskVal, DAG);
9031 if (Op4CCReg != CC)
9032 return {};
9033 const auto &&TrueSDVals = simplifyAssumingCCVal(TrueVal, CC, DAG);
9034 const auto &&FalseSDVals = simplifyAssumingCCVal(FalseVal, CC, DAG);
9035 if (TrueSDVals.empty() || FalseSDVals.empty())
9036 return {};
9037 SmallVector<SDValue, 4> MergedSDVals;
9038 for (auto &CCVal : {0, 1, 2, 3})
9039 MergedSDVals.emplace_back(((CCMaskVal & (1 << (3 - CCVal))) != 0)
9040 ? TrueSDVals[CCVal]
9041 : FalseSDVals[CCVal]);
9042 return MergedSDVals;
9043 }
9044 case ISD::ADD:
9045 case ISD::AND:
9046 case ISD::OR:
9047 case ISD::XOR:
9048 case ISD::SRA:
9049 // Avoid introducing CC spills (because ADD/AND/OR/XOR/SRA
9050 // would clobber CC).
9051 if (!Val.hasOneUse())
9052 return {};
9053 [[fallthrough]];
9054 case ISD::SHL:
9055 case ISD::SRL:
9056 SDValue Op0 = Val.getOperand(0), Op1 = Val.getOperand(1);
9057 const auto &&Op0SDVals = simplifyAssumingCCVal(Op0, CC, DAG);
9058 const auto &&Op1SDVals = simplifyAssumingCCVal(Op1, CC, DAG);
9059 if (Op0SDVals.empty() || Op1SDVals.empty())
9060 return {};
9061 SmallVector<SDValue, 4> BinaryOpSDVals;
9062 for (auto CCVal : {0, 1, 2, 3})
9063 BinaryOpSDVals.emplace_back(DAG.getNode(
9064 Opcode, DL, Val.getValueType(), Op0SDVals[CCVal], Op1SDVals[CCVal]));
9065 return BinaryOpSDVals;
9066 }
9067}
9068
9069static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask,
9070 SelectionDAG &DAG) {
9071 // We have a SELECT_CCMASK or BR_CCMASK comparing the condition code
9072 // set by the CCReg instruction using the CCValid / CCMask masks,
9073 // If the CCReg instruction is itself a ICMP / TM testing the condition
9074 // code set by some other instruction, see whether we can directly
9075 // use that condition code.
9076 auto *CCNode = CCReg.getNode();
9077 if (!CCNode)
9078 return false;
9079
9080 if (CCNode->getOpcode() == SystemZISD::TM) {
9081 if (CCValid != SystemZ::CCMASK_TM)
9082 return false;
9083 auto emulateTMCCMask = [](const SDValue &Op0Val, const SDValue &Op1Val) {
9084 auto *Op0Node = dyn_cast<ConstantSDNode>(Op0Val.getNode());
9085 auto *Op1Node = dyn_cast<ConstantSDNode>(Op1Val.getNode());
9086 if (!Op0Node || !Op1Node)
9087 return -1;
9088 auto Op0APVal = Op0Node->getAPIntValue();
9089 auto Op1APVal = Op1Node->getAPIntValue();
9090 auto Result = Op0APVal & Op1APVal;
9091 bool AllOnes = Result == Op1APVal;
9092 bool AllZeros = Result == 0;
9093 bool IsLeftMostBitSet = Result[Op1APVal.getActiveBits() - 1] != 0;
9094 return AllZeros ? 0 : AllOnes ? 3 : IsLeftMostBitSet ? 2 : 1;
9095 };
9096 SDValue Op0 = CCNode->getOperand(0);
9097 SDValue Op1 = CCNode->getOperand(1);
9098 auto [Op0CC, Op0CCValid] = findCCUse(Op0);
9099 if (Op0CC == SDValue())
9100 return false;
9101 const auto &&Op0SDVals = simplifyAssumingCCVal(Op0, Op0CC, DAG);
9102 const auto &&Op1SDVals = simplifyAssumingCCVal(Op1, Op0CC, DAG);
9103 if (Op0SDVals.empty() || Op1SDVals.empty())
9104 return false;
9105 int NewCCMask = 0;
9106 for (auto CC : {0, 1, 2, 3}) {
9107 auto CCVal = emulateTMCCMask(Op0SDVals[CC], Op1SDVals[CC]);
9108 if (CCVal < 0)
9109 return false;
9110 NewCCMask <<= 1;
9111 NewCCMask |= (CCMask & (1 << (3 - CCVal))) != 0;
9112 }
9113 NewCCMask &= Op0CCValid;
9114 CCReg = Op0CC;
9115 CCMask = NewCCMask;
9116 CCValid = Op0CCValid;
9117 return true;
9118 }
9119 if (CCNode->getOpcode() != SystemZISD::ICMP ||
9120 CCValid != SystemZ::CCMASK_ICMP)
9121 return false;
9122
9123 SDValue CmpOp0 = CCNode->getOperand(0);
9124 SDValue CmpOp1 = CCNode->getOperand(1);
9125 SDValue CmpOp2 = CCNode->getOperand(2);
9126 auto [Op0CC, Op0CCValid] = findCCUse(CmpOp0);
9127 if (Op0CC != SDValue()) {
9128 const auto &&Op0SDVals = simplifyAssumingCCVal(CmpOp0, Op0CC, DAG);
9129 const auto &&Op1SDVals = simplifyAssumingCCVal(CmpOp1, Op0CC, DAG);
9130 if (Op0SDVals.empty() || Op1SDVals.empty())
9131 return false;
9132
9133 auto *CmpType = dyn_cast<ConstantSDNode>(CmpOp2);
9134 auto CmpTypeVal = CmpType->getZExtValue();
9135 const auto compareCCSigned = [&CmpTypeVal](const SDValue &Op0Val,
9136 const SDValue &Op1Val) {
9137 auto *Op0Node = dyn_cast<ConstantSDNode>(Op0Val.getNode());
9138 auto *Op1Node = dyn_cast<ConstantSDNode>(Op1Val.getNode());
9139 if (!Op0Node || !Op1Node)
9140 return -1;
9141 auto Op0APVal = Op0Node->getAPIntValue();
9142 auto Op1APVal = Op1Node->getAPIntValue();
9143 if (CmpTypeVal == SystemZICMP::SignedOnly)
9144 return Op0APVal == Op1APVal ? 0 : Op0APVal.slt(Op1APVal) ? 1 : 2;
9145 return Op0APVal == Op1APVal ? 0 : Op0APVal.ult(Op1APVal) ? 1 : 2;
9146 };
9147 int NewCCMask = 0;
9148 for (auto CC : {0, 1, 2, 3}) {
9149 auto CCVal = compareCCSigned(Op0SDVals[CC], Op1SDVals[CC]);
9150 if (CCVal < 0)
9151 return false;
9152 NewCCMask <<= 1;
9153 NewCCMask |= (CCMask & (1 << (3 - CCVal))) != 0;
9154 }
9155 NewCCMask &= Op0CCValid;
9156 CCMask = NewCCMask;
9157 CCReg = Op0CC;
9158 CCValid = Op0CCValid;
9159 return true;
9160 }
9161
9162 return false;
9163}
9164
9165// Merging versus split in multiple branches cost.
9168 const Value *Lhs,
9169 const Value *Rhs,
9170 const Function *) const {
9171 const auto isFlagOutOpCC = [](const Value *V) {
9172 using namespace llvm::PatternMatch;
9173 const Value *RHSVal;
9174 const APInt *RHSC;
9175 if (const auto *I = dyn_cast<Instruction>(V)) {
9176 // PatternMatch.h provides concise tree-based pattern match of llvm IR.
9177 if (match(I->getOperand(0), m_And(m_Value(RHSVal), m_APInt(RHSC))) ||
9178 match(I, m_Cmp(m_Value(RHSVal), m_APInt(RHSC)))) {
9179 if (const auto *CB = dyn_cast<CallBase>(RHSVal)) {
9180 if (CB->isInlineAsm()) {
9181 const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
9182 return IA && IA->getConstraintString().contains("{@cc}");
9183 }
9184 }
9185 }
9186 }
9187 return false;
9188 };
9189 // Pattern (ICmp %asm) or (ICmp (And %asm)).
9190 // Cost of longest dependency chain (ICmp, And) is 2. CostThreshold or
9191 // BaseCost can be set >=2. If cost of instruction <= CostThreshold
9192 // conditionals will be merged or else conditionals will be split.
9193 if (isFlagOutOpCC(Lhs) && isFlagOutOpCC(Rhs))
9194 return {3, 0, -1};
9195 // Default.
9196 return {-1, -1, -1};
9197}
9198
9199SDValue SystemZTargetLowering::combineBR_CCMASK(SDNode *N,
9200 DAGCombinerInfo &DCI) const {
9201 SelectionDAG &DAG = DCI.DAG;
9202
9203 // Combine BR_CCMASK (ICMP (SELECT_CCMASK)) into a single BR_CCMASK.
9204 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1));
9205 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2));
9206 if (!CCValid || !CCMask)
9207 return SDValue();
9208
9209 int CCValidVal = CCValid->getZExtValue();
9210 int CCMaskVal = CCMask->getZExtValue();
9211 SDValue Chain = N->getOperand(0);
9212 SDValue CCReg = N->getOperand(4);
9213 // If combineCMask was able to merge or simplify ccvalid or ccmask, re-emit
9214 // the modified BR_CCMASK with the new values.
9215 // In order to avoid conditional branches with full or empty cc masks, do not
9216 // do this if ccmask is 0 or equal to ccvalid.
9217 if (combineCCMask(CCReg, CCValidVal, CCMaskVal, DAG) && CCMaskVal != 0 &&
9218 CCMaskVal != CCValidVal)
9219 return DAG.getNode(SystemZISD::BR_CCMASK, SDLoc(N), N->getValueType(0),
9220 Chain,
9221 DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32),
9222 DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32),
9223 N->getOperand(3), CCReg);
9224 return SDValue();
9225}
9226
9227SDValue SystemZTargetLowering::combineSELECT_CCMASK(
9228 SDNode *N, DAGCombinerInfo &DCI) const {
9229 SelectionDAG &DAG = DCI.DAG;
9230
9231 // Combine SELECT_CCMASK (ICMP (SELECT_CCMASK)) into a single SELECT_CCMASK.
9232 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(2));
9233 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(3));
9234 if (!CCValid || !CCMask)
9235 return SDValue();
9236
9237 int CCValidVal = CCValid->getZExtValue();
9238 int CCMaskVal = CCMask->getZExtValue();
9239 SDValue CCReg = N->getOperand(4);
9240
9241 bool IsCombinedCCReg = combineCCMask(CCReg, CCValidVal, CCMaskVal, DAG);
9242
9243 // Populate SDVals vector for each condition code ccval for given Val, which
9244 // can again be another nested select_ccmask with the same CC.
9245 const auto constructCCSDValsFromSELECT = [&CCReg](SDValue &Val) {
9246 if (Val.getOpcode() == SystemZISD::SELECT_CCMASK) {
9248 if (Val.getOperand(4) != CCReg)
9249 return SmallVector<SDValue, 4>{};
9250 SDValue TrueVal = Val.getOperand(0), FalseVal = Val.getOperand(1);
9251 auto *CCMask = dyn_cast<ConstantSDNode>(Val.getOperand(3));
9252 if (!CCMask)
9253 return SmallVector<SDValue, 4>{};
9254
9255 int CCMaskVal = CCMask->getZExtValue();
9256 for (auto &CC : {0, 1, 2, 3})
9257 Res.emplace_back(((CCMaskVal & (1 << (3 - CC))) != 0) ? TrueVal
9258 : FalseVal);
9259 return Res;
9260 }
9261 return SmallVector<SDValue, 4>{Val, Val, Val, Val};
9262 };
9263 // Attempting to optimize TrueVal/FalseVal in outermost select_ccmask either
9264 // with CCReg found by combineCCMask or original CCReg.
9265 SDValue TrueVal = N->getOperand(0);
9266 SDValue FalseVal = N->getOperand(1);
9267 auto &&TrueSDVals = simplifyAssumingCCVal(TrueVal, CCReg, DAG);
9268 auto &&FalseSDVals = simplifyAssumingCCVal(FalseVal, CCReg, DAG);
9269 // TrueSDVals/FalseSDVals might be empty in case of non-constant
9270 // TrueVal/FalseVal for select_ccmask, which can not be optimized further.
9271 if (TrueSDVals.empty())
9272 TrueSDVals = constructCCSDValsFromSELECT(TrueVal);
9273 if (FalseSDVals.empty())
9274 FalseSDVals = constructCCSDValsFromSELECT(FalseVal);
9275 if (!TrueSDVals.empty() && !FalseSDVals.empty()) {
9276 SmallSet<SDValue, 4> MergedSDValsSet;
9277 // Ignoring CC values outside CCValiid.
9278 for (auto CC : {0, 1, 2, 3}) {
9279 if ((CCValidVal & ((1 << (3 - CC)))) != 0)
9280 MergedSDValsSet.insert(((CCMaskVal & (1 << (3 - CC))) != 0)
9281 ? TrueSDVals[CC]
9282 : FalseSDVals[CC]);
9283 }
9284 if (MergedSDValsSet.size() == 1)
9285 return *MergedSDValsSet.begin();
9286 if (MergedSDValsSet.size() == 2) {
9287 auto BeginIt = MergedSDValsSet.begin();
9288 SDValue NewTrueVal = *BeginIt, NewFalseVal = *next(BeginIt);
9289 if (NewTrueVal == FalseVal || NewFalseVal == TrueVal)
9290 std::swap(NewTrueVal, NewFalseVal);
9291 int NewCCMask = 0;
9292 for (auto CC : {0, 1, 2, 3}) {
9293 NewCCMask <<= 1;
9294 NewCCMask |= ((CCMaskVal & (1 << (3 - CC))) != 0)
9295 ? (TrueSDVals[CC] == NewTrueVal)
9296 : (FalseSDVals[CC] == NewTrueVal);
9297 }
9298 CCMaskVal = NewCCMask;
9299 CCMaskVal &= CCValidVal;
9300 TrueVal = NewTrueVal;
9301 FalseVal = NewFalseVal;
9302 IsCombinedCCReg = true;
9303 }
9304 }
9305 // If the condition is trivially false or trivially true after
9306 // combineCCMask, just collapse this SELECT_CCMASK to the indicated value
9307 // (possibly modified by constructCCSDValsFromSELECT).
9308 if (CCMaskVal == 0)
9309 return FalseVal;
9310 if (CCMaskVal == CCValidVal)
9311 return TrueVal;
9312
9313 if (IsCombinedCCReg)
9314 return DAG.getNode(
9315 SystemZISD::SELECT_CCMASK, SDLoc(N), N->getValueType(0), TrueVal,
9316 FalseVal, DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32),
9317 DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32), CCReg);
9318
9319 return SDValue();
9320}
9321
9322SDValue SystemZTargetLowering::combineGET_CCMASK(
9323 SDNode *N, DAGCombinerInfo &DCI) const {
9324
9325 // Optimize away GET_CCMASK (SELECT_CCMASK) if the CC masks are compatible
9326 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1));
9327 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2));
9328 if (!CCValid || !CCMask)
9329 return SDValue();
9330 int CCValidVal = CCValid->getZExtValue();
9331 int CCMaskVal = CCMask->getZExtValue();
9332
9333 SDValue Select = N->getOperand(0);
9334 if (Select->getOpcode() == ISD::TRUNCATE)
9335 Select = Select->getOperand(0);
9336 if (Select->getOpcode() != SystemZISD::SELECT_CCMASK)
9337 return SDValue();
9338
9339 auto *SelectCCValid = dyn_cast<ConstantSDNode>(Select->getOperand(2));
9340 auto *SelectCCMask = dyn_cast<ConstantSDNode>(Select->getOperand(3));
9341 if (!SelectCCValid || !SelectCCMask)
9342 return SDValue();
9343 int SelectCCValidVal = SelectCCValid->getZExtValue();
9344 int SelectCCMaskVal = SelectCCMask->getZExtValue();
9345
9346 auto *TrueVal = dyn_cast<ConstantSDNode>(Select->getOperand(0));
9347 auto *FalseVal = dyn_cast<ConstantSDNode>(Select->getOperand(1));
9348 if (!TrueVal || !FalseVal)
9349 return SDValue();
9350 if (TrueVal->getZExtValue() == 1 && FalseVal->getZExtValue() == 0)
9351 ;
9352 else if (TrueVal->getZExtValue() == 0 && FalseVal->getZExtValue() == 1)
9353 SelectCCMaskVal ^= SelectCCValidVal;
9354 else
9355 return SDValue();
9356
9357 if (SelectCCValidVal & ~CCValidVal)
9358 return SDValue();
9359 if (SelectCCMaskVal != (CCMaskVal & SelectCCValidVal))
9360 return SDValue();
9361
9362 return Select->getOperand(4);
9363}
9364
9365SDValue SystemZTargetLowering::combineIntDIVREM(
9366 SDNode *N, DAGCombinerInfo &DCI) const {
9367 SelectionDAG &DAG = DCI.DAG;
9368 EVT VT = N->getValueType(0);
9369 // In the case where the divisor is a vector of constants a cheaper
9370 // sequence of instructions can replace the divide. BuildSDIV is called to
9371 // do this during DAG combining, but it only succeeds when it can build a
9372 // multiplication node. The only option for SystemZ is ISD::SMUL_LOHI, and
9373 // since it is not Legal but Custom it can only happen before
9374 // legalization. Therefore we must scalarize this early before Combine
9375 // 1. For widened vectors, this is already the result of type legalization.
9376 if (DCI.Level == BeforeLegalizeTypes && VT.isVector() && isTypeLegal(VT) &&
9377 DAG.isConstantIntBuildVectorOrConstantInt(N->getOperand(1)))
9378 return DAG.UnrollVectorOp(N);
9379 return SDValue();
9380}
9381
9382
9383// Transform a right shift of a multiply-and-add into a multiply-and-add-high.
9384// This is closely modeled after the common-code combineShiftToMULH.
9385SDValue SystemZTargetLowering::combineShiftToMulAddHigh(
9386 SDNode *N, DAGCombinerInfo &DCI) const {
9387 SelectionDAG &DAG = DCI.DAG;
9388 SDLoc DL(N);
9389
9390 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
9391 "SRL or SRA node is required here!");
9392
9393 if (!Subtarget.hasVector())
9394 return SDValue();
9395
9396 // Check the shift amount. Proceed with the transformation if the shift
9397 // amount is constant.
9398 ConstantSDNode *ShiftAmtSrc = isConstOrConstSplat(N->getOperand(1));
9399 if (!ShiftAmtSrc)
9400 return SDValue();
9401
9402 // The operation feeding into the shift must be an add.
9403 SDValue ShiftOperand = N->getOperand(0);
9404 if (ShiftOperand.getOpcode() != ISD::ADD)
9405 return SDValue();
9406
9407 // One operand of the add must be a multiply.
9408 SDValue MulOp = ShiftOperand.getOperand(0);
9409 SDValue AddOp = ShiftOperand.getOperand(1);
9410 if (MulOp.getOpcode() != ISD::MUL) {
9411 if (AddOp.getOpcode() != ISD::MUL)
9412 return SDValue();
9413 std::swap(MulOp, AddOp);
9414 }
9415
9416 // All operands must be equivalent extend nodes.
9417 SDValue LeftOp = MulOp.getOperand(0);
9418 SDValue RightOp = MulOp.getOperand(1);
9419
9420 bool IsSignExt = LeftOp.getOpcode() == ISD::SIGN_EXTEND;
9421 bool IsZeroExt = LeftOp.getOpcode() == ISD::ZERO_EXTEND;
9422
9423 if (!IsSignExt && !IsZeroExt)
9424 return SDValue();
9425
9426 EVT NarrowVT = LeftOp.getOperand(0).getValueType();
9427 unsigned NarrowVTSize = NarrowVT.getScalarSizeInBits();
9428
9429 SDValue MulhRightOp;
9430 if (ConstantSDNode *Constant = isConstOrConstSplat(RightOp)) {
9431 unsigned ActiveBits = IsSignExt
9432 ? Constant->getAPIntValue().getSignificantBits()
9433 : Constant->getAPIntValue().getActiveBits();
9434 if (ActiveBits > NarrowVTSize)
9435 return SDValue();
9436 MulhRightOp = DAG.getConstant(
9437 Constant->getAPIntValue().trunc(NarrowVT.getScalarSizeInBits()), DL,
9438 NarrowVT);
9439 } else {
9440 if (LeftOp.getOpcode() != RightOp.getOpcode())
9441 return SDValue();
9442 // Check that the two extend nodes are the same type.
9443 if (NarrowVT != RightOp.getOperand(0).getValueType())
9444 return SDValue();
9445 MulhRightOp = RightOp.getOperand(0);
9446 }
9447
9448 SDValue MulhAddOp;
9449 if (ConstantSDNode *Constant = isConstOrConstSplat(AddOp)) {
9450 unsigned ActiveBits = IsSignExt
9451 ? Constant->getAPIntValue().getSignificantBits()
9452 : Constant->getAPIntValue().getActiveBits();
9453 if (ActiveBits > NarrowVTSize)
9454 return SDValue();
9455 MulhAddOp = DAG.getConstant(
9456 Constant->getAPIntValue().trunc(NarrowVT.getScalarSizeInBits()), DL,
9457 NarrowVT);
9458 } else {
9459 if (LeftOp.getOpcode() != AddOp.getOpcode())
9460 return SDValue();
9461 // Check that the two extend nodes are the same type.
9462 if (NarrowVT != AddOp.getOperand(0).getValueType())
9463 return SDValue();
9464 MulhAddOp = AddOp.getOperand(0);
9465 }
9466
9467 EVT WideVT = LeftOp.getValueType();
9468 // Proceed with the transformation if the wide types match.
9469 assert((WideVT == RightOp.getValueType()) &&
9470 "Cannot have a multiply node with two different operand types.");
9471 assert((WideVT == AddOp.getValueType()) &&
9472 "Cannot have an add node with two different operand types.");
9473
9474 // Proceed with the transformation if the wide type is twice as large
9475 // as the narrow type.
9476 if (WideVT.getScalarSizeInBits() != 2 * NarrowVTSize)
9477 return SDValue();
9478
9479 // Check the shift amount with the narrow type size.
9480 // Proceed with the transformation if the shift amount is the width
9481 // of the narrow type.
9482 unsigned ShiftAmt = ShiftAmtSrc->getZExtValue();
9483 if (ShiftAmt != NarrowVTSize)
9484 return SDValue();
9485
9486 // Proceed if we support the multiply-and-add-high operation.
9487 if (!(NarrowVT == MVT::v16i8 || NarrowVT == MVT::v8i16 ||
9488 NarrowVT == MVT::v4i32 ||
9489 (Subtarget.hasVectorEnhancements3() &&
9490 (NarrowVT == MVT::v2i64 || NarrowVT == MVT::i128))))
9491 return SDValue();
9492
9493 // Emit the VMAH (signed) or VMALH (unsigned) operation.
9494 SDValue Result = DAG.getNode(IsSignExt ? SystemZISD::VMAH : SystemZISD::VMALH,
9495 DL, NarrowVT, LeftOp.getOperand(0),
9496 MulhRightOp, MulhAddOp);
9497 bool IsSigned = N->getOpcode() == ISD::SRA;
9498 return DAG.getExtOrTrunc(IsSigned, Result, DL, WideVT);
9499}
9500
9501// Op is an operand of a multiplication. Check whether this can be folded
9502// into an even/odd widening operation; if so, return the opcode to be used
9503// and update Op to the appropriate sub-operand. Note that the caller must
9504// verify that *both* operands of the multiplication support the operation.
9507 SDValue &Op) {
9508 EVT VT = Op.getValueType();
9509
9510 // Check for (sign/zero_extend_vector_inreg (vector_shuffle)) corresponding
9511 // to selecting the even or odd vector elements.
9512 if (VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
9513 (Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
9514 Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG)) {
9515 bool IsSigned = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
9516 unsigned NumElts = VT.getVectorNumElements();
9517 Op = Op.getOperand(0);
9518 if (Op.getValueType().getVectorNumElements() == 2 * NumElts &&
9519 Op.getOpcode() == ISD::VECTOR_SHUFFLE) {
9521 ArrayRef<int> ShuffleMask = SVN->getMask();
9522 bool CanUseEven = true, CanUseOdd = true;
9523 for (unsigned Elt = 0; Elt < NumElts; Elt++) {
9524 if (ShuffleMask[Elt] == -1)
9525 continue;
9526 if (unsigned(ShuffleMask[Elt]) != 2 * Elt)
9527 CanUseEven = false;
9528 if (unsigned(ShuffleMask[Elt]) != 2 * Elt + 1)
9529 CanUseOdd = false;
9530 }
9531 Op = Op.getOperand(0);
9532 if (CanUseEven)
9533 return IsSigned ? SystemZISD::VME : SystemZISD::VMLE;
9534 if (CanUseOdd)
9535 return IsSigned ? SystemZISD::VMO : SystemZISD::VMLO;
9536 }
9537 }
9538
9539 // For z17, we can also support the v2i64->i128 case, which looks like
9540 // (sign/zero_extend (extract_vector_elt X 0/1))
9541 if (VT == MVT::i128 && Subtarget.hasVectorEnhancements3() &&
9542 (Op.getOpcode() == ISD::SIGN_EXTEND ||
9543 Op.getOpcode() == ISD::ZERO_EXTEND)) {
9544 bool IsSigned = Op.getOpcode() == ISD::SIGN_EXTEND;
9545 Op = Op.getOperand(0);
9546 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9547 Op.getOperand(0).getValueType() == MVT::v2i64 &&
9548 Op.getOperand(1).getOpcode() == ISD::Constant) {
9549 unsigned Elem = Op.getConstantOperandVal(1);
9550 Op = Op.getOperand(0);
9551 if (Elem == 0)
9552 return IsSigned ? SystemZISD::VME : SystemZISD::VMLE;
9553 if (Elem == 1)
9554 return IsSigned ? SystemZISD::VMO : SystemZISD::VMLO;
9555 }
9556 }
9557
9558 return 0;
9559}
9560
9561SDValue SystemZTargetLowering::combineMUL(
9562 SDNode *N, DAGCombinerInfo &DCI) const {
9563 SelectionDAG &DAG = DCI.DAG;
9564
9565 // Detect even/odd widening multiplication.
9566 SDValue Op0 = N->getOperand(0);
9567 SDValue Op1 = N->getOperand(1);
9568 unsigned OpcodeCand0 = detectEvenOddMultiplyOperand(DAG, Subtarget, Op0);
9569 unsigned OpcodeCand1 = detectEvenOddMultiplyOperand(DAG, Subtarget, Op1);
9570 if (OpcodeCand0 && OpcodeCand0 == OpcodeCand1)
9571 return DAG.getNode(OpcodeCand0, SDLoc(N), N->getValueType(0), Op0, Op1);
9572
9573 return SDValue();
9574}
9575
9576SDValue SystemZTargetLowering::combineINTRINSIC(
9577 SDNode *N, DAGCombinerInfo &DCI) const {
9578 SelectionDAG &DAG = DCI.DAG;
9579
9580 unsigned Id = N->getConstantOperandVal(1);
9581 switch (Id) {
9582 // VECTOR LOAD (RIGHTMOST) WITH LENGTH with a length operand of 15
9583 // or larger is simply a vector load.
9584 case Intrinsic::s390_vll:
9585 case Intrinsic::s390_vlrl:
9586 if (auto *C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
9587 if (C->getZExtValue() >= 15)
9588 return DAG.getLoad(N->getValueType(0), SDLoc(N), N->getOperand(0),
9589 N->getOperand(3), MachinePointerInfo());
9590 break;
9591 // Likewise for VECTOR STORE (RIGHTMOST) WITH LENGTH.
9592 case Intrinsic::s390_vstl:
9593 case Intrinsic::s390_vstrl:
9594 if (auto *C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
9595 if (C->getZExtValue() >= 15)
9596 return DAG.getStore(N->getOperand(0), SDLoc(N), N->getOperand(2),
9597 N->getOperand(4), MachinePointerInfo());
9598 break;
9599 }
9600
9601 return SDValue();
9602}
9603
9604SDValue SystemZTargetLowering::unwrapAddress(SDValue N) const {
9605 if (N->getOpcode() == SystemZISD::PCREL_WRAPPER)
9606 return N->getOperand(0);
9607 return N;
9608}
9609
9611 DAGCombinerInfo &DCI) const {
9612 switch(N->getOpcode()) {
9613 default: break;
9614 case ISD::ZERO_EXTEND: return combineZERO_EXTEND(N, DCI);
9615 case ISD::SIGN_EXTEND: return combineSIGN_EXTEND(N, DCI);
9616 case ISD::SIGN_EXTEND_INREG: return combineSIGN_EXTEND_INREG(N, DCI);
9617 case SystemZISD::MERGE_HIGH:
9618 case SystemZISD::MERGE_LOW: return combineMERGE(N, DCI);
9619 case ISD::LOAD: return combineLOAD(N, DCI);
9620 case ISD::STORE: return combineSTORE(N, DCI);
9621 case ISD::VECTOR_SHUFFLE: return combineVECTOR_SHUFFLE(N, DCI);
9622 case ISD::EXTRACT_VECTOR_ELT: return combineEXTRACT_VECTOR_ELT(N, DCI);
9623 case SystemZISD::JOIN_DWORDS: return combineJOIN_DWORDS(N, DCI);
9625 case ISD::FP_ROUND: return combineFP_ROUND(N, DCI);
9627 case ISD::FP_EXTEND: return combineFP_EXTEND(N, DCI);
9628 case ISD::SINT_TO_FP:
9629 case ISD::UINT_TO_FP: return combineINT_TO_FP(N, DCI);
9630 case ISD::FCOPYSIGN: return combineFCOPYSIGN(N, DCI);
9631 case ISD::BSWAP: return combineBSWAP(N, DCI);
9632 case ISD::SETCC: return combineSETCC(N, DCI);
9633 case SystemZISD::BR_CCMASK: return combineBR_CCMASK(N, DCI);
9634 case SystemZISD::SELECT_CCMASK: return combineSELECT_CCMASK(N, DCI);
9635 case SystemZISD::GET_CCMASK: return combineGET_CCMASK(N, DCI);
9636 case ISD::SRL:
9637 case ISD::SRA: return combineShiftToMulAddHigh(N, DCI);
9638 case ISD::MUL: return combineMUL(N, DCI);
9639 case ISD::SDIV:
9640 case ISD::UDIV:
9641 case ISD::SREM:
9642 case ISD::UREM: return combineIntDIVREM(N, DCI);
9644 case ISD::INTRINSIC_VOID: return combineINTRINSIC(N, DCI);
9645 }
9646
9647 return SDValue();
9648}
9649
9650// Return the demanded elements for the OpNo source operand of Op. DemandedElts
9651// are for Op.
9652static APInt getDemandedSrcElements(SDValue Op, const APInt &DemandedElts,
9653 unsigned OpNo) {
9654 EVT VT = Op.getValueType();
9655 unsigned NumElts = (VT.isVector() ? VT.getVectorNumElements() : 1);
9656 APInt SrcDemE;
9657 unsigned Opcode = Op.getOpcode();
9658 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
9659 unsigned Id = Op.getConstantOperandVal(0);
9660 switch (Id) {
9661 case Intrinsic::s390_vpksh: // PACKS
9662 case Intrinsic::s390_vpksf:
9663 case Intrinsic::s390_vpksg:
9664 case Intrinsic::s390_vpkshs: // PACKS_CC
9665 case Intrinsic::s390_vpksfs:
9666 case Intrinsic::s390_vpksgs:
9667 case Intrinsic::s390_vpklsh: // PACKLS
9668 case Intrinsic::s390_vpklsf:
9669 case Intrinsic::s390_vpklsg:
9670 case Intrinsic::s390_vpklshs: // PACKLS_CC
9671 case Intrinsic::s390_vpklsfs:
9672 case Intrinsic::s390_vpklsgs:
9673 // VECTOR PACK truncates the elements of two source vectors into one.
9674 SrcDemE = DemandedElts;
9675 if (OpNo == 2)
9676 SrcDemE.lshrInPlace(NumElts / 2);
9677 SrcDemE = SrcDemE.trunc(NumElts / 2);
9678 break;
9679 // VECTOR UNPACK extends half the elements of the source vector.
9680 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
9681 case Intrinsic::s390_vuphh:
9682 case Intrinsic::s390_vuphf:
9683 case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH
9684 case Intrinsic::s390_vuplhh:
9685 case Intrinsic::s390_vuplhf:
9686 SrcDemE = APInt(NumElts * 2, 0);
9687 SrcDemE.insertBits(DemandedElts, 0);
9688 break;
9689 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
9690 case Intrinsic::s390_vuplhw:
9691 case Intrinsic::s390_vuplf:
9692 case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW
9693 case Intrinsic::s390_vupllh:
9694 case Intrinsic::s390_vupllf:
9695 SrcDemE = APInt(NumElts * 2, 0);
9696 SrcDemE.insertBits(DemandedElts, NumElts);
9697 break;
9698 case Intrinsic::s390_vpdi: {
9699 // VECTOR PERMUTE DWORD IMMEDIATE selects one element from each source.
9700 SrcDemE = APInt(NumElts, 0);
9701 if (!DemandedElts[OpNo - 1])
9702 break;
9703 unsigned Mask = Op.getConstantOperandVal(3);
9704 unsigned MaskBit = ((OpNo - 1) ? 1 : 4);
9705 // Demand input element 0 or 1, given by the mask bit value.
9706 SrcDemE.setBit((Mask & MaskBit)? 1 : 0);
9707 break;
9708 }
9709 case Intrinsic::s390_vsldb: {
9710 // VECTOR SHIFT LEFT DOUBLE BY BYTE
9711 assert(VT == MVT::v16i8 && "Unexpected type.");
9712 unsigned FirstIdx = Op.getConstantOperandVal(3);
9713 assert (FirstIdx > 0 && FirstIdx < 16 && "Unused operand.");
9714 unsigned NumSrc0Els = 16 - FirstIdx;
9715 SrcDemE = APInt(NumElts, 0);
9716 if (OpNo == 1) {
9717 APInt DemEls = DemandedElts.trunc(NumSrc0Els);
9718 SrcDemE.insertBits(DemEls, FirstIdx);
9719 } else {
9720 APInt DemEls = DemandedElts.lshr(NumSrc0Els);
9721 SrcDemE.insertBits(DemEls, 0);
9722 }
9723 break;
9724 }
9725 case Intrinsic::s390_vperm:
9726 SrcDemE = APInt::getAllOnes(NumElts);
9727 break;
9728 default:
9729 llvm_unreachable("Unhandled intrinsic.");
9730 break;
9731 }
9732 } else {
9733 switch (Opcode) {
9734 case SystemZISD::JOIN_DWORDS:
9735 // Scalar operand.
9736 SrcDemE = APInt(1, 1);
9737 break;
9738 case SystemZISD::SELECT_CCMASK:
9739 SrcDemE = DemandedElts;
9740 break;
9741 default:
9742 llvm_unreachable("Unhandled opcode.");
9743 break;
9744 }
9745 }
9746 return SrcDemE;
9747}
9748
9750 const APInt &DemandedElts,
9751 const SelectionDAG &DAG, unsigned Depth,
9752 unsigned OpNo) {
9753 APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo);
9754 APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1);
9755 KnownBits LHSKnown =
9756 DAG.computeKnownBits(Op.getOperand(OpNo), Src0DemE, Depth + 1);
9757 KnownBits RHSKnown =
9758 DAG.computeKnownBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1);
9759 Known = LHSKnown.intersectWith(RHSKnown);
9760}
9761
9762void
9765 const APInt &DemandedElts,
9766 const SelectionDAG &DAG,
9767 unsigned Depth) const {
9768 Known.resetAll();
9769
9770 // Intrinsic CC result is returned in the two low bits.
9771 unsigned Tmp0, Tmp1; // not used
9772 if (Op.getResNo() == 1 && isIntrinsicWithCC(Op, Tmp0, Tmp1)) {
9773 Known.Zero.setBitsFrom(2);
9774 return;
9775 }
9776 [[maybe_unused]] EVT VT = Op.getValueType();
9777 if (Op.getResNo() != 0)
9778 return;
9779 assert (Known.getBitWidth() == VT.getScalarSizeInBits() &&
9780 "KnownBits does not match VT in bitwidth");
9781 assert ((!VT.isVector() ||
9782 (DemandedElts.getBitWidth() == VT.getVectorNumElements())) &&
9783 "DemandedElts does not match VT number of elements");
9784 unsigned BitWidth = Known.getBitWidth();
9785 unsigned Opcode = Op.getOpcode();
9786 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
9787 bool IsLogical = false;
9788 unsigned Id = Op.getConstantOperandVal(0);
9789 switch (Id) {
9790 case Intrinsic::s390_vpksh: // PACKS
9791 case Intrinsic::s390_vpksf:
9792 case Intrinsic::s390_vpksg:
9793 case Intrinsic::s390_vpkshs: // PACKS_CC
9794 case Intrinsic::s390_vpksfs:
9795 case Intrinsic::s390_vpksgs:
9796 case Intrinsic::s390_vpklsh: // PACKLS
9797 case Intrinsic::s390_vpklsf:
9798 case Intrinsic::s390_vpklsg:
9799 case Intrinsic::s390_vpklshs: // PACKLS_CC
9800 case Intrinsic::s390_vpklsfs:
9801 case Intrinsic::s390_vpklsgs:
9802 case Intrinsic::s390_vpdi:
9803 case Intrinsic::s390_vsldb:
9804 case Intrinsic::s390_vperm:
9805 computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 1);
9806 break;
9807 case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH
9808 case Intrinsic::s390_vuplhh:
9809 case Intrinsic::s390_vuplhf:
9810 case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW
9811 case Intrinsic::s390_vupllh:
9812 case Intrinsic::s390_vupllf:
9813 IsLogical = true;
9814 [[fallthrough]];
9815 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
9816 case Intrinsic::s390_vuphh:
9817 case Intrinsic::s390_vuphf:
9818 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
9819 case Intrinsic::s390_vuplhw:
9820 case Intrinsic::s390_vuplf: {
9821 SDValue SrcOp = Op.getOperand(1);
9822 APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 0);
9823 Known = DAG.computeKnownBits(SrcOp, SrcDemE, Depth + 1);
9824 if (IsLogical) {
9825 Known = Known.zext(BitWidth);
9826 } else
9827 Known = Known.sext(BitWidth);
9828 break;
9829 }
9830 default:
9831 break;
9832 }
9833 } else {
9834 switch (Opcode) {
9835 case SystemZISD::JOIN_DWORDS:
9836 case SystemZISD::SELECT_CCMASK:
9837 computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 0);
9838 break;
9839 case SystemZISD::REPLICATE: {
9840 SDValue SrcOp = Op.getOperand(0);
9841 Known = DAG.computeKnownBits(SrcOp, Depth + 1);
9842 if (Known.getBitWidth() < BitWidth && isa<ConstantSDNode>(SrcOp))
9843 Known = Known.sext(BitWidth); // VREPI sign extends the immedate.
9844 break;
9845 }
9846 default:
9847 break;
9848 }
9849 }
9850
9851 // Known has the width of the source operand(s). Adjust if needed to match
9852 // the passed bitwidth.
9853 if (Known.getBitWidth() != BitWidth)
9854 Known = Known.anyextOrTrunc(BitWidth);
9855}
9856
9857static unsigned computeNumSignBitsBinOp(SDValue Op, const APInt &DemandedElts,
9858 const SelectionDAG &DAG, unsigned Depth,
9859 unsigned OpNo) {
9860 APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo);
9861 unsigned LHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo), Src0DemE, Depth + 1);
9862 if (LHS == 1) return 1; // Early out.
9863 APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1);
9864 unsigned RHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1);
9865 if (RHS == 1) return 1; // Early out.
9866 unsigned Common = std::min(LHS, RHS);
9867 unsigned SrcBitWidth = Op.getOperand(OpNo).getScalarValueSizeInBits();
9868 EVT VT = Op.getValueType();
9869 unsigned VTBits = VT.getScalarSizeInBits();
9870 if (SrcBitWidth > VTBits) { // PACK
9871 unsigned SrcExtraBits = SrcBitWidth - VTBits;
9872 if (Common > SrcExtraBits)
9873 return (Common - SrcExtraBits);
9874 return 1;
9875 }
9876 assert (SrcBitWidth == VTBits && "Expected operands of same bitwidth.");
9877 return Common;
9878}
9879
9880unsigned
9882 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9883 unsigned Depth) const {
9884 if (Op.getResNo() != 0)
9885 return 1;
9886 unsigned Opcode = Op.getOpcode();
9887 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
9888 unsigned Id = Op.getConstantOperandVal(0);
9889 switch (Id) {
9890 case Intrinsic::s390_vpksh: // PACKS
9891 case Intrinsic::s390_vpksf:
9892 case Intrinsic::s390_vpksg:
9893 case Intrinsic::s390_vpkshs: // PACKS_CC
9894 case Intrinsic::s390_vpksfs:
9895 case Intrinsic::s390_vpksgs:
9896 case Intrinsic::s390_vpklsh: // PACKLS
9897 case Intrinsic::s390_vpklsf:
9898 case Intrinsic::s390_vpklsg:
9899 case Intrinsic::s390_vpklshs: // PACKLS_CC
9900 case Intrinsic::s390_vpklsfs:
9901 case Intrinsic::s390_vpklsgs:
9902 case Intrinsic::s390_vpdi:
9903 case Intrinsic::s390_vsldb:
9904 case Intrinsic::s390_vperm:
9905 return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 1);
9906 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
9907 case Intrinsic::s390_vuphh:
9908 case Intrinsic::s390_vuphf:
9909 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
9910 case Intrinsic::s390_vuplhw:
9911 case Intrinsic::s390_vuplf: {
9912 SDValue PackedOp = Op.getOperand(1);
9913 APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 1);
9914 unsigned Tmp = DAG.ComputeNumSignBits(PackedOp, SrcDemE, Depth + 1);
9915 EVT VT = Op.getValueType();
9916 unsigned VTBits = VT.getScalarSizeInBits();
9917 Tmp += VTBits - PackedOp.getScalarValueSizeInBits();
9918 return Tmp;
9919 }
9920 default:
9921 break;
9922 }
9923 } else {
9924 switch (Opcode) {
9925 case SystemZISD::SELECT_CCMASK:
9926 return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 0);
9927 default:
9928 break;
9929 }
9930 }
9931
9932 return 1;
9933}
9934
9936 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9937 UndefPoisonKind Kind, unsigned Depth) const {
9938 switch (Op->getOpcode()) {
9939 case SystemZISD::PCREL_WRAPPER:
9940 case SystemZISD::PCREL_OFFSET:
9941 return true;
9942 }
9943 return false;
9944}
9945
9946unsigned
9948 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
9949 unsigned StackAlign = TFI->getStackAlignment();
9950 assert(StackAlign >=1 && isPowerOf2_32(StackAlign) &&
9951 "Unexpected stack alignment");
9952 // The default stack probe size is 4096 if the function has no
9953 // stack-probe-size attribute.
9954 unsigned StackProbeSize =
9955 MF.getFunction().getFnAttributeAsParsedInteger("stack-probe-size", 4096);
9956 // Round down to the stack alignment.
9957 StackProbeSize &= ~(StackAlign - 1);
9958 return StackProbeSize ? StackProbeSize : StackAlign;
9959}
9960
9961//===----------------------------------------------------------------------===//
9962// Custom insertion
9963//===----------------------------------------------------------------------===//
9964
9965// Force base value Base into a register before MI. Return the register.
9967 const SystemZInstrInfo *TII) {
9968 MachineBasicBlock *MBB = MI.getParent();
9969 MachineFunction &MF = *MBB->getParent();
9971
9972 if (Base.isReg()) {
9973 // Copy Base into a new virtual register to help register coalescing in
9974 // cases with multiple uses.
9975 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
9976 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::COPY), Reg)
9977 .add(Base);
9978 return Reg;
9979 }
9980
9981 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
9982 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LA), Reg)
9983 .add(Base)
9984 .addImm(0)
9985 .addReg(0);
9986 return Reg;
9987}
9988
9989// The CC operand of MI might be missing a kill marker because there
9990// were multiple uses of CC, and ISel didn't know which to mark.
9991// Figure out whether MI should have had a kill marker.
9993 // Scan forward through BB for a use/def of CC.
9995 for (MachineBasicBlock::iterator miE = MBB->end(); miI != miE; ++miI) {
9996 const MachineInstr &MI = *miI;
9997 if (MI.readsRegister(SystemZ::CC, /*TRI=*/nullptr))
9998 return false;
9999 if (MI.definesRegister(SystemZ::CC, /*TRI=*/nullptr))
10000 break; // Should have kill-flag - update below.
10001 }
10002
10003 // If we hit the end of the block, check whether CC is live into a
10004 // successor.
10005 if (miI == MBB->end()) {
10006 for (const MachineBasicBlock *Succ : MBB->successors())
10007 if (Succ->isLiveIn(SystemZ::CC))
10008 return false;
10009 }
10010
10011 return true;
10012}
10013
10014// Return true if it is OK for this Select pseudo-opcode to be cascaded
10015// together with other Select pseudo-opcodes into a single basic-block with
10016// a conditional jump around it.
10018 switch (MI.getOpcode()) {
10019 case SystemZ::Select32:
10020 case SystemZ::Select64:
10021 case SystemZ::Select128:
10022 case SystemZ::SelectF32:
10023 case SystemZ::SelectF64:
10024 case SystemZ::SelectF128:
10025 case SystemZ::SelectVR32:
10026 case SystemZ::SelectVR64:
10027 case SystemZ::SelectVR128:
10028 return true;
10029
10030 default:
10031 return false;
10032 }
10033}
10034
10035// Helper function, which inserts PHI functions into SinkMBB:
10036// %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ],
10037// where %FalseValue(i) and %TrueValue(i) are taken from Selects.
10039 MachineBasicBlock *TrueMBB,
10040 MachineBasicBlock *FalseMBB,
10041 MachineBasicBlock *SinkMBB) {
10042 MachineFunction *MF = TrueMBB->getParent();
10044
10045 MachineInstr *FirstMI = Selects.front();
10046 unsigned CCValid = FirstMI->getOperand(3).getImm();
10047 unsigned CCMask = FirstMI->getOperand(4).getImm();
10048
10049 MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
10050
10051 // As we are creating the PHIs, we have to be careful if there is more than
10052 // one. Later Selects may reference the results of earlier Selects, but later
10053 // PHIs have to reference the individual true/false inputs from earlier PHIs.
10054 // That also means that PHI construction must work forward from earlier to
10055 // later, and that the code must maintain a mapping from earlier PHI's
10056 // destination registers, and the registers that went into the PHI.
10058
10059 for (auto *MI : Selects) {
10060 Register DestReg = MI->getOperand(0).getReg();
10061 Register TrueReg = MI->getOperand(1).getReg();
10062 Register FalseReg = MI->getOperand(2).getReg();
10063
10064 // If this Select we are generating is the opposite condition from
10065 // the jump we generated, then we have to swap the operands for the
10066 // PHI that is going to be generated.
10067 if (MI->getOperand(4).getImm() == (CCValid ^ CCMask))
10068 std::swap(TrueReg, FalseReg);
10069
10070 if (auto It = RegRewriteTable.find(TrueReg); It != RegRewriteTable.end())
10071 TrueReg = It->second.first;
10072
10073 if (auto It = RegRewriteTable.find(FalseReg); It != RegRewriteTable.end())
10074 FalseReg = It->second.second;
10075
10076 DebugLoc DL = MI->getDebugLoc();
10077 BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(SystemZ::PHI), DestReg)
10078 .addReg(TrueReg).addMBB(TrueMBB)
10079 .addReg(FalseReg).addMBB(FalseMBB);
10080
10081 // Add this PHI to the rewrite table.
10082 RegRewriteTable[DestReg] = std::make_pair(TrueReg, FalseReg);
10083 }
10084
10085 MF->getProperties().resetNoPHIs();
10086}
10087
10089SystemZTargetLowering::emitAdjCallStack(MachineInstr &MI,
10090 MachineBasicBlock *BB) const {
10091 MachineFunction &MF = *BB->getParent();
10092 MachineFrameInfo &MFI = MF.getFrameInfo();
10093 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
10094 assert(TFL->hasReservedCallFrame(MF) &&
10095 "ADJSTACKDOWN and ADJSTACKUP should be no-ops");
10096 (void)TFL;
10097 // Get the MaxCallFrameSize value and erase MI since it serves no further
10098 // purpose as the call frame is statically reserved in the prolog. Set
10099 // AdjustsStack as MI is *not* mapped as a frame instruction.
10100 uint32_t NumBytes = MI.getOperand(0).getImm();
10101 if (NumBytes > MFI.getMaxCallFrameSize())
10102 MFI.setMaxCallFrameSize(NumBytes);
10103 MFI.setAdjustsStack(true);
10104
10105 MI.eraseFromParent();
10106 return BB;
10107}
10108
10109// Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
10111SystemZTargetLowering::emitSelect(MachineInstr &MI,
10112 MachineBasicBlock *MBB) const {
10113 assert(isSelectPseudo(MI) && "Bad call to emitSelect()");
10114 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10115
10116 unsigned CCValid = MI.getOperand(3).getImm();
10117 unsigned CCMask = MI.getOperand(4).getImm();
10118
10119 // If we have a sequence of Select* pseudo instructions using the
10120 // same condition code value, we want to expand all of them into
10121 // a single pair of basic blocks using the same condition.
10122 SmallVector<MachineInstr*, 8> Selects;
10123 SmallVector<MachineInstr*, 8> DbgValues;
10124 Selects.push_back(&MI);
10125 unsigned Count = 0;
10126 for (MachineInstr &NextMI : llvm::make_range(
10127 std::next(MachineBasicBlock::iterator(MI)), MBB->end())) {
10128 if (isSelectPseudo(NextMI)) {
10129 assert(NextMI.getOperand(3).getImm() == CCValid &&
10130 "Bad CCValid operands since CC was not redefined.");
10131 if (NextMI.getOperand(4).getImm() == CCMask ||
10132 NextMI.getOperand(4).getImm() == (CCValid ^ CCMask)) {
10133 Selects.push_back(&NextMI);
10134 continue;
10135 }
10136 break;
10137 }
10138 if (NextMI.definesRegister(SystemZ::CC, /*TRI=*/nullptr) ||
10139 NextMI.usesCustomInsertionHook())
10140 break;
10141 bool User = false;
10142 for (auto *SelMI : Selects)
10143 if (NextMI.readsVirtualRegister(SelMI->getOperand(0).getReg())) {
10144 User = true;
10145 break;
10146 }
10147 if (NextMI.isDebugInstr()) {
10148 if (User) {
10149 assert(NextMI.isDebugValue() && "Unhandled debug opcode.");
10150 DbgValues.push_back(&NextMI);
10151 }
10152 } else if (User || ++Count > 20)
10153 break;
10154 }
10155
10156 MachineInstr *LastMI = Selects.back();
10157 bool CCKilled = (LastMI->killsRegister(SystemZ::CC, /*TRI=*/nullptr) ||
10158 checkCCKill(*LastMI, MBB));
10159 MachineBasicBlock *StartMBB = MBB;
10160 MachineBasicBlock *JoinMBB = SystemZ::splitBlockAfter(LastMI, MBB);
10161 MachineBasicBlock *FalseMBB = SystemZ::emitBlockAfter(StartMBB);
10162
10163 // Unless CC was killed in the last Select instruction, mark it as
10164 // live-in to both FalseMBB and JoinMBB.
10165 if (!CCKilled) {
10166 FalseMBB->addLiveIn(SystemZ::CC);
10167 JoinMBB->addLiveIn(SystemZ::CC);
10168 }
10169
10170 // StartMBB:
10171 // BRC CCMask, JoinMBB
10172 // # fallthrough to FalseMBB
10173 MBB = StartMBB;
10174 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::BRC))
10175 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
10176 MBB->addSuccessor(JoinMBB);
10177 MBB->addSuccessor(FalseMBB);
10178
10179 // FalseMBB:
10180 // # fallthrough to JoinMBB
10181 MBB = FalseMBB;
10182 MBB->addSuccessor(JoinMBB);
10183
10184 // JoinMBB:
10185 // %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
10186 // ...
10187 MBB = JoinMBB;
10188 createPHIsForSelects(Selects, StartMBB, FalseMBB, MBB);
10189 for (auto *SelMI : Selects)
10190 SelMI->eraseFromParent();
10191
10193 for (auto *DbgMI : DbgValues)
10194 MBB->splice(InsertPos, StartMBB, DbgMI);
10195
10196 return JoinMBB;
10197}
10198
10199// Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
10200// StoreOpcode is the store to use and Invert says whether the store should
10201// happen when the condition is false rather than true. If a STORE ON
10202// CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
10203MachineBasicBlock *SystemZTargetLowering::emitCondStore(MachineInstr &MI,
10205 unsigned StoreOpcode,
10206 unsigned STOCOpcode,
10207 bool Invert) const {
10208 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10209
10210 Register SrcReg = MI.getOperand(0).getReg();
10211 MachineOperand Base = MI.getOperand(1);
10212 int64_t Disp = MI.getOperand(2).getImm();
10213 Register IndexReg = MI.getOperand(3).getReg();
10214 unsigned CCValid = MI.getOperand(4).getImm();
10215 unsigned CCMask = MI.getOperand(5).getImm();
10216 DebugLoc DL = MI.getDebugLoc();
10217
10218 StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
10219
10220 // ISel pattern matching also adds a load memory operand of the same
10221 // address, so take special care to find the storing memory operand.
10222 MachineMemOperand *MMO = nullptr;
10223 for (auto *I : MI.memoperands())
10224 if (I->isStore()) {
10225 MMO = I;
10226 break;
10227 }
10228
10229 // Use STOCOpcode if possible. We could use different store patterns in
10230 // order to avoid matching the index register, but the performance trade-offs
10231 // might be more complicated in that case.
10232 if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) {
10233 if (Invert)
10234 CCMask ^= CCValid;
10235
10236 BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
10237 .addReg(SrcReg)
10238 .add(Base)
10239 .addImm(Disp)
10240 .addImm(CCValid)
10241 .addImm(CCMask)
10242 .addMemOperand(MMO);
10243
10244 MI.eraseFromParent();
10245 return MBB;
10246 }
10247
10248 // Get the condition needed to branch around the store.
10249 if (!Invert)
10250 CCMask ^= CCValid;
10251
10252 MachineBasicBlock *StartMBB = MBB;
10253 MachineBasicBlock *JoinMBB = SystemZ::splitBlockBefore(MI, MBB);
10254 MachineBasicBlock *FalseMBB = SystemZ::emitBlockAfter(StartMBB);
10255
10256 // Unless CC was killed in the CondStore instruction, mark it as
10257 // live-in to both FalseMBB and JoinMBB.
10258 if (!MI.killsRegister(SystemZ::CC, /*TRI=*/nullptr) &&
10259 !checkCCKill(MI, JoinMBB)) {
10260 FalseMBB->addLiveIn(SystemZ::CC);
10261 JoinMBB->addLiveIn(SystemZ::CC);
10262 }
10263
10264 // StartMBB:
10265 // BRC CCMask, JoinMBB
10266 // # fallthrough to FalseMBB
10267 MBB = StartMBB;
10268 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10269 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
10270 MBB->addSuccessor(JoinMBB);
10271 MBB->addSuccessor(FalseMBB);
10272
10273 // FalseMBB:
10274 // store %SrcReg, %Disp(%Index,%Base)
10275 // # fallthrough to JoinMBB
10276 MBB = FalseMBB;
10277 BuildMI(MBB, DL, TII->get(StoreOpcode))
10278 .addReg(SrcReg)
10279 .add(Base)
10280 .addImm(Disp)
10281 .addReg(IndexReg)
10282 .addMemOperand(MMO);
10283 MBB->addSuccessor(JoinMBB);
10284
10285 MI.eraseFromParent();
10286 return JoinMBB;
10287}
10288
10289// Implement EmitInstrWithCustomInserter for pseudo [SU]Cmp128Hi instruction MI.
10291SystemZTargetLowering::emitICmp128Hi(MachineInstr &MI,
10293 bool Unsigned) const {
10294 MachineFunction &MF = *MBB->getParent();
10295 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10296 MachineRegisterInfo &MRI = MF.getRegInfo();
10297
10298 // Synthetic instruction to compare 128-bit values.
10299 // Sets CC 1 if Op0 > Op1, sets a different CC otherwise.
10300 Register Op0 = MI.getOperand(0).getReg();
10301 Register Op1 = MI.getOperand(1).getReg();
10302
10303 MachineBasicBlock *StartMBB = MBB;
10304 MachineBasicBlock *JoinMBB = SystemZ::splitBlockAfter(MI, MBB);
10305 MachineBasicBlock *HiEqMBB = SystemZ::emitBlockAfter(StartMBB);
10306
10307 // StartMBB:
10308 //
10309 // Use VECTOR ELEMENT COMPARE [LOGICAL] to compare the high parts.
10310 // Swap the inputs to get:
10311 // CC 1 if high(Op0) > high(Op1)
10312 // CC 2 if high(Op0) < high(Op1)
10313 // CC 0 if high(Op0) == high(Op1)
10314 //
10315 // If CC != 0, we'd done, so jump over the next instruction.
10316 //
10317 // VEC[L]G Op1, Op0
10318 // JNE JoinMBB
10319 // # fallthrough to HiEqMBB
10320 MBB = StartMBB;
10321 int HiOpcode = Unsigned? SystemZ::VECLG : SystemZ::VECG;
10322 BuildMI(MBB, MI.getDebugLoc(), TII->get(HiOpcode))
10323 .addReg(Op1).addReg(Op0);
10324 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::BRC))
10326 MBB->addSuccessor(JoinMBB);
10327 MBB->addSuccessor(HiEqMBB);
10328
10329 // HiEqMBB:
10330 //
10331 // Otherwise, use VECTOR COMPARE HIGH LOGICAL.
10332 // Since we already know the high parts are equal, the CC
10333 // result will only depend on the low parts:
10334 // CC 1 if low(Op0) > low(Op1)
10335 // CC 3 if low(Op0) <= low(Op1)
10336 //
10337 // VCHLGS Tmp, Op0, Op1
10338 // # fallthrough to JoinMBB
10339 MBB = HiEqMBB;
10340 Register Temp = MRI.createVirtualRegister(&SystemZ::VR128BitRegClass);
10341 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::VCHLGS), Temp)
10342 .addReg(Op0).addReg(Op1);
10343 MBB->addSuccessor(JoinMBB);
10344
10345 // Mark CC as live-in to JoinMBB.
10346 JoinMBB->addLiveIn(SystemZ::CC);
10347
10348 MI.eraseFromParent();
10349 return JoinMBB;
10350}
10351
10352// Implement EmitInstrWithCustomInserter for subword pseudo ATOMIC_LOADW_* or
10353// ATOMIC_SWAPW instruction MI. BinOpcode is the instruction that performs
10354// the binary operation elided by "*", or 0 for ATOMIC_SWAPW. Invert says
10355// whether the field should be inverted after performing BinOpcode (e.g. for
10356// NAND).
10357MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadBinary(
10358 MachineInstr &MI, MachineBasicBlock *MBB, unsigned BinOpcode,
10359 bool Invert) const {
10360 MachineFunction &MF = *MBB->getParent();
10361 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10362 MachineRegisterInfo &MRI = MF.getRegInfo();
10363
10364 // Extract the operands. Base can be a register or a frame index.
10365 // Src2 can be a register or immediate.
10366 Register Dest = MI.getOperand(0).getReg();
10367 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
10368 int64_t Disp = MI.getOperand(2).getImm();
10369 MachineOperand Src2 = earlyUseOperand(MI.getOperand(3));
10370 Register BitShift = MI.getOperand(4).getReg();
10371 Register NegBitShift = MI.getOperand(5).getReg();
10372 unsigned BitSize = MI.getOperand(6).getImm();
10373 DebugLoc DL = MI.getDebugLoc();
10374
10375 // Get the right opcodes for the displacement.
10376 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
10377 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
10378 assert(LOpcode && CSOpcode && "Displacement out of range");
10379
10380 // Create virtual registers for temporary results.
10381 Register OrigVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10382 Register OldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10383 Register NewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10384 Register RotatedOldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10385 Register RotatedNewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10386
10387 // Insert a basic block for the main loop.
10388 MachineBasicBlock *StartMBB = MBB;
10389 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10390 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10391
10392 // StartMBB:
10393 // ...
10394 // %OrigVal = L Disp(%Base)
10395 // # fall through to LoopMBB
10396 MBB = StartMBB;
10397 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
10398 MBB->addSuccessor(LoopMBB);
10399
10400 // LoopMBB:
10401 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
10402 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
10403 // %RotatedNewVal = OP %RotatedOldVal, %Src2
10404 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
10405 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
10406 // JNE LoopMBB
10407 // # fall through to DoneMBB
10408 MBB = LoopMBB;
10409 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
10410 .addReg(OrigVal).addMBB(StartMBB)
10411 .addReg(Dest).addMBB(LoopMBB);
10412 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
10413 .addReg(OldVal).addReg(BitShift).addImm(0);
10414 if (Invert) {
10415 // Perform the operation normally and then invert every bit of the field.
10416 Register Tmp = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10417 BuildMI(MBB, DL, TII->get(BinOpcode), Tmp)
10418 .addReg(RotatedOldVal)
10419 .add(Src2)
10420 .setOperandDead(3);
10421 // XILF with the upper BitSize bits set.
10422 BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
10423 .addReg(Tmp)
10424 .addImm(-1U << (32 - BitSize))
10425 .setOperandDead(3);
10426 } else if (BinOpcode)
10427 // A simply binary operation.
10428 BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
10429 .addReg(RotatedOldVal)
10430 .add(Src2)
10431 .setOperandDead(3);
10432 else
10433 // Use RISBG to rotate Src2 into position and use it to replace the
10434 // field in RotatedOldVal.
10435 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
10436 .addReg(RotatedOldVal)
10437 .addReg(Src2.getReg())
10438 .addImm(32)
10439 .addImm(31 + BitSize)
10440 .addImm(32 - BitSize)
10441 .setOperandDead(6);
10442 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
10443 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
10444 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
10445 .addReg(OldVal)
10446 .addReg(NewVal)
10447 .add(Base)
10448 .addImm(Disp);
10449 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10451 MBB->addSuccessor(LoopMBB);
10452 MBB->addSuccessor(DoneMBB);
10453
10454 MI.eraseFromParent();
10455 return DoneMBB;
10456}
10457
10458// Implement EmitInstrWithCustomInserter for subword pseudo
10459// ATOMIC_LOADW_{,U}{MIN,MAX} instruction MI. CompareOpcode is the
10460// instruction that should be used to compare the current field with the
10461// minimum or maximum value. KeepOldMask is the BRC condition-code mask
10462// for when the current field should be kept.
10463MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadMinMax(
10464 MachineInstr &MI, MachineBasicBlock *MBB, unsigned CompareOpcode,
10465 unsigned KeepOldMask) const {
10466 MachineFunction &MF = *MBB->getParent();
10467 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10468 MachineRegisterInfo &MRI = MF.getRegInfo();
10469
10470 // Extract the operands. Base can be a register or a frame index.
10471 Register Dest = MI.getOperand(0).getReg();
10472 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
10473 int64_t Disp = MI.getOperand(2).getImm();
10474 Register Src2 = MI.getOperand(3).getReg();
10475 Register BitShift = MI.getOperand(4).getReg();
10476 Register NegBitShift = MI.getOperand(5).getReg();
10477 unsigned BitSize = MI.getOperand(6).getImm();
10478 DebugLoc DL = MI.getDebugLoc();
10479
10480 // Get the right opcodes for the displacement.
10481 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
10482 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
10483 assert(LOpcode && CSOpcode && "Displacement out of range");
10484
10485 // Create virtual registers for temporary results.
10486 Register OrigVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10487 Register OldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10488 Register NewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10489 Register RotatedOldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10490 Register RotatedAltVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10491 Register RotatedNewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10492
10493 // Insert 3 basic blocks for the loop.
10494 MachineBasicBlock *StartMBB = MBB;
10495 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10496 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10497 MachineBasicBlock *UseAltMBB = SystemZ::emitBlockAfter(LoopMBB);
10498 MachineBasicBlock *UpdateMBB = SystemZ::emitBlockAfter(UseAltMBB);
10499
10500 // StartMBB:
10501 // ...
10502 // %OrigVal = L Disp(%Base)
10503 // # fall through to LoopMBB
10504 MBB = StartMBB;
10505 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
10506 MBB->addSuccessor(LoopMBB);
10507
10508 // LoopMBB:
10509 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
10510 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
10511 // CompareOpcode %RotatedOldVal, %Src2
10512 // BRC KeepOldMask, UpdateMBB
10513 MBB = LoopMBB;
10514 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
10515 .addReg(OrigVal).addMBB(StartMBB)
10516 .addReg(Dest).addMBB(UpdateMBB);
10517 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
10518 .addReg(OldVal).addReg(BitShift).addImm(0);
10519 BuildMI(MBB, DL, TII->get(CompareOpcode))
10520 .addReg(RotatedOldVal).addReg(Src2);
10521 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10522 .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
10523 MBB->addSuccessor(UpdateMBB);
10524 MBB->addSuccessor(UseAltMBB);
10525
10526 // UseAltMBB:
10527 // %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
10528 // # fall through to UpdateMBB
10529 MBB = UseAltMBB;
10530 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
10531 .addReg(RotatedOldVal)
10532 .addReg(Src2)
10533 .addImm(32)
10534 .addImm(31 + BitSize)
10535 .addImm(0)
10536 .setOperandDead(6);
10537 MBB->addSuccessor(UpdateMBB);
10538
10539 // UpdateMBB:
10540 // %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
10541 // [ %RotatedAltVal, UseAltMBB ]
10542 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
10543 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
10544 // JNE LoopMBB
10545 // # fall through to DoneMBB
10546 MBB = UpdateMBB;
10547 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
10548 .addReg(RotatedOldVal).addMBB(LoopMBB)
10549 .addReg(RotatedAltVal).addMBB(UseAltMBB);
10550 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
10551 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
10552 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
10553 .addReg(OldVal)
10554 .addReg(NewVal)
10555 .add(Base)
10556 .addImm(Disp);
10557 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10559 MBB->addSuccessor(LoopMBB);
10560 MBB->addSuccessor(DoneMBB);
10561
10562 MI.eraseFromParent();
10563 return DoneMBB;
10564}
10565
10566// Implement EmitInstrWithCustomInserter for subword pseudo ATOMIC_CMP_SWAPW
10567// instruction MI.
10569SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr &MI,
10570 MachineBasicBlock *MBB) const {
10571 MachineFunction &MF = *MBB->getParent();
10572 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10573 MachineRegisterInfo &MRI = MF.getRegInfo();
10574
10575 // Extract the operands. Base can be a register or a frame index.
10576 Register Dest = MI.getOperand(0).getReg();
10577 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
10578 int64_t Disp = MI.getOperand(2).getImm();
10579 Register CmpVal = MI.getOperand(3).getReg();
10580 Register OrigSwapVal = MI.getOperand(4).getReg();
10581 Register BitShift = MI.getOperand(5).getReg();
10582 Register NegBitShift = MI.getOperand(6).getReg();
10583 int64_t BitSize = MI.getOperand(7).getImm();
10584 DebugLoc DL = MI.getDebugLoc();
10585
10586 const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
10587
10588 // Get the right opcodes for the displacement and zero-extension.
10589 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
10590 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
10591 unsigned ZExtOpcode = BitSize == 8 ? SystemZ::LLCR : SystemZ::LLHR;
10592 assert(LOpcode && CSOpcode && "Displacement out of range");
10593
10594 // Create virtual registers for temporary results.
10595 Register OrigOldVal = MRI.createVirtualRegister(RC);
10596 Register OldVal = MRI.createVirtualRegister(RC);
10597 Register SwapVal = MRI.createVirtualRegister(RC);
10598 Register StoreVal = MRI.createVirtualRegister(RC);
10599 Register OldValRot = MRI.createVirtualRegister(RC);
10600 Register RetryOldVal = MRI.createVirtualRegister(RC);
10601 Register RetrySwapVal = MRI.createVirtualRegister(RC);
10602
10603 // Insert 2 basic blocks for the loop.
10604 MachineBasicBlock *StartMBB = MBB;
10605 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10606 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10607 MachineBasicBlock *SetMBB = SystemZ::emitBlockAfter(LoopMBB);
10608
10609 // StartMBB:
10610 // ...
10611 // %OrigOldVal = L Disp(%Base)
10612 // # fall through to LoopMBB
10613 MBB = StartMBB;
10614 BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
10615 .add(Base)
10616 .addImm(Disp)
10617 .addReg(0);
10618 MBB->addSuccessor(LoopMBB);
10619
10620 // LoopMBB:
10621 // %OldVal = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
10622 // %SwapVal = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
10623 // %OldValRot = RLL %OldVal, BitSize(%BitShift)
10624 // ^^ The low BitSize bits contain the field
10625 // of interest.
10626 // %RetrySwapVal = RISBG32 %SwapVal, %OldValRot, 32, 63-BitSize, 0
10627 // ^^ Replace the upper 32-BitSize bits of the
10628 // swap value with those that we loaded and rotated.
10629 // %Dest = LL[CH] %OldValRot
10630 // CR %Dest, %CmpVal
10631 // JNE DoneMBB
10632 // # Fall through to SetMBB
10633 MBB = LoopMBB;
10634 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
10635 .addReg(OrigOldVal).addMBB(StartMBB)
10636 .addReg(RetryOldVal).addMBB(SetMBB);
10637 BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
10638 .addReg(OrigSwapVal).addMBB(StartMBB)
10639 .addReg(RetrySwapVal).addMBB(SetMBB);
10640 BuildMI(MBB, DL, TII->get(SystemZ::RLL), OldValRot)
10641 .addReg(OldVal).addReg(BitShift).addImm(BitSize);
10642 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
10643 .addReg(SwapVal)
10644 .addReg(OldValRot)
10645 .addImm(32)
10646 .addImm(63 - BitSize)
10647 .addImm(0)
10648 .setOperandDead(6);
10649 BuildMI(MBB, DL, TII->get(ZExtOpcode), Dest)
10650 .addReg(OldValRot);
10651 BuildMI(MBB, DL, TII->get(SystemZ::CR))
10652 .addReg(Dest).addReg(CmpVal);
10653 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10656 MBB->addSuccessor(DoneMBB);
10657 MBB->addSuccessor(SetMBB);
10658
10659 // SetMBB:
10660 // %StoreVal = RLL %RetrySwapVal, -BitSize(%NegBitShift)
10661 // ^^ Rotate the new field to its proper position.
10662 // %RetryOldVal = CS %OldVal, %StoreVal, Disp(%Base)
10663 // JNE LoopMBB
10664 // # fall through to ExitMBB
10665 MBB = SetMBB;
10666 BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
10667 .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
10668 BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
10669 .addReg(OldVal)
10670 .addReg(StoreVal)
10671 .add(Base)
10672 .addImm(Disp);
10673 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10675 MBB->addSuccessor(LoopMBB);
10676 MBB->addSuccessor(DoneMBB);
10677
10678 // If the CC def wasn't dead in the ATOMIC_CMP_SWAPW, mark CC as live-in
10679 // to the block after the loop. At this point, CC may have been defined
10680 // either by the CR in LoopMBB or by the CS in SetMBB.
10681 if (!MI.registerDefIsDead(SystemZ::CC, /*TRI=*/nullptr))
10682 DoneMBB->addLiveIn(SystemZ::CC);
10683
10684 MI.eraseFromParent();
10685 return DoneMBB;
10686}
10687
10689SystemZTargetLowering::emitMemMemWrapper(MachineInstr &MI,
10691 unsigned Opcode, bool IsMemset) const {
10692 MachineFunction &MF = *MBB->getParent();
10693 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10694 MachineRegisterInfo &MRI = MF.getRegInfo();
10695 DebugLoc DL = MI.getDebugLoc();
10696
10697 MachineOperand DestBase = earlyUseOperand(MI.getOperand(0));
10698 uint64_t DestDisp = MI.getOperand(1).getImm();
10699 MachineOperand SrcBase = MachineOperand::CreateReg(0U, false);
10700 uint64_t SrcDisp;
10701
10702 // Fold the displacement Disp if it is out of range.
10703 auto foldDisplIfNeeded = [&](MachineOperand &Base, uint64_t &Disp) -> void {
10704 if (!isUInt<12>(Disp)) {
10705 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10706 unsigned Opcode = TII->getOpcodeForOffset(SystemZ::LA, Disp);
10707 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII->get(Opcode), Reg)
10708 .add(Base).addImm(Disp).addReg(0);
10710 Disp = 0;
10711 }
10712 };
10713
10714 if (!IsMemset) {
10715 SrcBase = earlyUseOperand(MI.getOperand(2));
10716 SrcDisp = MI.getOperand(3).getImm();
10717 } else {
10718 SrcBase = DestBase;
10719 SrcDisp = DestDisp++;
10720 foldDisplIfNeeded(DestBase, DestDisp);
10721 }
10722
10723 MachineOperand &LengthMO = MI.getOperand(IsMemset ? 2 : 4);
10724 bool IsImmForm = LengthMO.isImm();
10725 bool IsRegForm = !IsImmForm;
10726
10727 // Build and insert one Opcode of Length, with special treatment for memset.
10728 auto insertMemMemOp = [&](MachineBasicBlock *InsMBB,
10730 MachineOperand DBase, uint64_t DDisp,
10731 MachineOperand SBase, uint64_t SDisp,
10732 unsigned Length) -> void {
10733 assert(Length > 0 && Length <= 256 && "Building memory op with bad length.");
10734 if (IsMemset) {
10735 MachineOperand ByteMO = earlyUseOperand(MI.getOperand(3));
10736 if (ByteMO.isImm())
10737 BuildMI(*InsMBB, InsPos, DL, TII->get(SystemZ::MVI))
10738 .add(SBase).addImm(SDisp).add(ByteMO);
10739 else
10740 BuildMI(*InsMBB, InsPos, DL, TII->get(SystemZ::STC))
10741 .add(ByteMO).add(SBase).addImm(SDisp).addReg(0);
10742 if (--Length == 0)
10743 return;
10744 }
10745 BuildMI(*MBB, InsPos, DL, TII->get(Opcode))
10746 .add(DBase).addImm(DDisp).addImm(Length)
10747 .add(SBase).addImm(SDisp)
10748 .setMemRefs(MI.memoperands());
10749 };
10750
10751 bool NeedsLoop = false;
10752 uint64_t ImmLength = 0;
10753 Register LenAdjReg = SystemZ::NoRegister;
10754 if (IsImmForm) {
10755 ImmLength = LengthMO.getImm();
10756 ImmLength += IsMemset ? 2 : 1; // Add back the subtracted adjustment.
10757 if (ImmLength == 0) {
10758 MI.eraseFromParent();
10759 return MBB;
10760 }
10761 if (Opcode == SystemZ::CLC) {
10762 if (ImmLength > 3 * 256)
10763 // A two-CLC sequence is a clear win over a loop, not least because
10764 // it needs only one branch. A three-CLC sequence needs the same
10765 // number of branches as a loop (i.e. 2), but is shorter. That
10766 // brings us to lengths greater than 768 bytes. It seems relatively
10767 // likely that a difference will be found within the first 768 bytes,
10768 // so we just optimize for the smallest number of branch
10769 // instructions, in order to avoid polluting the prediction buffer
10770 // too much.
10771 NeedsLoop = true;
10772 } else if (ImmLength > 6 * 256)
10773 // The heuristic we use is to prefer loops for anything that would
10774 // require 7 or more MVCs. With these kinds of sizes there isn't much
10775 // to choose between straight-line code and looping code, since the
10776 // time will be dominated by the MVCs themselves.
10777 NeedsLoop = true;
10778 } else {
10779 NeedsLoop = true;
10780 LenAdjReg = LengthMO.getReg();
10781 }
10782
10783 // When generating more than one CLC, all but the last will need to
10784 // branch to the end when a difference is found.
10785 MachineBasicBlock *EndMBB =
10786 (Opcode == SystemZ::CLC && (ImmLength > 256 || NeedsLoop)
10788 : nullptr);
10789
10790 if (NeedsLoop) {
10791 Register StartCountReg =
10792 MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
10793 if (IsImmForm) {
10794 TII->loadImmediate(*MBB, MI, StartCountReg, ImmLength / 256);
10795 ImmLength &= 255;
10796 } else {
10797 BuildMI(*MBB, MI, DL, TII->get(SystemZ::SRLG), StartCountReg)
10798 .addReg(LenAdjReg)
10799 .addReg(0)
10800 .addImm(8);
10801 }
10802
10803 bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
10804 auto loadZeroAddress = [&]() -> MachineOperand {
10805 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10806 BuildMI(*MBB, MI, DL, TII->get(SystemZ::LGHI), Reg).addImm(0);
10807 return MachineOperand::CreateReg(Reg, false);
10808 };
10809 if (DestBase.isReg() && DestBase.getReg() == SystemZ::NoRegister)
10810 DestBase = loadZeroAddress();
10811 if (SrcBase.isReg() && SrcBase.getReg() == SystemZ::NoRegister)
10812 SrcBase = HaveSingleBase ? DestBase : loadZeroAddress();
10813
10814 MachineBasicBlock *StartMBB = nullptr;
10815 MachineBasicBlock *LoopMBB = nullptr;
10816 MachineBasicBlock *NextMBB = nullptr;
10817 MachineBasicBlock *DoneMBB = nullptr;
10818 MachineBasicBlock *AllDoneMBB = nullptr;
10819
10820 Register StartSrcReg = forceReg(MI, SrcBase, TII);
10821 Register StartDestReg =
10822 (HaveSingleBase ? StartSrcReg : forceReg(MI, DestBase, TII));
10823
10824 const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
10825 Register ThisSrcReg = MRI.createVirtualRegister(RC);
10826 Register ThisDestReg =
10827 (HaveSingleBase ? ThisSrcReg : MRI.createVirtualRegister(RC));
10828 Register NextSrcReg = MRI.createVirtualRegister(RC);
10829 Register NextDestReg =
10830 (HaveSingleBase ? NextSrcReg : MRI.createVirtualRegister(RC));
10831 RC = &SystemZ::GR64BitRegClass;
10832 Register ThisCountReg = MRI.createVirtualRegister(RC);
10833 Register NextCountReg = MRI.createVirtualRegister(RC);
10834
10835 if (IsRegForm) {
10836 AllDoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10837 StartMBB = SystemZ::emitBlockAfter(MBB);
10838 LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10839 NextMBB = (EndMBB ? SystemZ::emitBlockAfter(LoopMBB) : LoopMBB);
10840 DoneMBB = SystemZ::emitBlockAfter(NextMBB);
10841
10842 // MBB:
10843 // # Jump to AllDoneMBB if LenAdjReg means 0, or fall thru to StartMBB.
10844 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10845 .addReg(LenAdjReg).addImm(IsMemset ? -2 : -1);
10846 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10848 .addMBB(AllDoneMBB);
10849 MBB->addSuccessor(AllDoneMBB);
10850 if (!IsMemset)
10851 MBB->addSuccessor(StartMBB);
10852 else {
10853 // MemsetOneCheckMBB:
10854 // # Jump to MemsetOneMBB for a memset of length 1, or
10855 // # fall thru to StartMBB.
10856 MachineBasicBlock *MemsetOneCheckMBB = SystemZ::emitBlockAfter(MBB);
10857 MachineBasicBlock *MemsetOneMBB = SystemZ::emitBlockAfter(&*MF.rbegin());
10858 MBB->addSuccessor(MemsetOneCheckMBB);
10859 MBB = MemsetOneCheckMBB;
10860 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10861 .addReg(LenAdjReg).addImm(-1);
10862 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10864 .addMBB(MemsetOneMBB);
10865 MBB->addSuccessor(MemsetOneMBB, {10, 100});
10866 MBB->addSuccessor(StartMBB, {90, 100});
10867
10868 // MemsetOneMBB:
10869 // # Jump back to AllDoneMBB after a single MVI or STC.
10870 MBB = MemsetOneMBB;
10871 insertMemMemOp(MBB, MBB->end(),
10872 MachineOperand::CreateReg(StartDestReg, false), DestDisp,
10873 MachineOperand::CreateReg(StartSrcReg, false), SrcDisp,
10874 1);
10875 BuildMI(MBB, DL, TII->get(SystemZ::J)).addMBB(AllDoneMBB);
10876 MBB->addSuccessor(AllDoneMBB);
10877 }
10878
10879 // StartMBB:
10880 // # Jump to DoneMBB if %StartCountReg is zero, or fall through to LoopMBB.
10881 MBB = StartMBB;
10882 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10883 .addReg(StartCountReg).addImm(0);
10884 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10886 .addMBB(DoneMBB);
10887 MBB->addSuccessor(DoneMBB);
10888 MBB->addSuccessor(LoopMBB);
10889 }
10890 else {
10891 StartMBB = MBB;
10892 DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10893 LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10894 NextMBB = (EndMBB ? SystemZ::emitBlockAfter(LoopMBB) : LoopMBB);
10895
10896 // StartMBB:
10897 // # fall through to LoopMBB
10898 MBB->addSuccessor(LoopMBB);
10899
10900 DestBase = MachineOperand::CreateReg(NextDestReg, false);
10901 SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
10902 if (EndMBB && !ImmLength)
10903 // If the loop handled the whole CLC range, DoneMBB will be empty with
10904 // CC live-through into EndMBB, so add it as live-in.
10905 DoneMBB->addLiveIn(SystemZ::CC);
10906 }
10907
10908 // LoopMBB:
10909 // %ThisDestReg = phi [ %StartDestReg, StartMBB ],
10910 // [ %NextDestReg, NextMBB ]
10911 // %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
10912 // [ %NextSrcReg, NextMBB ]
10913 // %ThisCountReg = phi [ %StartCountReg, StartMBB ],
10914 // [ %NextCountReg, NextMBB ]
10915 // ( PFD 2, 768+DestDisp(%ThisDestReg) )
10916 // Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
10917 // ( JLH EndMBB )
10918 //
10919 // The prefetch is used only for MVC. The JLH is used only for CLC.
10920 MBB = LoopMBB;
10921 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
10922 .addReg(StartDestReg).addMBB(StartMBB)
10923 .addReg(NextDestReg).addMBB(NextMBB);
10924 if (!HaveSingleBase)
10925 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
10926 .addReg(StartSrcReg).addMBB(StartMBB)
10927 .addReg(NextSrcReg).addMBB(NextMBB);
10928 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
10929 .addReg(StartCountReg).addMBB(StartMBB)
10930 .addReg(NextCountReg).addMBB(NextMBB);
10931 if (Opcode == SystemZ::MVC)
10932 BuildMI(MBB, DL, TII->get(SystemZ::PFD))
10934 .addReg(ThisDestReg).addImm(DestDisp - IsMemset + 768).addReg(0);
10935 insertMemMemOp(MBB, MBB->end(),
10936 MachineOperand::CreateReg(ThisDestReg, false), DestDisp,
10937 MachineOperand::CreateReg(ThisSrcReg, false), SrcDisp, 256);
10938 if (EndMBB) {
10939 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10941 .addMBB(EndMBB);
10942 MBB->addSuccessor(EndMBB);
10943 MBB->addSuccessor(NextMBB);
10944 }
10945
10946 // NextMBB:
10947 // %NextDestReg = LA 256(%ThisDestReg)
10948 // %NextSrcReg = LA 256(%ThisSrcReg)
10949 // %NextCountReg = AGHI %ThisCountReg, -1
10950 // CGHI %NextCountReg, 0
10951 // JLH LoopMBB
10952 // # fall through to DoneMBB
10953 //
10954 // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
10955 MBB = NextMBB;
10956 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
10957 .addReg(ThisDestReg).addImm(256).addReg(0);
10958 if (!HaveSingleBase)
10959 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
10960 .addReg(ThisSrcReg).addImm(256).addReg(0);
10961 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
10962 .addReg(ThisCountReg)
10963 .addImm(-1)
10964 .setOperandDead(3);
10965 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10966 .addReg(NextCountReg).addImm(0);
10967 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10969 .addMBB(LoopMBB);
10970 MBB->addSuccessor(LoopMBB);
10971 MBB->addSuccessor(DoneMBB);
10972
10973 MBB = DoneMBB;
10974 if (IsRegForm) {
10975 // DoneMBB:
10976 // # Make PHIs for RemDestReg/RemSrcReg as the loop may or may not run.
10977 // # Use EXecute Relative Long for the remainder of the bytes. The target
10978 // instruction of the EXRL will have a length field of 1 since 0 is an
10979 // illegal value. The number of bytes processed becomes (%LenAdjReg &
10980 // 0xff) + 1.
10981 // # Fall through to AllDoneMBB.
10982 Register RemSrcReg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10983 Register RemDestReg = HaveSingleBase ? RemSrcReg
10984 : MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10985 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RemDestReg)
10986 .addReg(StartDestReg).addMBB(StartMBB)
10987 .addReg(NextDestReg).addMBB(NextMBB);
10988 if (!HaveSingleBase)
10989 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RemSrcReg)
10990 .addReg(StartSrcReg).addMBB(StartMBB)
10991 .addReg(NextSrcReg).addMBB(NextMBB);
10992 if (IsMemset)
10993 insertMemMemOp(MBB, MBB->end(),
10994 MachineOperand::CreateReg(RemDestReg, false), DestDisp,
10995 MachineOperand::CreateReg(RemSrcReg, false), SrcDisp, 1);
10996 MachineInstrBuilder EXRL_MIB =
10997 BuildMI(MBB, DL, TII->get(SystemZ::EXRL_Pseudo))
10998 .addImm(Opcode)
10999 .addReg(LenAdjReg)
11000 .addReg(RemDestReg).addImm(DestDisp)
11001 .addReg(RemSrcReg).addImm(SrcDisp);
11002 MBB->addSuccessor(AllDoneMBB);
11003 MBB = AllDoneMBB;
11004 if (Opcode != SystemZ::MVC) {
11005 EXRL_MIB.addReg(SystemZ::CC, RegState::ImplicitDefine);
11006 if (EndMBB)
11007 MBB->addLiveIn(SystemZ::CC);
11008 }
11009 }
11010 MF.getProperties().resetNoPHIs();
11011 }
11012
11013 // Handle any remaining bytes with straight-line code.
11014 while (ImmLength > 0) {
11015 uint64_t ThisLength = std::min(ImmLength, uint64_t(256));
11016 // The previous iteration might have created out-of-range displacements.
11017 // Apply them using LA/LAY if so.
11018 foldDisplIfNeeded(DestBase, DestDisp);
11019 foldDisplIfNeeded(SrcBase, SrcDisp);
11020 insertMemMemOp(MBB, MI, DestBase, DestDisp, SrcBase, SrcDisp, ThisLength);
11021 DestDisp += ThisLength;
11022 SrcDisp += ThisLength;
11023 ImmLength -= ThisLength;
11024 // If there's another CLC to go, branch to the end if a difference
11025 // was found.
11026 if (EndMBB && ImmLength > 0) {
11027 MachineBasicBlock *NextMBB = SystemZ::splitBlockBefore(MI, MBB);
11028 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11030 .addMBB(EndMBB);
11031 MBB->addSuccessor(EndMBB);
11032 MBB->addSuccessor(NextMBB);
11033 MBB = NextMBB;
11034 }
11035 }
11036 if (EndMBB) {
11037 MBB->addSuccessor(EndMBB);
11038 MBB = EndMBB;
11039 MBB->addLiveIn(SystemZ::CC);
11040 }
11041
11042 MI.eraseFromParent();
11043 return MBB;
11044}
11045
11047SystemZTargetLowering::emitMemmoveImm(MachineInstr &MI,
11048 MachineBasicBlock *MBB) const {
11049 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11050
11051 DebugLoc DL = MI.getDebugLoc();
11052 MachineOperand DstAddr = earlyUseOperand(MI.getOperand(0));
11053 MachineOperand SrcAddr = earlyUseOperand(MI.getOperand(1));
11054 uint64_t Len = MI.getOperand(2).getImm();
11055 assert(Len > 0 && Len <= 256 && "Memmove of of unsupported constant length.");
11056
11057 // Use MVC or MVCRL after comparing the addresses.
11058 MachineBasicBlock *DoneMBB = SystemZ::splitBlockAfter(MI, MBB);
11059 MachineBasicBlock *MvcMBB = SystemZ::emitBlockAfter(MBB);
11060 MachineBasicBlock *MvcrlMBB = SystemZ::emitBlockAfter(MvcMBB);
11061 MBB->addSuccessor(MvcMBB);
11062 MBB->addSuccessor(MvcrlMBB);
11063 MvcMBB->addSuccessor(DoneMBB);
11064 MvcrlMBB->addSuccessor(DoneMBB);
11065
11066 BuildMI(MBB, DL, TII->get(SystemZ::CLGR)).add(SrcAddr).add(DstAddr);
11067 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11069 .addMBB(MvcrlMBB);
11070
11071 BuildMI(MvcMBB, DL, TII->get(SystemZ::MVC))
11072 .add(DstAddr).addImm(0)
11073 .addImm(Len)
11074 .add(SrcAddr).addImm(0)
11075 .setMemRefs(MI.memoperands());
11076 BuildMI(MvcMBB, DL, TII->get(SystemZ::J)).addMBB(DoneMBB);
11077
11078 BuildMI(MvcrlMBB, DL, TII->get(SystemZ::LHI), SystemZ::R0L).addImm(Len - 1);
11079 BuildMI(MvcrlMBB, DL, TII->get(SystemZ::MVCRL))
11080 .add(DstAddr).addImm(0)
11081 .add(SrcAddr).addImm(0)
11082 .setMemRefs(MI.memoperands());
11083
11084 MI.eraseFromParent();
11085 return DoneMBB;
11086}
11087
11088// Decompose string pseudo-instruction MI into a loop that continually performs
11089// Opcode until CC != 3.
11090MachineBasicBlock *SystemZTargetLowering::emitStringWrapper(
11091 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
11092 MachineFunction &MF = *MBB->getParent();
11093 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11094 MachineRegisterInfo &MRI = MF.getRegInfo();
11095 DebugLoc DL = MI.getDebugLoc();
11096
11097 uint64_t End1Reg = MI.getOperand(0).getReg();
11098 uint64_t Start1Reg = MI.getOperand(1).getReg();
11099 uint64_t Start2Reg = MI.getOperand(2).getReg();
11100 uint64_t CharReg = MI.getOperand(3).getReg();
11101
11102 const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
11103 uint64_t This1Reg = MRI.createVirtualRegister(RC);
11104 uint64_t This2Reg = MRI.createVirtualRegister(RC);
11105 uint64_t End2Reg = MRI.createVirtualRegister(RC);
11106
11107 MachineBasicBlock *StartMBB = MBB;
11108 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
11109 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
11110
11111 // StartMBB:
11112 // # fall through to LoopMBB
11113 MBB->addSuccessor(LoopMBB);
11114
11115 // LoopMBB:
11116 // %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
11117 // %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
11118 // R0L = %CharReg
11119 // %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
11120 // JO LoopMBB
11121 // # fall through to DoneMBB
11122 //
11123 // The load of R0L can be hoisted by post-RA LICM.
11124 MBB = LoopMBB;
11125
11126 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
11127 .addReg(Start1Reg).addMBB(StartMBB)
11128 .addReg(End1Reg).addMBB(LoopMBB);
11129 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
11130 .addReg(Start2Reg).addMBB(StartMBB)
11131 .addReg(End2Reg).addMBB(LoopMBB);
11132 BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
11133 BuildMI(MBB, DL, TII->get(Opcode))
11134 .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
11135 .addReg(This1Reg).addReg(This2Reg);
11136 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11138 MBB->addSuccessor(LoopMBB);
11139 MBB->addSuccessor(DoneMBB);
11140
11141 DoneMBB->addLiveIn(SystemZ::CC);
11142
11143 MI.eraseFromParent();
11144 return DoneMBB;
11145}
11146
11147// Update TBEGIN instruction with final opcode and register clobbers.
11148MachineBasicBlock *SystemZTargetLowering::emitTransactionBegin(
11149 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode,
11150 bool NoFloat) const {
11151 MachineFunction &MF = *MBB->getParent();
11152 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11153 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11154
11155 // Update opcode.
11156 MI.setDesc(TII->get(Opcode));
11157
11158 // We cannot handle a TBEGIN that clobbers the stack or frame pointer.
11159 // Make sure to add the corresponding GRSM bits if they are missing.
11160 uint64_t Control = MI.getOperand(2).getImm();
11161 static const unsigned GPRControlBit[16] = {
11162 0x8000, 0x8000, 0x4000, 0x4000, 0x2000, 0x2000, 0x1000, 0x1000,
11163 0x0800, 0x0800, 0x0400, 0x0400, 0x0200, 0x0200, 0x0100, 0x0100
11164 };
11165 Control |= GPRControlBit[15];
11166 if (TFI->hasFP(MF))
11167 Control |= GPRControlBit[11];
11168 MI.getOperand(2).setImm(Control);
11169
11170 // Add GPR clobbers.
11171 for (int I = 0; I < 16; I++) {
11172 if ((Control & GPRControlBit[I]) == 0) {
11173 unsigned Reg = SystemZMC::GR64Regs[I];
11174 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
11175 }
11176 }
11177
11178 // Add FPR/VR clobbers.
11179 if (!NoFloat && (Control & 4) != 0) {
11180 if (Subtarget.hasVector()) {
11181 for (unsigned Reg : SystemZMC::VR128Regs) {
11182 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
11183 }
11184 } else {
11185 for (unsigned Reg : SystemZMC::FP64Regs) {
11186 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
11187 }
11188 }
11189 }
11190
11191 return MBB;
11192}
11193
11194MachineBasicBlock *SystemZTargetLowering::emitLoadAndTestCmp0(
11195 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
11196 MachineFunction &MF = *MBB->getParent();
11197 MachineRegisterInfo *MRI = &MF.getRegInfo();
11198 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11199 DebugLoc DL = MI.getDebugLoc();
11200
11201 Register SrcReg = MI.getOperand(0).getReg();
11202
11203 // Create new virtual register of the same class as source.
11204 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
11205 Register DstReg = MRI->createVirtualRegister(RC);
11206
11207 // Replace pseudo with a normal load-and-test that models the def as
11208 // well.
11209 BuildMI(*MBB, MI, DL, TII->get(Opcode), DstReg)
11210 .addReg(SrcReg)
11211 .setMIFlags(MI.getFlags());
11212 MI.eraseFromParent();
11213
11214 return MBB;
11215}
11216
11217MachineBasicBlock *SystemZTargetLowering::emitProbedAlloca(
11219 MachineFunction &MF = *MBB->getParent();
11220 MachineRegisterInfo *MRI = &MF.getRegInfo();
11221 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11222 DebugLoc DL = MI.getDebugLoc();
11223 const unsigned ProbeSize = getStackProbeSize(MF);
11224 Register DstReg = MI.getOperand(0).getReg();
11225 Register SizeReg = MI.getOperand(2).getReg();
11226
11227 MachineBasicBlock *StartMBB = MBB;
11228 MachineBasicBlock *DoneMBB = SystemZ::splitBlockAfter(MI, MBB);
11229 MachineBasicBlock *LoopTestMBB = SystemZ::emitBlockAfter(StartMBB);
11230 MachineBasicBlock *LoopBodyMBB = SystemZ::emitBlockAfter(LoopTestMBB);
11231 MachineBasicBlock *TailTestMBB = SystemZ::emitBlockAfter(LoopBodyMBB);
11232 MachineBasicBlock *TailMBB = SystemZ::emitBlockAfter(TailTestMBB);
11233
11234 MachineMemOperand *VolLdMMO = MF.getMachineMemOperand(MachinePointerInfo(),
11236
11237 Register PHIReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11238 Register IncReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11239
11240 // LoopTestMBB
11241 // BRC TailTestMBB
11242 // # fallthrough to LoopBodyMBB
11243 StartMBB->addSuccessor(LoopTestMBB);
11244 MBB = LoopTestMBB;
11245 BuildMI(MBB, DL, TII->get(SystemZ::PHI), PHIReg)
11246 .addReg(SizeReg)
11247 .addMBB(StartMBB)
11248 .addReg(IncReg)
11249 .addMBB(LoopBodyMBB);
11250 BuildMI(MBB, DL, TII->get(SystemZ::CLGFI))
11251 .addReg(PHIReg)
11252 .addImm(ProbeSize);
11253 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11255 .addMBB(TailTestMBB);
11256 MBB->addSuccessor(LoopBodyMBB);
11257 MBB->addSuccessor(TailTestMBB);
11258
11259 // LoopBodyMBB: Allocate and probe by means of a volatile compare.
11260 // J LoopTestMBB
11261 MBB = LoopBodyMBB;
11262 BuildMI(MBB, DL, TII->get(SystemZ::SLGFI), IncReg)
11263 .addReg(PHIReg)
11264 .addImm(ProbeSize)
11265 .setOperandDead(3);
11266 BuildMI(MBB, DL, TII->get(SystemZ::SLGFI), SystemZ::R15D)
11267 .addReg(SystemZ::R15D)
11268 .addImm(ProbeSize)
11269 .setOperandDead(3);
11270 BuildMI(MBB, DL, TII->get(SystemZ::CG))
11271 .addReg(SystemZ::R15D)
11272 .addReg(SystemZ::R15D)
11273 .addImm(ProbeSize - 8)
11274 .addReg(0)
11275 .setOperandDead(4)
11276 .setMemRefs(VolLdMMO);
11277 BuildMI(MBB, DL, TII->get(SystemZ::J)).addMBB(LoopTestMBB);
11278 MBB->addSuccessor(LoopTestMBB);
11279
11280 // TailTestMBB
11281 // BRC DoneMBB
11282 // # fallthrough to TailMBB
11283 MBB = TailTestMBB;
11284 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
11285 .addReg(PHIReg)
11286 .addImm(0);
11287 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11289 .addMBB(DoneMBB);
11290 MBB->addSuccessor(TailMBB);
11291 MBB->addSuccessor(DoneMBB);
11292
11293 // TailMBB
11294 // # fallthrough to DoneMBB
11295 MBB = TailMBB;
11296 BuildMI(MBB, DL, TII->get(SystemZ::SLGR), SystemZ::R15D)
11297 .addReg(SystemZ::R15D)
11298 .addReg(PHIReg)
11299 .setOperandDead(3);
11300 BuildMI(MBB, DL, TII->get(SystemZ::CG))
11301 .addReg(SystemZ::R15D)
11302 .addReg(SystemZ::R15D)
11303 .addImm(-8)
11304 .addReg(PHIReg)
11305 .setOperandDead(4)
11306 .setMemRefs(VolLdMMO);
11307 MBB->addSuccessor(DoneMBB);
11308
11309 // DoneMBB
11310 MBB = DoneMBB;
11311 BuildMI(*MBB, MBB->begin(), DL, TII->get(TargetOpcode::COPY), DstReg)
11312 .addReg(SystemZ::R15D);
11313
11314 MI.eraseFromParent();
11315 return DoneMBB;
11316}
11317
11318SDValue SystemZTargetLowering::
11319getBackchainAddress(SDValue SP, SelectionDAG &DAG) const {
11321 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>();
11322 SDLoc DL(SP);
11323 return DAG.getNode(ISD::ADD, DL, MVT::i64, SP,
11324 DAG.getIntPtrConstant(TFL->getBackchainOffset(MF), DL));
11325}
11326
11327// Replace a _STACKGUARD_DAG pseudo with a _STACKGUARD pseudo, adding
11328// a dead early-clobber def reg that will be used as a scratch register
11329// when the pseudo is expanded.
11330MachineBasicBlock *SystemZTargetLowering::emitStackGuardPseudo(
11331 MachineInstr &MI, MachineBasicBlock *MBB, unsigned PseudoOp) const {
11332 MachineRegisterInfo *MRI = &MBB->getParent()->getRegInfo();
11333 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11334 DebugLoc DL = MI.getDebugLoc();
11335 Register AddrReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11336 BuildMI(*MBB, MI, DL, TII->get(PseudoOp), AddrReg)
11337 .addFrameIndex(MI.getOperand(0).getIndex())
11338 .addImm(MI.getOperand(1).getImm());
11339 MI.eraseFromParent();
11340 return MBB;
11341}
11342
11345 switch (MI.getOpcode()) {
11346 case SystemZ::ADJCALLSTACKDOWN:
11347 case SystemZ::ADJCALLSTACKUP:
11348 return emitAdjCallStack(MI, MBB);
11349
11350 case SystemZ::Select32:
11351 case SystemZ::Select64:
11352 case SystemZ::Select128:
11353 case SystemZ::SelectF32:
11354 case SystemZ::SelectF64:
11355 case SystemZ::SelectF128:
11356 case SystemZ::SelectVR32:
11357 case SystemZ::SelectVR64:
11358 case SystemZ::SelectVR128:
11359 return emitSelect(MI, MBB);
11360
11361 case SystemZ::CondStore8Mux:
11362 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
11363 case SystemZ::CondStore8MuxInv:
11364 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
11365 case SystemZ::CondStore16Mux:
11366 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
11367 case SystemZ::CondStore16MuxInv:
11368 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
11369 case SystemZ::CondStore32Mux:
11370 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, false);
11371 case SystemZ::CondStore32MuxInv:
11372 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, true);
11373 case SystemZ::CondStore8:
11374 return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
11375 case SystemZ::CondStore8Inv:
11376 return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
11377 case SystemZ::CondStore16:
11378 return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
11379 case SystemZ::CondStore16Inv:
11380 return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
11381 case SystemZ::CondStore32:
11382 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
11383 case SystemZ::CondStore32Inv:
11384 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
11385 case SystemZ::CondStore64:
11386 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
11387 case SystemZ::CondStore64Inv:
11388 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
11389 case SystemZ::CondStoreF32:
11390 return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
11391 case SystemZ::CondStoreF32Inv:
11392 return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
11393 case SystemZ::CondStoreF64:
11394 return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
11395 case SystemZ::CondStoreF64Inv:
11396 return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
11397
11398 case SystemZ::SCmp128Hi:
11399 return emitICmp128Hi(MI, MBB, false);
11400 case SystemZ::UCmp128Hi:
11401 return emitICmp128Hi(MI, MBB, true);
11402
11403
11404 case SystemZ::ATOMIC_SWAPW:
11405 return emitAtomicLoadBinary(MI, MBB, 0);
11406
11407 case SystemZ::ATOMIC_LOADW_AR:
11408 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR);
11409 case SystemZ::ATOMIC_LOADW_AFI:
11410 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI);
11411
11412 case SystemZ::ATOMIC_LOADW_SR:
11413 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR);
11414
11415 case SystemZ::ATOMIC_LOADW_NR:
11416 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR);
11417 case SystemZ::ATOMIC_LOADW_NILH:
11418 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH);
11419
11420 case SystemZ::ATOMIC_LOADW_OR:
11421 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR);
11422 case SystemZ::ATOMIC_LOADW_OILH:
11423 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH);
11424
11425 case SystemZ::ATOMIC_LOADW_XR:
11426 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR);
11427 case SystemZ::ATOMIC_LOADW_XILF:
11428 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF);
11429
11430 case SystemZ::ATOMIC_LOADW_NRi:
11431 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, true);
11432 case SystemZ::ATOMIC_LOADW_NILHi:
11433 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, true);
11434
11435 case SystemZ::ATOMIC_LOADW_MIN:
11436 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR, SystemZ::CCMASK_CMP_LE);
11437 case SystemZ::ATOMIC_LOADW_MAX:
11438 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR, SystemZ::CCMASK_CMP_GE);
11439 case SystemZ::ATOMIC_LOADW_UMIN:
11440 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR, SystemZ::CCMASK_CMP_LE);
11441 case SystemZ::ATOMIC_LOADW_UMAX:
11442 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR, SystemZ::CCMASK_CMP_GE);
11443
11444 case SystemZ::ATOMIC_CMP_SWAPW:
11445 return emitAtomicCmpSwapW(MI, MBB);
11446 case SystemZ::MVCImm:
11447 case SystemZ::MVCReg:
11448 return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
11449 case SystemZ::NCImm:
11450 return emitMemMemWrapper(MI, MBB, SystemZ::NC);
11451 case SystemZ::OCImm:
11452 return emitMemMemWrapper(MI, MBB, SystemZ::OC);
11453 case SystemZ::XCImm:
11454 case SystemZ::XCReg:
11455 return emitMemMemWrapper(MI, MBB, SystemZ::XC);
11456 case SystemZ::CLCImm:
11457 case SystemZ::CLCReg:
11458 return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
11459 case SystemZ::MemsetImmImm:
11460 case SystemZ::MemsetImmReg:
11461 case SystemZ::MemsetRegImm:
11462 case SystemZ::MemsetRegReg:
11463 return emitMemMemWrapper(MI, MBB, SystemZ::MVC, true/*IsMemset*/);
11464 case SystemZ::MemmoveImm:
11465 return emitMemmoveImm(MI, MBB);
11466 case SystemZ::CLSTLoop:
11467 return emitStringWrapper(MI, MBB, SystemZ::CLST);
11468 case SystemZ::MVSTLoop:
11469 return emitStringWrapper(MI, MBB, SystemZ::MVST);
11470 case SystemZ::SRSTLoop:
11471 return emitStringWrapper(MI, MBB, SystemZ::SRST);
11472 case SystemZ::TBEGIN:
11473 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, false);
11474 case SystemZ::TBEGIN_nofloat:
11475 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, true);
11476 case SystemZ::TBEGINC:
11477 return emitTransactionBegin(MI, MBB, SystemZ::TBEGINC, true);
11478 case SystemZ::LTEBRCompare_Pseudo:
11479 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTEBR);
11480 case SystemZ::LTDBRCompare_Pseudo:
11481 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTDBR);
11482 case SystemZ::LTXBRCompare_Pseudo:
11483 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTXBR);
11484
11485 case SystemZ::PROBED_ALLOCA:
11486 return emitProbedAlloca(MI, MBB);
11487 case SystemZ::EH_SjLj_SetJmp:
11488 return emitEHSjLjSetJmp(MI, MBB);
11489 case SystemZ::EH_SjLj_LongJmp:
11490 return emitEHSjLjLongJmp(MI, MBB);
11491
11492 case TargetOpcode::STACKMAP:
11493 case TargetOpcode::PATCHPOINT:
11494 return emitPatchPoint(MI, MBB);
11495
11496 case SystemZ::MOV_STACKGUARD_DAG:
11497 return emitStackGuardPseudo(MI, MBB, SystemZ::MOV_STACKGUARD);
11498
11499 case SystemZ::CMP_STACKGUARD_DAG:
11500 return emitStackGuardPseudo(MI, MBB, SystemZ::CMP_STACKGUARD);
11501
11502 default:
11503 llvm_unreachable("Unexpected instr type to insert");
11504 }
11505}
11506
11507SDValue SystemZTargetLowering::lowerGET_ROUNDING(SDValue Op,
11508 SelectionDAG &DAG) const {
11509 SDLoc dl(Op);
11510 /*
11511 The rounding method is in FPC Byte 3 bits 6-7, and has the following
11512 settings:
11513 00 Round to nearest
11514 01 Round to 0
11515 10 Round to +inf
11516 11 Round to -inf
11517
11518 FLT_ROUNDS, on the other hand, expects the following:
11519 -1 Undefined
11520 0 Round to 0
11521 1 Round to nearest
11522 2 Round to +inf
11523 3 Round to -inf
11524 */
11525
11526 // Save FPC to register.
11527 SDValue Chain = Op.getOperand(0);
11528 SDValue EFPC(
11529 DAG.getMachineNode(SystemZ::EFPC, dl, {MVT::i32, MVT::Other}, Chain), 0);
11530 Chain = EFPC.getValue(1);
11531
11532 // Transform as necessary
11533 SDValue CWD1 = DAG.getNode(ISD::AND, dl, MVT::i32, EFPC,
11534 DAG.getConstant(3, dl, MVT::i32));
11535 // RetVal = (CWD1 ^ (CWD1 >> 1)) ^ 1
11536 SDValue CWD2 = DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1,
11537 DAG.getNode(ISD::SRL, dl, MVT::i32, CWD1,
11538 DAG.getConstant(1, dl, MVT::i32)));
11539
11540 SDValue RetVal = DAG.getNode(ISD::XOR, dl, MVT::i32, CWD2,
11541 DAG.getConstant(1, dl, MVT::i32));
11542 RetVal = DAG.getZExtOrTrunc(RetVal, dl, Op.getValueType());
11543
11544 return DAG.getMergeValues({RetVal, Chain}, dl);
11545}
11546
11547SDValue SystemZTargetLowering::lowerVECREDUCE_ADD(SDValue Op,
11548 SelectionDAG &DAG) const {
11549 EVT VT = Op.getValueType();
11550 Op = Op.getOperand(0);
11551 EVT OpVT = Op.getValueType();
11552
11553 assert(OpVT.isVector() && "Operand type for VECREDUCE_ADD is not a vector.");
11554
11555 SDLoc DL(Op);
11556
11557 // load a 0 vector for the third operand of VSUM.
11558 SDValue Zero = DAG.getSplatBuildVector(OpVT, DL, DAG.getConstant(0, DL, VT));
11559
11560 // execute VSUM.
11561 switch (OpVT.getScalarSizeInBits()) {
11562 case 8:
11563 case 16:
11564 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Zero);
11565 [[fallthrough]];
11566 case 32:
11567 case 64:
11568 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::i128, Op,
11569 DAG.getBitcast(Op.getValueType(), Zero));
11570 break;
11571 case 128:
11572 break; // VSUM over v1i128 should not happen and would be a noop
11573 default:
11574 llvm_unreachable("Unexpected scalar size.");
11575 }
11576 // Cast to original vector type, retrieve last element.
11577 return DAG.getNode(
11578 ISD::EXTRACT_VECTOR_ELT, DL, VT, DAG.getBitcast(OpVT, Op),
11579 DAG.getConstant(OpVT.getVectorNumElements() - 1, DL, MVT::i32));
11580}
11581
11582static void printFunctionArgExts(const Function *F, raw_ostream &OS) {
11583 FunctionType *FT = F->getFunctionType();
11584 const AttributeList &Attrs = F->getAttributes();
11585 if (Attrs.hasRetAttrs())
11586 OS << Attrs.getAsString(AttributeList::ReturnIndex) << " ";
11587 OS << *F->getReturnType() << " @" << F->getName() << "(";
11588 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
11589 if (I)
11590 OS << ", ";
11591 OS << *FT->getParamType(I);
11592 AttributeSet ArgAttrs = Attrs.getParamAttrs(I);
11593 for (auto A : {Attribute::SExt, Attribute::ZExt, Attribute::NoExt})
11594 if (ArgAttrs.hasAttribute(A))
11595 OS << " " << Attribute::getNameFromAttrKind(A);
11596 }
11597 if (F->isVarArg())
11598 OS << ", ...";
11599 OS << ")\n";
11600}
11601
11602bool SystemZTargetLowering::isInternal(const Function *Fn) const {
11603 std::map<const Function *, bool>::iterator Itr = IsInternalCache.find(Fn);
11604 if (Itr == IsInternalCache.end())
11605 Itr = IsInternalCache
11606 .insert(std::pair<const Function *, bool>(
11607 Fn, (Fn->hasLocalLinkage() && !Fn->hasAddressTaken())))
11608 .first;
11609 return Itr->second;
11610}
11611
11612bool SystemZTargetLowering::enableNarrowIntArgsVerification() const {
11613 if (!Subtarget.isTargetELF())
11614 return false;
11615
11616 if (auto V = toOptional(Subtarget.getCLOpts().argext_abi_check))
11617 return *V;
11618
11619#ifdef NDEBUG
11620 return false;
11621#endif
11622
11624}
11625
11626void SystemZTargetLowering::verifyNarrowIntegerArgs_Call(
11627 CallLoweringInfo &CLI, const SmallVectorImpl<ISD::OutputArg> &Outs,
11628 const Function *F, SDValue Callee) const {
11629 if (!enableNarrowIntArgsVerification())
11630 return;
11631 bool IsInternal = false;
11632 const Function *CalleeFn = nullptr;
11633 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
11634 if ((CalleeFn = dyn_cast<Function>(G->getGlobal())))
11635 IsInternal = isInternal(CalleeFn);
11636 bool C_ABI = CLI.CallConv == CallingConv::C && !IsInternal;
11637 if (!verifyNarrowIntegerArgs(C_ABI, Outs, CalleeFn, /*IsRet=*/false)) {
11638 errs() << "Callee: ";
11639 if (CalleeFn != nullptr)
11640 printFunctionArgExts(CalleeFn, errs());
11641 else
11642 errs() << "-\n";
11643 errs() << "Caller: ";
11645 if (CLI.CB)
11646 errs() << " " << *CLI.CB;
11647 llvm_unreachable("");
11648 }
11649 LLVM_DEBUG(dbgs() << "Outgoing call arguments verified as ABI compliant: ";
11650 if (CalleeFn != nullptr) printFunctionArgExts(CalleeFn, dbgs());
11651 else dbgs() << "-\n";);
11652}
11653
11654void SystemZTargetLowering::verifyNarrowIntegerArgs_Ret(
11656 const Function *F) const {
11657 if (!enableNarrowIntArgsVerification())
11658 return;
11659 bool C_ABI = CallConv == CallingConv::C && !isInternal(F);
11660 if (!verifyNarrowIntegerArgs(C_ABI, Outs, F, /*IsRet=*/true)) {
11661 errs() << "Returning from function: ";
11663 llvm_unreachable("");
11664 }
11665 LLVM_DEBUG(dbgs() << "Return argument verified as ABI compliant : ";
11667}
11668
11669// Verify that narrow integer arguments are extended according to the
11670// function header (calllee for a call, containing function for a ret).
11671// If C_ABI is true, an extension attribute must be present.
11672bool SystemZTargetLowering::verifyNarrowIntegerArgs(
11673 bool C_ABI, const SmallVectorImpl<ISD::OutputArg> &Outs,
11674 const Function *FunHeader, bool IsRet) const {
11675 if (IsRet && Outs.size() != 1)
11676 return true;
11677
11678 for (unsigned i = 0; i < Outs.size(); ++i) {
11679 EVT OrigArgVT = Outs[i].ArgVT;
11680 if (!OrigArgVT.isScalarInteger() || OrigArgVT.getSizeInBits() >= 64)
11681 continue;
11682 assert(Outs[i].VT == MVT::i32 && "Unexpected integer argument VT.");
11683 ISD::ArgFlagsTy Flags = Outs[i].Flags;
11684 unsigned OrigIdx = Outs[i].OrigArgIndex;
11685
11686 // Per the C ABI there must be an extension.
11687 if (C_ABI && !Flags.isSExt() && !Flags.isZExt() && !Flags.isNoExt()) {
11688 errs() << "ERROR: (C ABI violation) missing extension attribute on "
11689 << (IsRet ? "return value" : Twine("arg ") + Twine(OrigIdx))
11690 << ".\n";
11691 return false;
11692 }
11693
11694 // Flags should reflect the attributes of the function header.
11695 if (FunHeader) {
11696 const AttributeList &FunAttrs = FunHeader->getAttributes();
11697 const AttributeSet Attrs =
11698 IsRet ? FunAttrs.getRetAttrs() : FunAttrs.getParamAttrs(OrigIdx);
11699 if (Attrs.hasAttribute(Attribute::SExt) && !Flags.isSExt()) {
11700 errs() << "ERROR: Missing SExt on arg " << OrigIdx << ".\n";
11701 return false;
11702 }
11703 if (Attrs.hasAttribute(Attribute::ZExt) && !Flags.isZExt()) {
11704 errs() << "ERROR: Missing ZExt on arg " << OrigIdx << ".\n";
11705 return false;
11706 }
11707 }
11708 }
11709
11710 return true;
11711}
11712
11714 Module &M, const LibcallLoweringInfo &Libcalls) const {
11715 StringRef GuardMode = M.getStackProtectorGuard();
11716
11717 // In the TLS case, no symbol needs to be inserted.
11718 if (GuardMode == "tls" || GuardMode.empty())
11719 return;
11720
11721 // Otherwise (in the global case), insert the appropriate global variable.
11723}
unsigned NumParts
return SDValue()
const AArch64Subtarget & Subtarget
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
uint64_t uint64_t
uint64_t Imm
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:665
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 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
SmallVector< MachineOperand, 4 > Cond
int64_t C1
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
MachineInstr *& Lo
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 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 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 bool isInBoundsConstantVectorIndex(EVT VecVT, SDValue Idx)
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 Register getOrCreateADAVirtualRegister(MachineFunction &MF)
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 void printFunctionArgExts(const Function *F, raw_ostream &OS)
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:448
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
Definition Attributes.h:532
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
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
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:44
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:127
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:317
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:941
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
uint64_t getFnAttributeAsParsedInteger(StringRef Kind, uint64_t Default=0) const
For a string attribute Kind, parse attribute as an integer.
Definition Function.cpp:778
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
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:76
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.
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...
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
ISD::CondCode getOperandCondCode(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)
LLVM_ABI SDValue getNegative(SDValue Val, const SDLoc &DL, EVT VT)
Create negative operation as (SUB 0, Val).
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:482
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:712
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)
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...
bool canMergeStoresTo(unsigned AS, EVT MemVT, const MachineFunction &MF) const override
Returns if it's reasonable to merge stores to MemVT size.
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.
FPImmAction getFPImmAction(const APFloat &Imm, EVT VT, bool ForCodeSize) const override
Returns how the legalizer should materialize the specified FP immediate.
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.
bool isTypeDesirableForOp(SDNode *N, EVT VT) const override
Overload that takes the specific node being optimized.
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...
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...
bool aggressivelyPreferBuildVectorSources(EVT VecVT) const override
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.
FPImmAction
How the legalizer should materialize a floating-point immediate.
@ ConstantPool
Load the immediate from the constant pool.
@ Legal
The target can instruction select the immediate natively.
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.
virtual bool isTypeDesirableForOp(unsigned, EVT VT) const
Return true if the target has native support for the specified value type and it is 'desirable' to us...
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.
TargetOptions Options
CodeModel::Model getCodeModel() const
Returns the code model.
unsigned VerifyArgABICompliance
When set to true, call/return argument extensions of narrow integers are verified in the target backe...
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:352
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
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
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
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
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 char Attrs[]
Key for Kernel::Metadata::mAttrs.
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
LLVM_ABI bool isConstantSplatVector(SDValue V, APInt &SplatValue)
Node predicates.
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
LLVM_ABI bool isConstantSplatVectorAllZeros(SDValue V, bool BuildVectorOnly=false)
Return true if the specified value is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are 0 ...
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:851
@ 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:811
@ 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:885
@ 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:912
@ 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:771
@ 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:942
@ 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:820
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:876
@ 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:681
@ 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:828
@ 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:688
@ 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 ...
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:720
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:793
@ 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:882
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:843
@ FMINNUM
FMINNUM/FMAXNUM - Same semantics as the llvm.minnum/maxnum intrinsics.
@ 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:931
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:920
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:751
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:837
@ 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
@ PEXT
Parallel bit extract (compress) and parallel bit deposit (expand).
Definition ISDOpcodes.h:807
@ 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 - Same semantics as the llvm.minimum/maximum intrinsics.
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:958
@ 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:763
@ 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:819
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:991
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:953
@ 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:888
@ BRCOND
BRCOND - Conditional branch.
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:865
@ 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 - Same semantics as the llvm.minimumnum/maximumnum intrinsics.
@ 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 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(SDValue V)
Return true if the specified value is a BUILD_VECTOR where all of the elements are 0 or undef.
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:66
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:46
static bool isImmHH(uint64_t Val)
Definition SystemZ.h:182
const unsigned CCMASK_TEND
Definition SystemZ.h:103
const unsigned CCMASK_CS_EQ
Definition SystemZ.h:73
const unsigned CCMASK_TBEGIN
Definition SystemZ.h:98
const unsigned CCMASK_0
Definition SystemZ.h:33
const MCPhysReg ELFArgFPRs[ELFNumArgFPRs]
MachineBasicBlock * splitBlockBefore(MachineBasicBlock::iterator MI, MachineBasicBlock *MBB)
const unsigned CCMASK_TM_SOME_1
Definition SystemZ.h:88
const unsigned CCMASK_LOGICAL_CARRY
Definition SystemZ.h:66
const unsigned TDCMASK_NORMAL_MINUS
Definition SystemZ.h:128
const unsigned CCMASK_TDC
Definition SystemZ.h:115
const unsigned CCMASK_FCMP
Definition SystemZ.h:54
const unsigned CCMASK_TM_SOME_0
Definition SystemZ.h:87
static bool isImmHL(uint64_t Val)
Definition SystemZ.h:177
const unsigned TDCMASK_SUBNORMAL_MINUS
Definition SystemZ.h:130
const unsigned PFD_READ
Definition SystemZ.h:121
const unsigned CCMASK_1
Definition SystemZ.h:34
const unsigned TDCMASK_NORMAL_PLUS
Definition SystemZ.h:127
const unsigned PFD_WRITE
Definition SystemZ.h:122
const unsigned CCMASK_CMP_GT
Definition SystemZ.h:43
const unsigned TDCMASK_QNAN_MINUS
Definition SystemZ.h:134
const unsigned CCMASK_CS
Definition SystemZ.h:75
const unsigned CCMASK_ANY
Definition SystemZ.h:37
const unsigned CCMASK_ARITH
Definition SystemZ.h:61
const unsigned CCMASK_TM_MIXED_MSB_0
Definition SystemZ.h:84
const unsigned TDCMASK_SUBNORMAL_PLUS
Definition SystemZ.h:129
static bool isImmLL(uint64_t Val)
Definition SystemZ.h:167
const unsigned VectorBits
Definition SystemZ.h:160
static bool isImmLH(uint64_t Val)
Definition SystemZ.h:172
MachineBasicBlock * emitBlockAfter(MachineBasicBlock *MBB)
const unsigned TDCMASK_INFINITY_PLUS
Definition SystemZ.h:131
unsigned reverseCCMask(unsigned CCMask)
const unsigned CCMASK_TM_ALL_0
Definition SystemZ.h:83
const unsigned IPM_CC
Definition SystemZ.h:118
const unsigned CCMASK_CMP_LE
Definition SystemZ.h:45
const unsigned CCMASK_CMP_O
Definition SystemZ.h:50
const unsigned CCMASK_CMP_EQ
Definition SystemZ.h:41
const unsigned VectorBytes
Definition SystemZ.h:164
const unsigned TDCMASK_INFINITY_MINUS
Definition SystemZ.h:132
const unsigned CCMASK_ICMP
Definition SystemZ.h:53
const unsigned CCMASK_VCMP_ALL
Definition SystemZ.h:107
const unsigned CCMASK_VCMP_NONE
Definition SystemZ.h:109
MachineBasicBlock * splitBlockAfter(MachineBasicBlock::iterator MI, MachineBasicBlock *MBB)
const unsigned CCMASK_VCMP
Definition SystemZ.h:110
const unsigned CCMASK_TM_MIXED_MSB_1
Definition SystemZ.h:85
const unsigned CCMASK_TM_MSB_0
Definition SystemZ.h:89
const unsigned CCMASK_ARITH_OVERFLOW
Definition SystemZ.h:60
const unsigned CCMASK_CS_NE
Definition SystemZ.h:74
const unsigned TDCMASK_SNAN_PLUS
Definition SystemZ.h:135
const unsigned CCMASK_TM
Definition SystemZ.h:91
const unsigned CCMASK_3
Definition SystemZ.h:36
const unsigned CCMASK_NONE
Definition SystemZ.h:32
const unsigned CCMASK_CMP_LT
Definition SystemZ.h:42
const unsigned CCMASK_CMP_NE
Definition SystemZ.h:44
const unsigned TDCMASK_ZERO_PLUS
Definition SystemZ.h:125
const unsigned TDCMASK_QNAN_PLUS
Definition SystemZ.h:133
const unsigned TDCMASK_ZERO_MINUS
Definition SystemZ.h:126
unsigned even128(bool Is32bit)
const unsigned CCMASK_TM_ALL_1
Definition SystemZ.h:86
const unsigned CCMASK_LOGICAL_BORROW
Definition SystemZ.h:68
const unsigned ELFNumArgFPRs
const unsigned CCMASK_CMP_UO
Definition SystemZ.h:49
const unsigned CCMASK_LOGICAL
Definition SystemZ.h:70
const unsigned CCMASK_TM_MSB_1
Definition SystemZ.h:90
const unsigned TDCMASK_SNAN_MINUS
Definition SystemZ.h:136
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
constexpr std::optional< bool > toOptional(BoolOrDefault X)
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:572
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:320
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:881
#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:433
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:160
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:170
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:423
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:354
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:419
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:191
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:361
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:286
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:366
bool isVectorOf(EVT EltVT) const
Return true if this is a vector with matching element type.
Definition ValueTypes.h:196
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:180
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:374
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:175
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.