LLVM 24.0.0git
SystemZISelLowering.cpp
Go to the documentation of this file.
1//===-- SystemZISelLowering.cpp - SystemZ DAG lowering implementation -----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the SystemZTargetLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "SystemZISelLowering.h"
14#include "SystemZCallingConv.h"
17#include "llvm/ADT/SmallSet.h"
22#include "llvm/IR/GlobalAlias.h"
24#include "llvm/IR/Intrinsics.h"
25#include "llvm/IR/IntrinsicsS390.h"
26#include "llvm/IR/Module.h"
32#include <cctype>
33#include <optional>
34
35using namespace llvm;
36
37#define DEBUG_TYPE "systemz-lower"
38
39// Temporarily let this be disabled by default until all known problems
40// related to argument extensions are fixed.
42 "argext-abi-check", cl::init(false),
43 cl::desc("Verify that narrow int args are properly extended per the "
44 "SystemZ ABI."));
45
46namespace {
47// Represents information about a comparison.
48struct Comparison {
49 Comparison(SDValue Op0In, SDValue Op1In, SDValue ChainIn)
50 : Op0(Op0In), Op1(Op1In), Chain(ChainIn),
51 Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
52
53 // The operands to the comparison.
54 SDValue Op0, Op1;
55
56 // Chain if this is a strict floating-point comparison.
57 SDValue Chain;
58
59 // The opcode that should be used to compare Op0 and Op1.
60 unsigned Opcode;
61
62 // A SystemZICMP value. Only used for integer comparisons.
63 unsigned ICmpType;
64
65 // The mask of CC values that Opcode can produce.
66 unsigned CCValid;
67
68 // The mask of CC values for which the original condition is true.
69 unsigned CCMask;
70};
71} // end anonymous namespace
72
73// Classify VT as either 32 or 64 bit.
74static bool is32Bit(EVT VT) {
75 switch (VT.getSimpleVT().SimpleTy) {
76 case MVT::i32:
77 return true;
78 case MVT::i64:
79 return false;
80 default:
81 llvm_unreachable("Unsupported type");
82 }
83}
84
85// Return a version of MachineOperand that can be safely used before the
86// final use.
88 if (Op.isReg())
89 Op.setIsKill(false);
90 return Op;
91}
92
94 const SystemZSubtarget &STI)
95 : TargetLowering(TM, STI), Subtarget(STI) {
96 MVT PtrVT = MVT::i64;
97
98 auto *Regs = STI.getSpecialRegisters();
99
100 // Set up the register classes.
101 if (Subtarget.hasHighWord())
102 addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
103 else
104 addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
105 addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass);
106 if (!useSoftFloat()) {
107 if (Subtarget.hasVector()) {
108 addRegisterClass(MVT::f16, &SystemZ::VR16BitRegClass);
109 addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass);
110 addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass);
111 } else {
112 addRegisterClass(MVT::f16, &SystemZ::FP16BitRegClass);
113 addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass);
114 addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass);
115 }
116 if (Subtarget.hasVectorEnhancements1())
117 addRegisterClass(MVT::f128, &SystemZ::VR128BitRegClass);
118 else
119 addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
120
121 if (Subtarget.hasVector()) {
122 addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass);
123 addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass);
124 addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass);
125 addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass);
126 addRegisterClass(MVT::v8f16, &SystemZ::VR128BitRegClass);
127 addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass);
128 addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass);
129 }
130
131 if (Subtarget.hasVector())
132 addRegisterClass(MVT::i128, &SystemZ::VR128BitRegClass);
133 }
134
135 // Without vector support, model GR128 register pairs as v2i64.
136 if (!Subtarget.hasVector())
137 addRegisterClass(MVT::v2i64, &SystemZ::GR128BitRegClass);
138
139 // Compute derived properties from the register classes
140 computeRegisterProperties(Subtarget.getRegisterInfo());
141
142 // Set up special registers.
143 setStackPointerRegisterToSaveRestore(Regs->getStackPointerRegister());
144
145 // TODO: It may be better to default to latency-oriented scheduling, however
146 // LLVM's current latency-oriented scheduler can't handle physreg definitions
147 // such as SystemZ has with CC, so set this to the register-pressure
148 // scheduler, because it can.
150
153
155
156 // Instructions are strings of 2-byte aligned 2-byte values.
158 // For performance reasons we prefer 16-byte alignment.
160
161 // Handle operations that are handled in a similar way for all types.
162 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
163 I <= MVT::LAST_FP_VALUETYPE;
164 ++I) {
166 if (isTypeLegal(VT)) {
167 // Lower SET_CC into an IPM-based sequence.
171
172 // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
174
175 // Lower SELECT_CC and BR_CC into separate comparisons and branches.
178 }
179 }
180
181 // Expand jump table branches as address arithmetic followed by an
182 // indirect jump.
184
185 // Expand BRCOND into a BR_CC (see above).
187
188 // Handle integer types except i128.
189 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
190 I <= MVT::LAST_INTEGER_VALUETYPE;
191 ++I) {
193 if (isTypeLegal(VT) && VT != MVT::i128) {
195
196 // Expand individual DIV and REMs into DIVREMs.
203
204 // Support addition/subtraction with overflow.
207
208 // Support addition/subtraction with carry.
211
212 // Support carry in as value rather than glue.
215
216 // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
217 // available, or if the operand is constant.
219
220 // Use POPCNT on z196 and above.
221 if (Subtarget.hasPopulationCount())
223 else
225
226 // No special instructions for these.
229
230 // Use *MUL_LOHI where possible instead of MULH*.
235
236 // The fp<=>i32/i64 conversions are all Legal except for f16 and for
237 // unsigned on z10 (only z196 and above have native support for
238 // unsigned conversions).
245 // Handle unsigned 32-bit input types as signed 64-bit types on z10.
246 auto OpAction =
247 (!Subtarget.hasFPExtension() && VT == MVT::i32) ? Promote : Custom;
248 setOperationAction(Op, VT, OpAction);
249 }
250 }
251 }
252
253 // Handle i128 if legal.
254 if (isTypeLegal(MVT::i128)) {
255 // No special instructions for these.
262
263 // We may be able to use VSLDB/VSLD/VSRD for these.
266
267 // No special instructions for these before z17.
268 if (!Subtarget.hasVectorEnhancements3()) {
278 } else {
279 // Even if we do have a legal 128-bit multiply, we do not
280 // want 64-bit multiply-high operations to use it.
283 }
284
285 // Support addition/subtraction with carry.
290
291 // Use VPOPCT and add up partial results.
293
294 // Additional instructions available with z17.
295 if (Subtarget.hasVectorEnhancements3()) {
296 setOperationAction(ISD::ABS, MVT::i128, Legal);
297
299 MVT::i128, Legal);
300 }
301 }
302
303 // These need custom handling in order to handle the f16 conversions.
312
313 // Type legalization will convert 8- and 16-bit atomic operations into
314 // forms that operate on i32s (but still keeping the original memory VT).
315 // Lower them into full i32 operations.
327
328 // Whether or not i128 is not a legal type, we need to custom lower
329 // the atomic operations in order to exploit SystemZ instructions.
334
335 // Mark sign/zero extending atomic loads as legal, which will make
336 // DAGCombiner fold extensions into atomic loads if possible.
338 {MVT::i8, MVT::i16, MVT::i32}, Legal);
340 {MVT::i8, MVT::i16}, Legal);
342 MVT::i8, Legal);
343
344 // We can use the CC result of compare-and-swap to implement
345 // the "success" result of ATOMIC_CMP_SWAP_WITH_SUCCESS.
349
351
352 // Traps are legal, as we will convert them to "j .+2".
353 setOperationAction(ISD::TRAP, MVT::Other, Legal);
354
355 // We have native support for a 64-bit CTLZ, via FLOGR.
359
360 // On z17 we have native support for a 64-bit CTTZ.
361 if (Subtarget.hasMiscellaneousExtensions4()) {
365 }
366
367 // On z15 we have native support for a 64-bit CTPOP.
368 if (Subtarget.hasMiscellaneousExtensions3()) {
371 }
372
373 // Give LowerOperation the chance to replace 64-bit ORs with subregs.
375
376 // Expand 128 bit shifts without using a libcall.
380
381 // Also expand 256 bit shifts if i128 is a legal type.
382 if (isTypeLegal(MVT::i128)) {
386 }
387
388 // Handle bitcast from fp128 to i128.
389 if (!isTypeLegal(MVT::i128))
391
392 // We have native instructions for i8, i16 and i32 extensions, but not i1.
394 for (MVT VT : MVT::integer_valuetypes()) {
398 }
399
400 // Handle the various types of symbolic address.
406
407 // We need to handle dynamic allocations specially because of the
408 // 160-byte area at the bottom of the stack.
411
414
415 // Handle prefetches with PFD or PFDRL.
417
418 // Handle readcyclecounter with STCKF.
420
422 // Assume by default that all vector operations need to be expanded.
423 for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
424 if (getOperationAction(Opcode, VT) == Legal)
425 setOperationAction(Opcode, VT, Expand);
426
427 // Likewise all truncating stores and extending loads.
428 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
429 setTruncStoreAction(VT, InnerVT, Expand);
432 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
433 }
434
435 if (Subtarget.hasVector() && isTypeLegal(VT)) {
436 // These operations are legal for anything that can be stored in a
437 // vector register, even if there is no native support for the format
438 // as such. In particular, we can do these for v4f32 even though there
439 // are no specific instructions for that format.
445
446 // Likewise, except that we need to replace the nodes with something
447 // more specific.
450 }
451 }
452
453 if (!Subtarget.hasVector()) {
454 // A v2i64 GR128 pair can only be built from or split into its halves.
455 // Loads and stores are expanded to avoid tying up a register pair.
458 MVT::v2i64, Legal);
460 MVT::v2i64, Custom);
461 }
462
463 // Handle integer vector types.
465 if (Subtarget.hasVector() && isTypeLegal(VT)) {
466 // These operations have direct equivalents.
471 if (VT != MVT::v2i64 || Subtarget.hasVectorEnhancements3()) {
475 }
476 if (Subtarget.hasVectorEnhancements3() &&
477 VT != MVT::v16i8 && VT != MVT::v8i16) {
482 }
487 if (Subtarget.hasVectorEnhancements1())
489 else
493
494 // Convert a GPR scalar to a vector by inserting it into element 0.
496
497 // Use a series of unpacks for extensions.
500
501 // Detect shifts/rotates by a scalar amount and convert them into
502 // V*_BY_SCALAR.
507
508 // Add ISD::VECREDUCE_ADD as custom in order to implement
509 // it with VZERO+VSUM
511
512 // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
513 // and inverting the result as necessary.
515
517 Legal);
518 }
519 }
520
521 if (Subtarget.hasVector()) {
522 // There should be no need to check for float types other than v2f64
523 // since <2 x f32> isn't a legal type.
532
541 }
542
543 if (Subtarget.hasVectorEnhancements2()) {
552
561 }
562
563 // Handle floating-point types.
564 if (!useSoftFloat()) {
565 // Promote all f16 operations to float, with some exceptions below.
566 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
567 setOperationAction(Opc, MVT::f16, Promote);
569 for (MVT VT : {MVT::f32, MVT::f64, MVT::f128}) {
570 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
571 setTruncStoreAction(VT, MVT::f16, Expand);
572 }
574 setOperationAction(Op, MVT::f16, Subtarget.hasVector() ? Legal : Custom);
578
579 for (auto Op : {ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN})
580 setOperationAction(Op, MVT::f16, Legal);
581 }
582
583 for (unsigned I = MVT::FIRST_FP_VALUETYPE;
584 I <= MVT::LAST_FP_VALUETYPE;
585 ++I) {
587 if (isTypeLegal(VT) && VT != MVT::f16) {
588 // We can use FI for FRINT.
590
591 // We can use the extended form of FI for other rounding operations.
592 if (Subtarget.hasFPExtension()) {
599 }
600
601 // No special instructions for these.
607
608 // Special treatment.
610
611 // Handle constrained floating-point operations.
620 if (Subtarget.hasFPExtension()) {
627 }
628
629 // Extension from f16 needs libcall.
632 }
633 }
634
635 // Handle floating-point vector types.
636 if (Subtarget.hasVector()) {
637 // Scalar-to-vector conversion is just a subreg.
641
642 // Some insertions and extractions can be done directly but others
643 // need to go via integers.
650
651 // These operations have direct equivalents.
652 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
653 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
654 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
655 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
656 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
657 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
658 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
659 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
660 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
663 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
667
668 // Handle constrained floating-point operations.
682
687 if (Subtarget.hasVectorEnhancements1()) {
690 }
691 }
692
693 // The vector enhancements facility 1 has instructions for these.
694 if (Subtarget.hasVectorEnhancements1()) {
695 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
696 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
697 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
698 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
699 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
700 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
701 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
702 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
703 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
706 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
710
711 for (MVT Type : {MVT::f64, MVT::v2f64, MVT::f32, MVT::v4f32, MVT::f128}) {
720 }
721
722 // Handle constrained floating-point operations.
736 for (auto VT : { MVT::f32, MVT::f64, MVT::f128,
737 MVT::v4f32, MVT::v2f64 }) {
744 }
745 }
746
747 // We only have fused f128 multiply-addition on vector registers.
748 if (!Subtarget.hasVectorEnhancements1()) {
751 }
752
753 // We don't have a copysign instruction on vector registers.
754 if (Subtarget.hasVectorEnhancements1())
756
757 // Needed so that we don't try to implement f128 constant loads using
758 // a load-and-extend of a f80 constant (in cases where the constant
759 // would fit in an f80).
760 for (MVT VT : MVT::fp_valuetypes())
761 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
762
763 // We don't have extending load instruction on vector registers.
764 if (Subtarget.hasVectorEnhancements1()) {
765 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
766 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
767 }
768
769 // Floating-point truncation and stores need to be done separately.
770 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
771 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
772 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
773
774 // We have 64-bit FPR<->GPR moves, but need special handling for
775 // 32-bit forms.
776 if (!Subtarget.hasVector()) {
779 }
780
781 // VASTART and VACOPY need to deal with the SystemZ-specific varargs
782 // structure, but VAEND is a no-op.
786
787 if (Subtarget.isTargetzOS()) {
788 // Handle address space casts between mixed sized pointers.
791 }
792
794
795 // Codes for which we want to perform some z-specific combinations.
799 ISD::LOAD,
812 ISD::SRL,
813 ISD::SRA,
814 ISD::MUL,
815 ISD::SDIV,
816 ISD::UDIV,
817 ISD::SREM,
818 ISD::UREM,
821
822 // Handle intrinsics.
825
826 // We're not using SJLJ for exception handling, but they're implemented
827 // solely to support use of __builtin_setjmp / __builtin_longjmp.
830
831 // We want to use MVC in preference to even a single load/store pair.
832 MaxStoresPerMemcpy = Subtarget.hasVector() ? 2 : 0;
834
835 // Same with memmove.
836 MaxStoresPerMemmove = Subtarget.hasVector() ? 2 : 0;
838
839 // The main memset sequence is a byte store followed by an MVC.
840 // Two STC or MV..I stores win over that, but the kind of fused stores
841 // generated by target-independent code don't when the byte value is
842 // variable. E.g. "STC <reg>;MHI <reg>,257;STH <reg>" is not better
843 // than "STC;MVC". Handle the choice in target-specific code instead.
844 MaxStoresPerMemset = Subtarget.hasVector() ? 2 : 0;
846
847 // Default to having -disable-strictnode-mutation on
848 IsStrictFPEnabled = true;
849}
850
852 return Subtarget.hasSoftFloat();
853}
854
857 // Widen subvectors to the full width rather than promoting integer
858 // elements. This is better because:
859 //
860 // (a) it means that we can handle the ABI for passing and returning
861 // sub-128 vectors without having to handle them as legal types.
862 //
863 // (b) we don't have instructions to extend on load and truncate on store,
864 // so promoting the integers is less efficient.
865 //
866 // (c) there are no multiplication instructions for the widest integer
867 // type (v2i64).
868
869 // Expand (narrow) f16 vectors during type legalization to avoid
870 // operations for all elements as with expansion after widening. Without
871 // vector support, v2i64 is only legal as a GR128 pair, so do not widen or
872 // promote to it.
873 if (!Subtarget.hasVector() || VT.getScalarType() == MVT::f16)
876 if (VT.getScalarSizeInBits() % 8 == 0)
877 return TypeWidenVector;
879}
880
882 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
883 unsigned &NumIntermediates, MVT &RegisterVT) const {
884 // Pass fp16 vectors in VR(s).
885 if (Subtarget.hasVector() && VT.isVectorOf(MVT::f16)) {
886 IntermediateVT = RegisterVT = MVT::v8f16;
887 return NumIntermediates =
889 }
891 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
892 // Without vector support, v2i64 is a GR128 pair, which is never used to pass
893 // values. Pass the elements individually.
894 if (RegisterVT == MVT::v2i64 && !Subtarget.hasVector()) {
895 IntermediateVT = RegisterVT = MVT::i64;
896 NumIntermediates *= 2;
897 NumRegs *= 2;
898 }
899 return NumRegs;
900}
901
904 EVT VT) const {
905 // 128-bit single-element vector types are passed like other vectors,
906 // not like their element type.
907 if (Subtarget.hasVector() && VT.isVector() && VT.getSizeInBits() == 128 &&
908 VT.getVectorNumElements() == 1)
909 return MVT::v16i8;
910 // Pass fp16 vectors in VR(s).
911 if (Subtarget.hasVector() && VT.isVectorOf(MVT::f16))
912 return MVT::v8f16;
913 MVT RegisterVT =
915 if (RegisterVT == MVT::v2i64 && !Subtarget.hasVector())
916 return MVT::i64;
917 return RegisterVT;
918}
919
921 LLVMContext &Context, CallingConv::ID CC, EVT VT) const {
922 // Pass fp16 vectors in VR(s).
923 if (Subtarget.hasVector() && VT.isVectorOf(MVT::f16))
925 unsigned NumRegs =
927 MVT RegisterVT =
929 if (RegisterVT == MVT::v2i64 && !Subtarget.hasVector())
930 return NumRegs * 2;
931 return NumRegs;
932}
933
935 LLVMContext &, EVT VT) const {
936 if (!VT.isVector())
937 return MVT::i32;
939}
940
942 const MachineFunction &MF, EVT VT) const {
943 if (useSoftFloat())
944 return false;
945
946 VT = VT.getScalarType();
947
948 if (!VT.isSimple())
949 return false;
950
951 switch (VT.getSimpleVT().SimpleTy) {
952 case MVT::f32:
953 case MVT::f64:
954 return true;
955 case MVT::f128:
956 return Subtarget.hasVectorEnhancements1();
957 default:
958 break;
959 }
960
961 return false;
962}
963
964// Return true if the constant can be generated with a vector instruction,
965// such as VGM, VGMB or VREPI.
967 const SystemZSubtarget &Subtarget) {
968 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
969 if (!Subtarget.hasVector() ||
970 (isFP128 && !Subtarget.hasVectorEnhancements1()))
971 return false;
972
973 // Try using VECTOR GENERATE BYTE MASK. This is the architecturally-
974 // preferred way of creating all-zero and all-one vectors so give it
975 // priority over other methods below.
976 unsigned Mask = 0;
977 unsigned I = 0;
978 for (; I < SystemZ::VectorBytes; ++I) {
979 uint64_t Byte = IntBits.lshr(I * 8).trunc(8).getZExtValue();
980 if (Byte == 0xff)
981 Mask |= 1ULL << I;
982 else if (Byte != 0)
983 break;
984 }
985 if (I == SystemZ::VectorBytes) {
986 Opcode = SystemZISD::BYTE_MASK;
987 OpVals.push_back(Mask);
989 return true;
990 }
991
992 if (SplatBitSize > 64)
993 return false;
994
995 auto TryValue = [&](uint64_t Value) -> bool {
996 // Try VECTOR REPLICATE IMMEDIATE
997 int64_t SignedValue = SignExtend64(Value, SplatBitSize);
998 if (isInt<16>(SignedValue)) {
999 OpVals.push_back(((unsigned) SignedValue));
1000 Opcode = SystemZISD::REPLICATE;
1002 SystemZ::VectorBits / SplatBitSize);
1003 return true;
1004 }
1005 // Try VECTOR GENERATE MASK
1006 unsigned Start, End;
1007 if (TII->isRxSBGMask(Value, SplatBitSize, Start, End)) {
1008 // isRxSBGMask returns the bit numbers for a full 64-bit value, with 0
1009 // denoting 1 << 63 and 63 denoting 1. Convert them to bit numbers for
1010 // an SplatBitSize value, so that 0 denotes 1 << (SplatBitSize-1).
1011 OpVals.push_back(Start - (64 - SplatBitSize));
1012 OpVals.push_back(End - (64 - SplatBitSize));
1013 Opcode = SystemZISD::ROTATE_MASK;
1015 SystemZ::VectorBits / SplatBitSize);
1016 return true;
1017 }
1018 return false;
1019 };
1020
1021 // First try assuming that any undefined bits above the highest set bit
1022 // and below the lowest set bit are 1s. This increases the likelihood of
1023 // being able to use a sign-extended element value in VECTOR REPLICATE
1024 // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
1025 uint64_t SplatBitsZ = SplatBits.getZExtValue();
1026 uint64_t SplatUndefZ = SplatUndef.getZExtValue();
1027 unsigned LowerBits = llvm::countr_zero(SplatBitsZ);
1028 unsigned UpperBits = llvm::countl_zero(SplatBitsZ);
1029 uint64_t Lower = SplatUndefZ & maskTrailingOnes<uint64_t>(LowerBits);
1030 uint64_t Upper = SplatUndefZ & maskLeadingOnes<uint64_t>(UpperBits);
1031 if (TryValue(SplatBitsZ | Upper | Lower))
1032 return true;
1033
1034 // Now try assuming that any undefined bits between the first and
1035 // last defined set bits are set. This increases the chances of
1036 // using a non-wraparound mask.
1037 uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
1038 return TryValue(SplatBitsZ | Middle);
1039}
1040
1042 if (IntImm.isSingleWord()) {
1043 IntBits = APInt(128, IntImm.getZExtValue());
1044 IntBits <<= (SystemZ::VectorBits - IntImm.getBitWidth());
1045 } else
1046 IntBits = IntImm;
1047 assert(IntBits.getBitWidth() == 128 && "Unsupported APInt.");
1048
1049 // Find the smallest splat.
1050 SplatBits = IntImm;
1051 unsigned Width = SplatBits.getBitWidth();
1052 while (Width > 8) {
1053 unsigned HalfSize = Width / 2;
1054 APInt HighValue = SplatBits.lshr(HalfSize).trunc(HalfSize);
1055 APInt LowValue = SplatBits.trunc(HalfSize);
1056
1057 // If the two halves do not match, stop here.
1058 if (HighValue != LowValue || 8 > HalfSize)
1059 break;
1060
1061 SplatBits = HighValue;
1062 Width = HalfSize;
1063 }
1064 SplatUndef = 0;
1065 SplatBitSize = Width;
1066}
1067
1069 assert(BVN->isConstant() && "Expected a constant BUILD_VECTOR");
1070 bool HasAnyUndefs;
1071
1072 // Get IntBits by finding the 128 bit splat.
1073 BVN->isConstantSplat(IntBits, SplatUndef, SplatBitSize, HasAnyUndefs, 128,
1074 true);
1075
1076 // Get SplatBits by finding the 8 bit or greater splat.
1077 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 8,
1078 true);
1079}
1080
1083 bool ForCodeSize) const {
1084 // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
1085 if (Imm.isZero() || Imm.isNegZero())
1086 return FPImmAction::Legal;
1087
1091}
1092
1095 MachineBasicBlock *MBB) const {
1096 DebugLoc DL = MI.getDebugLoc();
1097 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1098 const SystemZRegisterInfo *TRI = Subtarget.getRegisterInfo();
1099
1100 MachineFunction *MF = MBB->getParent();
1101 MachineRegisterInfo &MRI = MF->getRegInfo();
1102
1103 const BasicBlock *BB = MBB->getBasicBlock();
1104 MachineFunction::iterator I = ++MBB->getIterator();
1105
1106 Register DstReg = MI.getOperand(0).getReg();
1107 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
1108 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
1109 (void)TRI;
1110 Register MainDstReg = MRI.createVirtualRegister(RC);
1111 Register RestoreDstReg = MRI.createVirtualRegister(RC);
1112
1113 MVT PVT = getPointerTy(MF->getDataLayout());
1114 assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
1115 // For v = setjmp(buf), we generate.
1116 // Algorithm:
1117 //
1118 // ---------
1119 // | thisMBB |
1120 // ---------
1121 // |
1122 // ------------------------
1123 // | |
1124 // ---------- ---------------
1125 // | mainMBB | | restoreMBB |
1126 // | v = 0 | | v = 1 |
1127 // ---------- ---------------
1128 // | |
1129 // -------------------------
1130 // |
1131 // -----------------------------
1132 // | sinkMBB |
1133 // | phi(v_mainMBB,v_restoreMBB) |
1134 // -----------------------------
1135 // thisMBB:
1136 // buf[FPOffset] = Frame Pointer if hasFP.
1137 // buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB.
1138 // buf[BCOffset] = Backchain value if building with -mbackchain.
1139 // buf[SPOffset] = Stack Pointer.
1140 // buf[LPOffset] = We never write this slot with R13, gcc stores R13 always.
1141 // SjLjSetup restoreMBB
1142 // mainMBB:
1143 // v_main = 0
1144 // sinkMBB:
1145 // v = phi(v_main, v_restore)
1146 // restoreMBB:
1147 // v_restore = 1
1148
1149 MachineBasicBlock *ThisMBB = MBB;
1150 MachineBasicBlock *MainMBB = MF->CreateMachineBasicBlock(BB);
1151 MachineBasicBlock *SinkMBB = MF->CreateMachineBasicBlock(BB);
1152 MachineBasicBlock *RestoreMBB = MF->CreateMachineBasicBlock(BB);
1153
1154 MF->insert(I, MainMBB);
1155 MF->insert(I, SinkMBB);
1156 MF->push_back(RestoreMBB);
1157 RestoreMBB->setMachineBlockAddressTaken();
1158
1160
1161 // Transfer the remainder of BB and its successor edges to sinkMBB.
1162 SinkMBB->splice(SinkMBB->begin(), MBB,
1163 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
1165
1166 // thisMBB:
1167 const int64_t FPOffset = 0; // Slot 1.
1168 const int64_t LabelOffset = 1 * PVT.getStoreSize(); // Slot 2.
1169 const int64_t BCOffset = 2 * PVT.getStoreSize(); // Slot 3.
1170 const int64_t SPOffset = 3 * PVT.getStoreSize(); // Slot 4.
1171
1172 // Buf address.
1173 Register BufReg = MI.getOperand(1).getReg();
1174
1175 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
1176 Register LabelReg = MRI.createVirtualRegister(PtrRC);
1177
1178 // Prepare IP for longjmp.
1179 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::LARL), LabelReg)
1180 .addMBB(RestoreMBB);
1181 // Store IP for return from jmp, slot 2, offset = 1.
1182 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1183 .addReg(LabelReg)
1184 .addReg(BufReg)
1185 .addImm(LabelOffset)
1186 .addReg(0);
1187
1188 auto *SpecialRegs = Subtarget.getSpecialRegisters();
1189 bool HasFP = Subtarget.getFrameLowering()->hasFP(*MF);
1190 if (HasFP) {
1191 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1192 .addReg(SpecialRegs->getFramePointerRegister())
1193 .addReg(BufReg)
1194 .addImm(FPOffset)
1195 .addReg(0);
1196 }
1197
1198 // Store SP.
1199 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1200 .addReg(SpecialRegs->getStackPointerRegister())
1201 .addReg(BufReg)
1202 .addImm(SPOffset)
1203 .addReg(0);
1204
1205 // Slot 3(Offset = 2) Backchain value (if building with -mbackchain).
1206 bool BackChain = MF->getSubtarget<SystemZSubtarget>().hasBackChain();
1207 if (BackChain) {
1208 Register BCReg = MRI.createVirtualRegister(PtrRC);
1209 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
1210 MIB = BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::LG), BCReg)
1211 .addReg(SpecialRegs->getStackPointerRegister())
1212 .addImm(TFL->getBackchainOffset(*MF))
1213 .addReg(0);
1214
1215 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1216 .addReg(BCReg)
1217 .addReg(BufReg)
1218 .addImm(BCOffset)
1219 .addReg(0);
1220 }
1221
1222 // Setup.
1223 MIB = BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::EH_SjLj_Setup))
1224 .addMBB(RestoreMBB);
1225
1226 const SystemZRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1227 MIB.addRegMask(RegInfo->getNoPreservedMask());
1228
1229 ThisMBB->addSuccessor(MainMBB);
1230 ThisMBB->addSuccessor(RestoreMBB);
1231
1232 // mainMBB:
1233 BuildMI(MainMBB, DL, TII->get(SystemZ::LHI), MainDstReg).addImm(0);
1234 MainMBB->addSuccessor(SinkMBB);
1235
1236 // sinkMBB:
1237 BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII->get(SystemZ::PHI), DstReg)
1238 .addReg(MainDstReg)
1239 .addMBB(MainMBB)
1240 .addReg(RestoreDstReg)
1241 .addMBB(RestoreMBB);
1242
1243 // restoreMBB.
1244 BuildMI(RestoreMBB, DL, TII->get(SystemZ::LHI), RestoreDstReg).addImm(1);
1245 BuildMI(RestoreMBB, DL, TII->get(SystemZ::J)).addMBB(SinkMBB);
1246 RestoreMBB->addSuccessor(SinkMBB);
1247
1248 MI.eraseFromParent();
1249
1250 return SinkMBB;
1251}
1252
1255 MachineBasicBlock *MBB) const {
1256
1257 DebugLoc DL = MI.getDebugLoc();
1258 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1259
1260 MachineFunction *MF = MBB->getParent();
1261 MachineRegisterInfo &MRI = MF->getRegInfo();
1262
1263 MVT PVT = getPointerTy(MF->getDataLayout());
1264 assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
1265 Register BufReg = MI.getOperand(0).getReg();
1266 const TargetRegisterClass *RC = MRI.getRegClass(BufReg);
1267 auto *SpecialRegs = Subtarget.getSpecialRegisters();
1268
1269 Register Tmp = MRI.createVirtualRegister(RC);
1270 Register BCReg = MRI.createVirtualRegister(RC);
1271
1273
1274 const int64_t FPOffset = 0;
1275 const int64_t LabelOffset = 1 * PVT.getStoreSize();
1276 const int64_t BCOffset = 2 * PVT.getStoreSize();
1277 const int64_t SPOffset = 3 * PVT.getStoreSize();
1278 const int64_t LPOffset = 4 * PVT.getStoreSize();
1279
1280 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG), Tmp)
1281 .addReg(BufReg)
1282 .addImm(LabelOffset)
1283 .addReg(0);
1284
1285 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG),
1286 SpecialRegs->getFramePointerRegister())
1287 .addReg(BufReg)
1288 .addImm(FPOffset)
1289 .addReg(0);
1290
1291 // We are restoring R13 even though we never stored in setjmp from llvm,
1292 // as gcc always stores R13 in builtin_setjmp. We could have mixed code
1293 // gcc setjmp and llvm longjmp.
1294 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG), SystemZ::R13D)
1295 .addReg(BufReg)
1296 .addImm(LPOffset)
1297 .addReg(0);
1298
1299 bool BackChain = MF->getSubtarget<SystemZSubtarget>().hasBackChain();
1300 if (BackChain) {
1301 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG), BCReg)
1302 .addReg(BufReg)
1303 .addImm(BCOffset)
1304 .addReg(0);
1305 }
1306
1307 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG),
1308 SpecialRegs->getStackPointerRegister())
1309 .addReg(BufReg)
1310 .addImm(SPOffset)
1311 .addReg(0);
1312
1313 if (BackChain) {
1314 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
1315 BuildMI(*MBB, MI, DL, TII->get(SystemZ::STG))
1316 .addReg(BCReg)
1317 .addReg(SpecialRegs->getStackPointerRegister())
1318 .addImm(TFL->getBackchainOffset(*MF))
1319 .addReg(0);
1320 }
1321
1322 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::BR)).addReg(Tmp);
1323
1324 MI.eraseFromParent();
1325 return MBB;
1326}
1327
1329 const MachineFunction &MF) const {
1330 // Without vector support, a v2i64 store would just be split again.
1331 return MemVT != MVT::v2i64 || Subtarget.hasVector();
1332}
1333
1335 EVT VecVT) const {
1336 // Without vector support, a v2i64 is just a pair of GPRs.
1337 return !Subtarget.hasVector();
1338}
1339
1340/// Returns true if stack probing through inline assembly is requested.
1342 // If the function specifically requests inline stack probes, emit them.
1343 if (MF.getFunction().hasFnAttribute("probe-stack"))
1344 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
1345 "inline-asm";
1346 return false;
1347}
1348
1353
1358
1361 const AtomicRMWInst *RMW) const {
1362 // Don't expand subword operations as they require special treatment.
1363 if (RMW->getType()->isIntegerTy(8) || RMW->getType()->isIntegerTy(16))
1365
1366 // Don't expand if there is a target instruction available.
1367 if (Subtarget.hasInterlockedAccess1() &&
1368 (RMW->getType()->isIntegerTy(32) || RMW->getType()->isIntegerTy(64)) &&
1375
1377}
1378
1380 // We can use CGFI or CLGFI.
1381 return isInt<32>(Imm) || isUInt<32>(Imm);
1382}
1383
1385 // We can use ALGFI or SLGFI.
1386 return isUInt<32>(Imm) || isUInt<32>(-Imm);
1387}
1388
1390 EVT VT, unsigned, Align, MachineMemOperand::Flags, unsigned *Fast) const {
1391 // Unaligned accesses should never be slower than the expanded version.
1392 // We check specifically for aligned accesses in the few cases where
1393 // they are required.
1394 if (Fast)
1395 *Fast = 1;
1396 return true;
1397}
1398
1400 EVT VT = Y.getValueType();
1401
1402 // We can use NC(G)RK for types in GPRs ...
1403 if (VT == MVT::i32 || VT == MVT::i64)
1404 return Subtarget.hasMiscellaneousExtensions3();
1405
1406 // ... or VNC for types in VRs.
1407 if (VT.isVector() || VT == MVT::i128)
1408 return Subtarget.hasVector();
1409
1410 return false;
1411}
1412
1413// Information about the addressing mode for a memory access.
1415 // True if a long displacement is supported.
1417
1418 // True if use of index register is supported.
1420
1421 AddressingMode(bool LongDispl, bool IdxReg) :
1422 LongDisplacement(LongDispl), IndexReg(IdxReg) {}
1423};
1424
1425// Return the desired addressing mode for a Load which has only one use (in
1426// the same block) which is a Store.
1428 Type *Ty) {
1429 // With vector support a Load->Store combination may be combined to either
1430 // an MVC or vector operations and it seems to work best to allow the
1431 // vector addressing mode.
1432 if (HasVector)
1433 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
1434
1435 // Otherwise only the MVC case is special.
1436 bool MVC = Ty->isIntegerTy(8);
1437 return AddressingMode(!MVC/*LongDispl*/, !MVC/*IdxReg*/);
1438}
1439
1440// Return the addressing mode which seems most desirable given an LLVM
1441// Instruction pointer.
1442static AddressingMode
1445 switch (II->getIntrinsicID()) {
1446 default: break;
1447 case Intrinsic::memset:
1448 case Intrinsic::memmove:
1449 case Intrinsic::memcpy:
1450 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
1451 }
1452 }
1453
1454 if (isa<LoadInst>(I) && I->hasOneUse()) {
1455 auto *SingleUser = cast<Instruction>(*I->user_begin());
1456 if (SingleUser->getParent() == I->getParent()) {
1457 if (isa<ICmpInst>(SingleUser)) {
1458 if (auto *C = dyn_cast<ConstantInt>(SingleUser->getOperand(1)))
1459 if (C->getBitWidth() <= 64 &&
1460 (isInt<16>(C->getSExtValue()) || isUInt<16>(C->getZExtValue())))
1461 // Comparison of memory with 16 bit signed / unsigned immediate
1462 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
1463 } else if (isa<StoreInst>(SingleUser))
1464 // Load->Store
1465 return getLoadStoreAddrMode(HasVector, I->getType());
1466 }
1467 } else if (auto *StoreI = dyn_cast<StoreInst>(I)) {
1468 if (auto *LoadI = dyn_cast<LoadInst>(StoreI->getValueOperand()))
1469 if (LoadI->hasOneUse() && LoadI->getParent() == I->getParent())
1470 // Load->Store
1471 return getLoadStoreAddrMode(HasVector, LoadI->getType());
1472 }
1473
1474 if (HasVector && (isa<LoadInst>(I) || isa<StoreInst>(I))) {
1475
1476 // * Use LDE instead of LE/LEY for z13 to avoid partial register
1477 // dependencies (LDE only supports small offsets).
1478 // * Utilize the vector registers to hold floating point
1479 // values (vector load / store instructions only support small
1480 // offsets).
1481
1482 Type *MemAccessTy = (isa<LoadInst>(I) ? I->getType() :
1483 I->getOperand(0)->getType());
1484 bool IsFPAccess = MemAccessTy->isFloatingPointTy();
1485 bool IsVectorAccess = MemAccessTy->isVectorTy();
1486
1487 // A store of an extracted vector element will be combined into a VSTE type
1488 // instruction.
1489 if (!IsVectorAccess && isa<StoreInst>(I)) {
1490 Value *DataOp = I->getOperand(0);
1491 if (isa<ExtractElementInst>(DataOp))
1492 IsVectorAccess = true;
1493 }
1494
1495 // A load which gets inserted into a vector element will be combined into a
1496 // VLE type instruction.
1497 if (!IsVectorAccess && isa<LoadInst>(I) && I->hasOneUse()) {
1498 User *LoadUser = *I->user_begin();
1499 if (isa<InsertElementInst>(LoadUser))
1500 IsVectorAccess = true;
1501 }
1502
1503 if (IsFPAccess || IsVectorAccess)
1504 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
1505 }
1506
1507 return AddressingMode(true/*LongDispl*/, true/*IdxReg*/);
1508}
1509
1511 const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I) const {
1512 // Punt on globals for now, although they can be used in limited
1513 // RELATIVE LONG cases.
1514 if (AM.BaseGV)
1515 return false;
1516
1517 // Require a 20-bit signed offset.
1518 if (!isInt<20>(AM.BaseOffs))
1519 return false;
1520
1521 bool RequireD12 =
1522 Subtarget.hasVector() && (Ty->isVectorTy() || Ty->isIntegerTy(128));
1523 AddressingMode SupportedAM(!RequireD12, true);
1524 if (I != nullptr)
1525 SupportedAM = supportedAddressingMode(I, Subtarget.hasVector());
1526
1527 if (!SupportedAM.LongDisplacement && !isUInt<12>(AM.BaseOffs))
1528 return false;
1529
1530 if (!SupportedAM.IndexReg)
1531 // No indexing allowed.
1532 return AM.Scale == 0;
1533 else
1534 // Indexing is OK but no scale factor can be applied.
1535 return AM.Scale == 0 || AM.Scale == 1;
1536}
1537
1539 LLVMContext &Context, std::vector<EVT> &MemOps, unsigned Limit,
1540 const MemOp &Op, unsigned DstAS, unsigned SrcAS,
1541 const AttributeList &FuncAttributes, EVT *LargestVT) const {
1542
1543 assert(Limit != ~0U &&
1544 "Expected EmitTargetCodeForMemXXX() to handle AlwaysInline cases.");
1545
1546 if (Op.isZeroMemset())
1547 return false; // Memset zero: Use XC.
1548
1549 const int MVCFastLen = 16;
1550 // Use MVC up to 16 bytes for memcpy. Small memset uses STC/MVI for first
1551 // byte.
1552 if (Op.isMemcpy() && Op.size() <= MVCFastLen)
1553 return false;
1554 if (Op.isMemset() && Op.size() - 1 <= MVCFastLen)
1555 return false;
1556
1557 // Avoid unaligned VL/VST:s.
1558 if ((Op.size() >= 16 && !Op.isAligned(Align(8))) ||
1559 (Op.size() >= 25 && Op.size() <= 31))
1560 return false;
1561
1563 Context, MemOps, Limit, Op, DstAS, SrcAS, FuncAttributes, LargestVT);
1564}
1565
1567 LLVMContext &Context, const MemOp &Op,
1568 const AttributeList &FuncAttributes) const {
1569 return Subtarget.hasVector() ? MVT::v2i64 : MVT::Other;
1570}
1571
1572bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
1573 if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
1574 return false;
1575 unsigned FromBits = FromType->getPrimitiveSizeInBits().getFixedValue();
1576 unsigned ToBits = ToType->getPrimitiveSizeInBits().getFixedValue();
1577 return FromBits > ToBits;
1578}
1579
1581 if (!FromVT.isInteger() || !ToVT.isInteger())
1582 return false;
1583 unsigned FromBits = FromVT.getFixedSizeInBits();
1584 unsigned ToBits = ToVT.getFixedSizeInBits();
1585 return FromBits > ToBits;
1586}
1587
1588//===----------------------------------------------------------------------===//
1589// Inline asm support
1590//===----------------------------------------------------------------------===//
1591
1594 if (Constraint.size() == 1) {
1595 switch (Constraint[0]) {
1596 case 'a': // Address register
1597 case 'd': // Data register (equivalent to 'r')
1598 case 'f': // Floating-point register
1599 case 'h': // High-part register
1600 case 'r': // General-purpose register
1601 case 'v': // Vector register
1602 return C_RegisterClass;
1603
1604 case 'Q': // Memory with base and unsigned 12-bit displacement
1605 case 'R': // Likewise, plus an index
1606 case 'S': // Memory with base and signed 20-bit displacement
1607 case 'T': // Likewise, plus an index
1608 case 'm': // Equivalent to 'T'.
1609 return C_Memory;
1610
1611 case 'I': // Unsigned 8-bit constant
1612 case 'J': // Unsigned 12-bit constant
1613 case 'K': // Signed 16-bit constant
1614 case 'L': // Signed 20-bit displacement (on all targets we support)
1615 case 'M': // 0x7fffffff
1616 return C_Immediate;
1617
1618 default:
1619 break;
1620 }
1621 } else if (Constraint.size() == 2 && Constraint[0] == 'Z') {
1622 switch (Constraint[1]) {
1623 case 'Q': // Address with base and unsigned 12-bit displacement
1624 case 'R': // Likewise, plus an index
1625 case 'S': // Address with base and signed 20-bit displacement
1626 case 'T': // Likewise, plus an index
1627 return C_Address;
1628
1629 default:
1630 break;
1631 }
1632 } else if (Constraint.size() == 5 && Constraint.starts_with("{")) {
1633 if (StringRef("{@cc}").compare(Constraint) == 0)
1634 return C_Other;
1635 }
1636 return TargetLowering::getConstraintType(Constraint);
1637}
1638
1641 AsmOperandInfo &Info, const char *Constraint) const {
1643 Value *CallOperandVal = Info.CallOperandVal;
1644 // If we don't have a value, we can't do a match,
1645 // but allow it at the lowest weight.
1646 if (!CallOperandVal)
1647 return CW_Default;
1648 Type *type = CallOperandVal->getType();
1649 // Look at the constraint type.
1650 switch (*Constraint) {
1651 default:
1652 Weight = TargetLowering::getSingleConstraintMatchWeight(Info, Constraint);
1653 break;
1654
1655 case 'a': // Address register
1656 case 'd': // Data register (equivalent to 'r')
1657 case 'h': // High-part register
1658 case 'r': // General-purpose register
1659 Weight =
1660 CallOperandVal->getType()->isIntegerTy() ? CW_Register : CW_Default;
1661 break;
1662
1663 case 'f': // Floating-point register
1664 if (!useSoftFloat())
1665 Weight = type->isFloatingPointTy() ? CW_Register : CW_Default;
1666 break;
1667
1668 case 'v': // Vector register
1669 if (Subtarget.hasVector())
1670 Weight = (type->isVectorTy() || type->isFloatingPointTy()) ? CW_Register
1671 : CW_Default;
1672 break;
1673
1674 case 'I': // Unsigned 8-bit constant
1675 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1676 if (isUInt<8>(C->getZExtValue()))
1677 Weight = CW_Constant;
1678 break;
1679
1680 case 'J': // Unsigned 12-bit constant
1681 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1682 if (isUInt<12>(C->getZExtValue()))
1683 Weight = CW_Constant;
1684 break;
1685
1686 case 'K': // Signed 16-bit constant
1687 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1688 if (isInt<16>(C->getSExtValue()))
1689 Weight = CW_Constant;
1690 break;
1691
1692 case 'L': // Signed 20-bit displacement (on all targets we support)
1693 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1694 if (isInt<20>(C->getSExtValue()))
1695 Weight = CW_Constant;
1696 break;
1697
1698 case 'M': // 0x7fffffff
1699 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1700 if (C->getZExtValue() == 0x7fffffff)
1701 Weight = CW_Constant;
1702 break;
1703 }
1704 return Weight;
1705}
1706
1707// Parse a "{tNNN}" register constraint for which the register type "t"
1708// has already been verified. MC is the class associated with "t" and
1709// Map maps 0-based register numbers to LLVM register numbers.
1710static std::pair<unsigned, const TargetRegisterClass *>
1712 const unsigned *Map, unsigned Size) {
1713 assert(*(Constraint.end()-1) == '}' && "Missing '}'");
1714 if (isdigit(Constraint[2])) {
1715 unsigned Index;
1716 bool Failed =
1717 Constraint.slice(2, Constraint.size() - 1).getAsInteger(10, Index);
1718 if (!Failed && Index < Size && Map[Index])
1719 return std::make_pair(Map[Index], RC);
1720 }
1721 return std::make_pair(0U, nullptr);
1722}
1723
1724std::pair<unsigned, const TargetRegisterClass *>
1726 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
1727 if (Constraint.size() == 1) {
1728 // GCC Constraint Letters
1729 switch (Constraint[0]) {
1730 default: break;
1731 case 'd': // Data register (equivalent to 'r')
1732 case 'r': // General-purpose register
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.getSizeInBits() == 16)
1752 return std::make_pair(0U, &SystemZ::FP16BitRegClass);
1753 else if (VT.getSizeInBits() == 64)
1754 return std::make_pair(0U, &SystemZ::FP64BitRegClass);
1755 else if (VT.getSizeInBits() == 128)
1756 return std::make_pair(0U, &SystemZ::FP128BitRegClass);
1757 return std::make_pair(0U, &SystemZ::FP32BitRegClass);
1758 }
1759 break;
1760
1761 case 'v': // Vector register
1762 if (Subtarget.hasVector()) {
1763 if (VT.getSizeInBits() == 16)
1764 return std::make_pair(0U, &SystemZ::VR16BitRegClass);
1765 if (VT.getSizeInBits() == 32)
1766 return std::make_pair(0U, &SystemZ::VR32BitRegClass);
1767 if (VT.getSizeInBits() == 64)
1768 return std::make_pair(0U, &SystemZ::VR64BitRegClass);
1769 return std::make_pair(0U, &SystemZ::VR128BitRegClass);
1770 }
1771 break;
1772 }
1773 }
1774 if (Constraint.starts_with("{")) {
1775
1776 // A clobber constraint (e.g. ~{f0}) will have MVT::Other which is illegal
1777 // to check the size on.
1778 auto getVTSizeInBits = [&VT]() {
1779 return VT == MVT::Other ? 0 : VT.getSizeInBits();
1780 };
1781
1782 // We need to override the default register parsing for GPRs and FPRs
1783 // because the interpretation depends on VT. The internal names of
1784 // the registers are also different from the external names
1785 // (F0D and F0S instead of F0, etc.).
1786 if (Constraint[1] == 'r') {
1787 if (getVTSizeInBits() == 32)
1788 return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
1790 if (getVTSizeInBits() == 128)
1791 return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
1793 return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
1795 }
1796 if (Constraint[1] == 'f') {
1797 if (useSoftFloat())
1798 return std::make_pair(
1799 0u, static_cast<const TargetRegisterClass *>(nullptr));
1800 if (getVTSizeInBits() == 16)
1801 return parseRegisterNumber(Constraint, &SystemZ::FP16BitRegClass,
1803 if (getVTSizeInBits() == 32)
1804 return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
1806 if (getVTSizeInBits() == 128)
1807 return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
1809 return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
1811 }
1812 if (Constraint[1] == 'v') {
1813 if (!Subtarget.hasVector())
1814 return std::make_pair(
1815 0u, static_cast<const TargetRegisterClass *>(nullptr));
1816 if (getVTSizeInBits() == 16)
1817 return parseRegisterNumber(Constraint, &SystemZ::VR16BitRegClass,
1819 if (getVTSizeInBits() == 32)
1820 return parseRegisterNumber(Constraint, &SystemZ::VR32BitRegClass,
1822 if (getVTSizeInBits() == 64)
1823 return parseRegisterNumber(Constraint, &SystemZ::VR64BitRegClass,
1825 return parseRegisterNumber(Constraint, &SystemZ::VR128BitRegClass,
1827 }
1828 if (Constraint[1] == '@') {
1829 if (StringRef("{@cc}").compare(Constraint) == 0)
1830 return std::make_pair(SystemZ::CC, &SystemZ::CCRRegClass);
1831 }
1832 }
1833 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1834}
1835
1836// FIXME? Maybe this could be a TableGen attribute on some registers and
1837// this table could be generated automatically from RegInfo.
1840 const MachineFunction &MF) const {
1841 Register Reg =
1843 .Case("r4", Subtarget.isTargetXPLINK64() ? SystemZ::R4D
1844 : SystemZ::NoRegister)
1845 .Case("r15",
1846 Subtarget.isTargetELF() ? SystemZ::R15D : SystemZ::NoRegister)
1847 .Default(Register());
1848
1849 return Reg;
1850}
1851
1853 ExceptionHandling EH, const Constant *PersonalityFn) const {
1854 return Subtarget.isTargetXPLINK64() ? SystemZ::R1D : SystemZ::R6D;
1855}
1856
1858 ExceptionHandling EH, const Constant *PersonalityFn) const {
1859 return Subtarget.isTargetXPLINK64() ? SystemZ::R2D : SystemZ::R7D;
1860}
1861
1862// Convert condition code in CCReg to an i32 value.
1864 SDLoc DL(CCReg);
1865 SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, CCReg);
1866 return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM,
1867 DAG.getConstant(SystemZ::IPM_CC, DL, MVT::i32));
1868}
1869
1870// Lower @cc targets via setcc.
1872 SDValue &Chain, SDValue &Glue, const SDLoc &DL,
1873 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
1874 if (StringRef("{@cc}").compare(OpInfo.ConstraintCode) != 0)
1875 return SDValue();
1876
1877 // Check that return type is valid.
1878 if (OpInfo.ConstraintVT.isVector() || !OpInfo.ConstraintVT.isInteger() ||
1879 OpInfo.ConstraintVT.getSizeInBits() < 8)
1880 report_fatal_error("Glue output operand is of invalid type");
1881
1882 if (Glue.getNode()) {
1883 Glue = DAG.getCopyFromReg(Chain, DL, SystemZ::CC, MVT::i32, Glue);
1884 Chain = Glue.getValue(1);
1885 } else
1886 Glue = DAG.getCopyFromReg(Chain, DL, SystemZ::CC, MVT::i32);
1887 return getCCResult(DAG, Glue);
1888}
1889
1891 SDValue Op, StringRef Constraint, std::vector<SDValue> &Ops,
1892 SelectionDAG &DAG) const {
1893 // Only support length 1 constraints for now.
1894 if (Constraint.size() == 1) {
1895 switch (Constraint[0]) {
1896 case 'I': // Unsigned 8-bit constant
1897 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1898 if (isUInt<8>(C->getZExtValue()))
1899 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1900 Op.getValueType()));
1901 return;
1902
1903 case 'J': // Unsigned 12-bit constant
1904 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1905 if (isUInt<12>(C->getZExtValue()))
1906 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1907 Op.getValueType()));
1908 return;
1909
1910 case 'K': // Signed 16-bit constant
1911 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1912 if (isInt<16>(C->getSExtValue()))
1913 Ops.push_back(DAG.getSignedTargetConstant(
1914 C->getSExtValue(), SDLoc(Op), Op.getValueType()));
1915 return;
1916
1917 case 'L': // Signed 20-bit displacement (on all targets we support)
1918 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1919 if (isInt<20>(C->getSExtValue()))
1920 Ops.push_back(DAG.getSignedTargetConstant(
1921 C->getSExtValue(), SDLoc(Op), Op.getValueType()));
1922 return;
1923
1924 case 'M': // 0x7fffffff
1925 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1926 if (C->getZExtValue() == 0x7fffffff)
1927 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1928 Op.getValueType()));
1929 return;
1930 }
1931 }
1933}
1934
1935//===----------------------------------------------------------------------===//
1936// Calling conventions
1937//===----------------------------------------------------------------------===//
1938
1939#define GET_CALLING_CONV_IMPL
1940#include "SystemZGenCallingConv.inc"
1941
1943 CallingConv::ID) const {
1944 static const MCPhysReg ScratchRegs[] = { SystemZ::R0D, SystemZ::R1D,
1945 SystemZ::R14D, 0 };
1946 return ScratchRegs;
1947}
1948
1950 Type *ToType) const {
1951 return isTruncateFree(FromType, ToType);
1952}
1953
1955 return CI->isTailCall();
1956}
1957
1958// Value is a value that has been passed to us in the location described by VA
1959// (and so has type VA.getLocVT()). Convert Value to VA.getValVT(), chaining
1960// any loads onto Chain.
1962 CCValAssign &VA, SDValue Chain,
1963 SDValue Value) {
1964 // If the argument has been promoted from a smaller type, insert an
1965 // assertion to capture this.
1966 if (VA.getLocInfo() == CCValAssign::SExt)
1968 DAG.getValueType(VA.getValVT()));
1969 else if (VA.getLocInfo() == CCValAssign::ZExt)
1971 DAG.getValueType(VA.getValVT()));
1972
1973 if (VA.isExtInLoc())
1974 Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
1975 else if (VA.getLocInfo() == CCValAssign::BCvt) {
1976 // If this is a short vector argument loaded from the stack,
1977 // extend from i64 to full vector size and then bitcast.
1978 assert(VA.getLocVT() == MVT::i64);
1979 assert(VA.getValVT().isVector());
1980 Value = DAG.getBuildVector(MVT::v2i64, DL, {Value, DAG.getUNDEF(MVT::i64)});
1981 Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
1982 } else
1983 assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
1984 return Value;
1985}
1986
1987// Value is a value of type VA.getValVT() that we need to copy into
1988// the location described by VA. Return a copy of Value converted to
1989// VA.getValVT(). The caller is responsible for handling indirect values.
1991 CCValAssign &VA, SDValue Value) {
1992 switch (VA.getLocInfo()) {
1993 case CCValAssign::SExt:
1994 return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
1995 case CCValAssign::ZExt:
1996 return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
1997 case CCValAssign::AExt:
1998 return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
1999 case CCValAssign::BCvt: {
2000 assert(VA.getLocVT() == MVT::i64 || VA.getLocVT() == MVT::i128);
2001 assert(VA.getValVT().isVector() || VA.getValVT() == MVT::f32 ||
2002 VA.getValVT() == MVT::f64 || VA.getValVT() == MVT::f128);
2003 // For an f32 vararg we need to first promote it to an f64 and then
2004 // bitcast it to an i64.
2005 if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i64)
2006 Value = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f64, Value);
2007 MVT BitCastToType = VA.getValVT().isVector() && VA.getLocVT() == MVT::i64
2008 ? MVT::v2i64
2009 : VA.getLocVT();
2010 Value = DAG.getNode(ISD::BITCAST, DL, BitCastToType, Value);
2011 // For ELF, this is a short vector argument to be stored to the stack,
2012 // bitcast to v2i64 and then extract first element.
2013 if (BitCastToType == MVT::v2i64)
2014 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
2015 DAG.getConstant(0, DL, MVT::i32));
2016 return Value;
2017 }
2018 case CCValAssign::Full:
2019 return Value;
2020 default:
2021 llvm_unreachable("Unhandled getLocInfo()");
2022 }
2023}
2024
2026 SDLoc DL(In);
2027 SDValue Lo, Hi;
2028 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128)) {
2029 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, In);
2030 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
2031 DAG.getNode(ISD::SRL, DL, MVT::i128, In,
2032 DAG.getConstant(64, DL, MVT::i32)));
2033 } else {
2034 std::tie(Lo, Hi) = DAG.SplitScalar(In, DL, MVT::i64, MVT::i64);
2035 }
2036
2037 return DAG.getNode(SystemZISD::PAIR128, DL, MVT::v2i64, Hi, Lo);
2038}
2039
2041 SDLoc DL(In);
2042 SDValue Hi = DAG.getTargetExtractSubreg(SystemZ::subreg_h64,
2043 DL, MVT::i64, In);
2044 SDValue Lo = DAG.getTargetExtractSubreg(SystemZ::subreg_l64,
2045 DL, MVT::i64, In);
2046
2047 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128)) {
2048 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, Lo);
2049 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, Hi);
2050 Hi = DAG.getNode(ISD::SHL, DL, MVT::i128, Hi,
2051 DAG.getConstant(64, DL, MVT::i32));
2052 return DAG.getNode(ISD::OR, DL, MVT::i128, Lo, Hi);
2053 } else {
2054 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128, Lo, Hi);
2055 }
2056}
2057
2059 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
2060 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
2061 EVT ValueVT = Val.getValueType();
2062 if (ValueVT.getSizeInBits() == 128 && NumParts == 1 && PartVT == MVT::Untyped) {
2063 // Inline assembly operand.
2064 Parts[0] = lowerI128ToGR128(DAG, DAG.getBitcast(MVT::i128, Val));
2065 return true;
2066 }
2067
2068 return false;
2069}
2070
2072 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
2073 MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const {
2074 if (ValueVT.getSizeInBits() == 128 && NumParts == 1 && PartVT == MVT::Untyped) {
2075 // Inline assembly operand.
2076 SDValue Res = lowerGR128ToI128(DAG, Parts[0]);
2077 return DAG.getBitcast(ValueVT, Res);
2078 }
2079
2080 return SDValue();
2081}
2082
2083// The first part of a split stack argument is at index I in Args (and
2084// ArgLocs). Return the type of a part and the number of them by reference.
2085template <class ArgTy>
2087 SmallVector<CCValAssign, 16> &ArgLocs, unsigned I,
2088 MVT &PartVT, unsigned &NumParts) {
2089 if (!Args[I].Flags.isSplit())
2090 return false;
2091 assert(I < ArgLocs.size() && ArgLocs.size() == Args.size() &&
2092 "ArgLocs havoc.");
2093 PartVT = ArgLocs[I].getValVT();
2094 NumParts = 1;
2095 for (unsigned PartIdx = I + 1;; ++PartIdx) {
2096 assert(PartIdx != ArgLocs.size() && "SplitEnd not found.");
2097 assert(ArgLocs[PartIdx].getValVT() == PartVT && "Unsupported split.");
2098 ++NumParts;
2099 if (Args[PartIdx].Flags.isSplitEnd())
2100 break;
2101 }
2102 return true;
2103}
2104
2106 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
2107 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2108 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2110 MachineFrameInfo &MFI = MF.getFrameInfo();
2111 MachineRegisterInfo &MRI = MF.getRegInfo();
2112 SystemZMachineFunctionInfo *FuncInfo =
2114 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>();
2115 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2116
2117 // Assign locations to all of the incoming arguments.
2119 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2120 CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
2121 FuncInfo->setSizeOfFnParams(CCInfo.getStackSize());
2122
2123 unsigned NumFixedGPRs = 0;
2124 unsigned NumFixedFPRs = 0;
2125 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
2126 SDValue ArgValue;
2127 CCValAssign &VA = ArgLocs[I];
2128 EVT LocVT = VA.getLocVT();
2129 if (VA.isRegLoc()) {
2130 // Arguments passed in registers
2131 const TargetRegisterClass *RC;
2132 switch (LocVT.getSimpleVT().SimpleTy) {
2133 default:
2134 // Integers smaller than i64 should be promoted to i64.
2135 llvm_unreachable("Unexpected argument type");
2136 case MVT::i32:
2137 NumFixedGPRs += 1;
2138 RC = &SystemZ::GR32BitRegClass;
2139 break;
2140 case MVT::i64:
2141 NumFixedGPRs += 1;
2142 RC = &SystemZ::GR64BitRegClass;
2143 break;
2144 case MVT::f16:
2145 NumFixedFPRs += 1;
2146 RC = &SystemZ::FP16BitRegClass;
2147 break;
2148 case MVT::f32:
2149 NumFixedFPRs += 1;
2150 RC = &SystemZ::FP32BitRegClass;
2151 break;
2152 case MVT::f64:
2153 NumFixedFPRs += 1;
2154 RC = &SystemZ::FP64BitRegClass;
2155 break;
2156 case MVT::f128:
2157 NumFixedFPRs += 2;
2158 RC = &SystemZ::FP128BitRegClass;
2159 break;
2160 case MVT::v16i8:
2161 case MVT::v8i16:
2162 case MVT::v4i32:
2163 case MVT::v2i64:
2164 case MVT::v8f16:
2165 case MVT::v4f32:
2166 case MVT::v2f64:
2167 RC = &SystemZ::VR128BitRegClass;
2168 break;
2169 }
2170
2171 Register VReg = MRI.createVirtualRegister(RC);
2172 MRI.addLiveIn(VA.getLocReg(), VReg);
2173 ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
2174 } else {
2175 assert(VA.isMemLoc() && "Argument not register or memory");
2176
2177 // Create the frame index object for this incoming parameter.
2178 // FIXME: Pre-include call frame size in the offset, should not
2179 // need to manually add it here.
2180 int64_t ArgSPOffset = VA.getLocMemOffset();
2181 if (Subtarget.isTargetXPLINK64()) {
2182 auto &XPRegs =
2183 Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
2184 ArgSPOffset += XPRegs.getCallFrameSize();
2185 }
2186 int FI =
2187 MFI.CreateFixedObject(LocVT.getSizeInBits() / 8, ArgSPOffset, true);
2188
2189 // Create the SelectionDAG nodes corresponding to a load
2190 // from this parameter. Unpromoted ints and floats are
2191 // passed as right-justified 8-byte values.
2192 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2193 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32 ||
2194 VA.getLocVT() == MVT::f16) {
2195 unsigned SlotOffs = VA.getLocVT() == MVT::f16 ? 6 : 4;
2196 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2197 DAG.getIntPtrConstant(SlotOffs, DL));
2198 }
2199 ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
2201 }
2202
2203 // Convert the value of the argument register into the value that's
2204 // being passed.
2205 if (VA.getLocInfo() == CCValAssign::Indirect) {
2206 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
2208 // If the original argument was split (e.g. i128), we need
2209 // to load all parts of it here (using the same address).
2210 MVT PartVT;
2211 unsigned NumParts;
2212 if (analyzeArgSplit(Ins, ArgLocs, I, PartVT, NumParts)) {
2213 for (unsigned PartIdx = 1; PartIdx < NumParts; ++PartIdx) {
2214 ++I;
2215 CCValAssign &PartVA = ArgLocs[I];
2216 unsigned PartOffset = Ins[I].PartOffset;
2217 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
2218 DAG.getIntPtrConstant(PartOffset, DL));
2219 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
2221 assert(PartOffset && "Offset should be non-zero.");
2222 }
2223 }
2224 } else if (Subtarget.isTargetXPLINK64() &&
2225 (VA.getLocInfo() == CCValAssign::SExt ||
2226 VA.getLocInfo() == CCValAssign::ZExt) &&
2227 Ins[I].ArgVT.isSimple()) {
2228 // Some prior z/OS compilers do not always perform the extension of
2229 // short integer arguments or pointers. To accommodate those, do not
2230 // rely on that extension by avoiding any AssertSext/AssertZext nodes by
2231 // directly truncating ArgValue to the original argument type.
2232 MVT OrigVT = Ins[I].ArgVT.getSimpleVT();
2233 InVals.push_back(DAG.getNode(ISD::TRUNCATE, DL, OrigVT, ArgValue));
2234 } else
2235 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
2236 }
2237
2238 if (IsVarArg && Subtarget.isTargetXPLINK64()) {
2239 // Save the number of non-varargs registers for later use by va_start, etc.
2240 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
2241 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
2242
2243 auto *Regs = static_cast<SystemZXPLINK64Registers *>(
2244 Subtarget.getSpecialRegisters());
2245
2246 // Likewise the address (in the form of a frame index) of where the
2247 // first stack vararg would be. The 1-byte size here is arbitrary.
2248 // FIXME: Pre-include call frame size in the offset, should not
2249 // need to manually add it here.
2250 int64_t VarArgOffset = CCInfo.getStackSize() + Regs->getCallFrameSize();
2251 int FI = MFI.CreateFixedObject(1, VarArgOffset, true);
2252 FuncInfo->setVarArgsFrameIndex(FI);
2253 }
2254
2255 if (IsVarArg && Subtarget.isTargetELF()) {
2256 // Save the number of non-varargs registers for later use by va_start, etc.
2257 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
2258 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
2259
2260 // Likewise the address (in the form of a frame index) of where the
2261 // first stack vararg would be. The 1-byte size here is arbitrary.
2262 int64_t VarArgsOffset = CCInfo.getStackSize();
2263 FuncInfo->setVarArgsFrameIndex(
2264 MFI.CreateFixedObject(1, VarArgsOffset, true));
2265
2266 // ...and a similar frame index for the caller-allocated save area
2267 // that will be used to store the incoming registers.
2268 int64_t RegSaveOffset =
2269 -SystemZMC::ELFCallFrameSize + TFL->getRegSpillOffset(MF, SystemZ::R2D) - 16;
2270 unsigned RegSaveIndex = MFI.CreateFixedObject(1, RegSaveOffset, true);
2271 FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
2272
2273 // Store the FPR varargs in the reserved frame slots. (We store the
2274 // GPRs as part of the prologue.)
2275 if (NumFixedFPRs < SystemZ::ELFNumArgFPRs && !useSoftFloat()) {
2277 for (unsigned I = NumFixedFPRs; I < SystemZ::ELFNumArgFPRs; ++I) {
2278 unsigned Offset = TFL->getRegSpillOffset(MF, SystemZ::ELFArgFPRs[I]);
2279 int FI =
2281 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2283 &SystemZ::FP64BitRegClass);
2284 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
2285 MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
2287 }
2288 // Join the stores, which are independent of one another.
2289 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2290 ArrayRef(&MemOps[NumFixedFPRs],
2291 SystemZ::ELFNumArgFPRs - NumFixedFPRs));
2292 }
2293 }
2294
2295 if (Subtarget.isTargetXPLINK64()) {
2296 // Create virual register for handling incoming "ADA" special register (R5)
2297 const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
2298 Register ADAvReg = MRI.createVirtualRegister(RC);
2299 auto *Regs = static_cast<SystemZXPLINK64Registers *>(
2300 Subtarget.getSpecialRegisters());
2301 MRI.addLiveIn(Regs->getADARegister(), ADAvReg);
2302 FuncInfo->setADAVirtualRegister(ADAvReg);
2303 }
2304 return Chain;
2305}
2306
2307static bool canUseSiblingCall(const CCState &ArgCCInfo,
2310 // Punt if there are any indirect or stack arguments, or if the call
2311 // needs the callee-saved argument register R6, or if the call uses
2312 // the callee-saved register arguments SwiftSelf and SwiftError.
2313 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
2314 CCValAssign &VA = ArgLocs[I];
2316 return false;
2317 if (!VA.isRegLoc())
2318 return false;
2319 Register Reg = VA.getLocReg();
2320 if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
2321 return false;
2322 if (Outs[I].Flags.isSwiftSelf() || Outs[I].Flags.isSwiftError())
2323 return false;
2324 }
2325 return true;
2326}
2327
2329 unsigned Offset, bool LoadAdr = false) {
2332 Register ADAvReg = MFI->getADAVirtualRegister();
2334
2335 SDValue Reg = DAG.getRegister(ADAvReg, PtrVT);
2336 SDValue Ofs = DAG.getTargetConstant(Offset, DL, PtrVT);
2337
2338 SDValue Result = DAG.getNode(SystemZISD::ADA_ENTRY, DL, PtrVT, Val, Reg, Ofs);
2339 if (!LoadAdr)
2340 Result = DAG.getLoad(
2341 PtrVT, DL, DAG.getEntryNode(), Result, MachinePointerInfo(), Align(8),
2343
2344 return Result;
2345}
2346
2347// ADA access using Global value
2348// Note: for functions, address of descriptor is returned
2350 EVT PtrVT) {
2351 unsigned ADAtype;
2352 bool LoadAddr = false;
2353 const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV);
2354 bool IsFunction =
2355 (isa<Function>(GV)) || (GA && isa<Function>(GA->getAliaseeObject()));
2356 bool IsInternal = (GV->hasInternalLinkage() || GV->hasPrivateLinkage());
2357
2358 if (IsFunction) {
2359 if (IsInternal) {
2361 LoadAddr = true;
2362 } else
2364 } else {
2366 }
2367 SDValue Val = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ADAtype);
2368
2369 return getADAEntry(DAG, Val, DL, 0, LoadAddr);
2370}
2371
2372static bool getzOSCalleeAndADA(SelectionDAG &DAG, SDValue &Callee, SDValue &ADA,
2373 SDLoc &DL, SDValue &Chain) {
2374 unsigned ADADelta = 0; // ADA offset in desc.
2375 unsigned EPADelta = 8; // EPA offset in desc.
2378
2379 // XPLink calling convention.
2380 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2381 bool IsInternal = (G->getGlobal()->hasInternalLinkage() ||
2382 G->getGlobal()->hasPrivateLinkage());
2383 if (IsInternal) {
2386 Register ADAvReg = MFI->getADAVirtualRegister();
2387 ADA = DAG.getCopyFromReg(Chain, DL, ADAvReg, PtrVT);
2388 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
2389 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2390 return true;
2391 } else {
2393 G->getGlobal(), DL, PtrVT, 0, SystemZII::MO_ADA_DIRECT_FUNC_DESC);
2394 ADA = getADAEntry(DAG, GA, DL, ADADelta);
2395 Callee = getADAEntry(DAG, GA, DL, EPADelta);
2396 }
2397 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2399 E->getSymbol(), PtrVT, SystemZII::MO_ADA_DIRECT_FUNC_DESC);
2400 ADA = getADAEntry(DAG, ES, DL, ADADelta);
2401 Callee = getADAEntry(DAG, ES, DL, EPADelta);
2402 } else {
2403 // Function pointer case
2404 ADA = DAG.getNode(ISD::ADD, DL, PtrVT, Callee,
2405 DAG.getConstant(ADADelta, DL, PtrVT));
2406 ADA = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), ADA,
2408 Callee = DAG.getNode(ISD::ADD, DL, PtrVT, Callee,
2409 DAG.getConstant(EPADelta, DL, PtrVT));
2410 Callee = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Callee,
2412 }
2413 return false;
2414}
2415
2416SDValue
2418 SmallVectorImpl<SDValue> &InVals) const {
2419 SelectionDAG &DAG = CLI.DAG;
2420 SDLoc &DL = CLI.DL;
2422 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2424 SDValue Chain = CLI.Chain;
2425 SDValue Callee = CLI.Callee;
2426 bool &IsTailCall = CLI.IsTailCall;
2427 CallingConv::ID CallConv = CLI.CallConv;
2428 bool IsVarArg = CLI.IsVarArg;
2430 EVT PtrVT = getPointerTy(MF.getDataLayout());
2431 LLVMContext &Ctx = *DAG.getContext();
2432 SystemZCallingConventionRegisters *Regs = Subtarget.getSpecialRegisters();
2433
2434 // FIXME: z/OS support to be added in later.
2435 if (Subtarget.isTargetXPLINK64())
2436 IsTailCall = false;
2437
2438 // Integer args <=32 bits should have an extension attribute.
2439 verifyNarrowIntegerArgs_Call(CLI, Outs, &MF.getFunction(), Callee);
2440
2441 // Analyze the operands of the call, assigning locations to each operand.
2443 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, Ctx);
2444 ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
2445
2446 // We don't support GuaranteedTailCallOpt, only automatically-detected
2447 // sibling calls.
2448 if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs, Outs))
2449 IsTailCall = false;
2450
2451 // Get a count of how many bytes are to be pushed on the stack.
2452 unsigned NumBytes = ArgCCInfo.getStackSize();
2453
2454 // Mark the start of the call.
2455 if (!IsTailCall)
2456 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
2457
2458 // Copy argument values to their designated locations.
2460 SmallVector<SDValue, 8> MemOpChains;
2461 SDValue StackPtr;
2462 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
2463 CCValAssign &VA = ArgLocs[I];
2464 SDValue ArgValue = OutVals[I];
2465
2466 if (VA.getLocInfo() == CCValAssign::Indirect) {
2467 // Store the argument in a stack slot and pass its address.
2468 EVT SlotVT;
2469 MVT PartVT;
2470 unsigned NumParts = 1;
2471 if (analyzeArgSplit(Outs, ArgLocs, I, PartVT, NumParts))
2472 SlotVT = EVT::getIntegerVT(Ctx, PartVT.getSizeInBits() * NumParts);
2473 else
2474 SlotVT = Outs[I].VT;
2475 SDValue SpillSlot = DAG.CreateStackTemporary(SlotVT);
2476 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2477
2478 MachinePointerInfo StackPtrInfo =
2480 MemOpChains.push_back(
2481 DAG.getStore(Chain, DL, ArgValue, SpillSlot, StackPtrInfo));
2482 // If the original argument was split (e.g. i128), we need
2483 // to store all parts of it here (and pass just one address).
2484 assert(Outs[I].PartOffset == 0);
2485 for (unsigned PartIdx = 1; PartIdx < NumParts; ++PartIdx) {
2486 ++I;
2487 SDValue PartValue = OutVals[I];
2488 unsigned PartOffset = Outs[I].PartOffset;
2489 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
2490 DAG.getIntPtrConstant(PartOffset, DL));
2491 MemOpChains.push_back(
2492 DAG.getStore(Chain, DL, PartValue, Address,
2493 StackPtrInfo.getWithOffset(PartOffset)));
2494 assert(PartOffset && "Offset should be non-zero.");
2495 assert((PartOffset + PartValue.getValueType().getStoreSize() <=
2496 SlotVT.getStoreSize()) && "Not enough space for argument part!");
2497 }
2498 ArgValue = SpillSlot;
2499 } else
2500 ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
2501
2502 if (VA.isRegLoc()) {
2503 // In XPLINK64, for the 128-bit vararg case, ArgValue is bitcasted to a
2504 // MVT::i128 type. We decompose the 128-bit type to a pair of its high
2505 // and low values.
2506 if (VA.getLocVT() == MVT::i128)
2507 ArgValue = lowerI128ToGR128(DAG, ArgValue);
2508 // Queue up the argument copies and emit them at the end.
2509 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
2510 } else {
2511 assert(VA.isMemLoc() && "Argument not register or memory");
2512
2513 // Work out the address of the stack slot. Unpromoted ints and
2514 // floats are passed as right-justified 8-byte values.
2515 if (!StackPtr.getNode())
2516 StackPtr = DAG.getCopyFromReg(Chain, DL,
2517 Regs->getStackPointerRegister(), PtrVT);
2518 unsigned Offset = Regs->getStackPointerBias() + Regs->getCallFrameSize() +
2519 VA.getLocMemOffset();
2520 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
2521 Offset += 4;
2522 else if (VA.getLocVT() == MVT::f16)
2523 Offset += 6;
2524 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
2526
2527 // Emit the store.
2528 MemOpChains.push_back(
2529 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
2530
2531 // Although long doubles or vectors are passed through the stack when
2532 // they are vararg (non-fixed arguments), if a long double or vector
2533 // occupies the third and fourth slot of the argument list GPR3 should
2534 // still shadow the third slot of the argument list.
2535 if (Subtarget.isTargetXPLINK64() && VA.needsCustom()) {
2536 SDValue ShadowArgValue =
2537 DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, ArgValue,
2538 DAG.getIntPtrConstant(1, DL));
2539 RegsToPass.push_back(std::make_pair(SystemZ::R3D, ShadowArgValue));
2540 }
2541 }
2542 }
2543
2544 // Join the stores, which are independent of one another.
2545 if (!MemOpChains.empty())
2546 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2547
2548 // Accept direct calls by converting symbolic call addresses to the
2549 // associated Target* opcodes. Force %r1 to be used for indirect
2550 // tail calls.
2551 SDValue Glue;
2552
2553 if (Subtarget.isTargetXPLINK64()) {
2554 SDValue ADA;
2555 bool IsBRASL = getzOSCalleeAndADA(DAG, Callee, ADA, DL, Chain);
2556 if (!IsBRASL) {
2557 unsigned CalleeReg = static_cast<SystemZXPLINK64Registers *>(Regs)
2558 ->getAddressOfCalleeRegister();
2559 Chain = DAG.getCopyToReg(Chain, DL, CalleeReg, Callee, Glue);
2560 Glue = Chain.getValue(1);
2561 Callee = DAG.getRegister(CalleeReg, Callee.getValueType());
2562 }
2563 RegsToPass.push_back(std::make_pair(
2564 static_cast<SystemZXPLINK64Registers *>(Regs)->getADARegister(), ADA));
2565 } else {
2566 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2567 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
2568 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2569 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2570 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
2571 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2572 } else if (IsTailCall) {
2573 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
2574 Glue = Chain.getValue(1);
2575 Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
2576 }
2577 }
2578
2579 // Build a sequence of copy-to-reg nodes, chained and glued together.
2580 for (const auto &[Reg, N] : RegsToPass) {
2581 Chain = DAG.getCopyToReg(Chain, DL, Reg, N, Glue);
2582 Glue = Chain.getValue(1);
2583 }
2584
2585 // The first call operand is the chain and the second is the target address.
2587 Ops.push_back(Chain);
2588 Ops.push_back(Callee);
2589
2590 // Add argument registers to the end of the list so that they are
2591 // known live into the call.
2592 for (const auto &[Reg, N] : RegsToPass)
2593 Ops.push_back(DAG.getRegister(Reg, N.getValueType()));
2594
2595 // Add a register mask operand representing the call-preserved registers.
2596 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2597 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2598 assert(Mask && "Missing call preserved mask for calling convention");
2599 Ops.push_back(DAG.getRegisterMask(Mask));
2600
2601 // Glue the call to the argument copies, if any.
2602 if (Glue.getNode())
2603 Ops.push_back(Glue);
2604
2605 // Emit the call.
2606 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2607 if (IsTailCall) {
2608 SDValue Ret = DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
2609 DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge);
2610 return Ret;
2611 }
2612 Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
2613 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2614 Glue = Chain.getValue(1);
2615
2616 // Mark the end of the call, which is glued to the call itself.
2617 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, Glue, DL);
2618 Glue = Chain.getValue(1);
2619
2620 // Assign locations to each value returned by this call.
2622 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, Ctx);
2623 RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
2624
2625 // Copy all of the result registers out of their specified physreg.
2626 for (CCValAssign &VA : RetLocs) {
2627 // Copy the value out, gluing the copy to the end of the call sequence.
2628 SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
2629 VA.getLocVT(), Glue);
2630 Chain = RetValue.getValue(1);
2631 Glue = RetValue.getValue(2);
2632
2633 // Convert the value of the return register into the value that's
2634 // being returned.
2635 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
2636 }
2637
2638 return Chain;
2639}
2640
2641// Generate a call taking the given operands as arguments and returning a
2642// result of type RetVT.
2644 SDValue Chain, SelectionDAG &DAG, const char *CalleeName, EVT RetVT,
2645 ArrayRef<SDValue> Ops, CallingConv::ID CallConv, bool IsSigned, SDLoc DL,
2646 bool DoesNotReturn, bool IsReturnValueUsed) const {
2648 Args.reserve(Ops.size());
2649
2650 for (SDValue Op : Ops) {
2652 Op, Op.getValueType().getTypeForEVT(*DAG.getContext()));
2653 Entry.IsSExt = shouldSignExtendTypeInLibCall(Entry.Ty, IsSigned);
2654 Entry.IsZExt = !Entry.IsSExt;
2655 Args.push_back(Entry);
2656 }
2657
2658 SDValue Callee =
2659 DAG.getExternalSymbol(CalleeName, getPointerTy(DAG.getDataLayout()));
2660
2661 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2663 bool SignExtend = shouldSignExtendTypeInLibCall(RetTy, IsSigned);
2664 CLI.setDebugLoc(DL)
2665 .setChain(Chain)
2666 .setCallee(CallConv, RetTy, Callee, std::move(Args))
2667 .setNoReturn(DoesNotReturn)
2668 .setDiscardResult(!IsReturnValueUsed)
2669 .setSExtResult(SignExtend)
2670 .setZExtResult(!SignExtend);
2671 return LowerCallTo(CLI);
2672}
2673
2675 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
2676 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context,
2677 const Type *RetTy) const {
2678 // Special case that we cannot easily detect in RetCC_SystemZ since
2679 // i128 may not be a legal type.
2680 for (auto &Out : Outs)
2681 if (Out.ArgVT.isScalarInteger() && Out.ArgVT.getSizeInBits() > 64)
2682 return false;
2683
2685 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, Context);
2686 return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ);
2687}
2688
2689SDValue
2691 bool IsVarArg,
2693 const SmallVectorImpl<SDValue> &OutVals,
2694 const SDLoc &DL, SelectionDAG &DAG) const {
2696
2697 // Integer args <=32 bits should have an extension attribute.
2698 verifyNarrowIntegerArgs_Ret(CallConv, Outs, &MF.getFunction());
2699
2700 // Assign locations to each returned value.
2702 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
2703 RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
2704
2705 // Quick exit for void returns
2706 if (RetLocs.empty())
2707 return DAG.getNode(SystemZISD::RET_GLUE, DL, MVT::Other, Chain);
2708
2709 if (CallConv == CallingConv::GHC)
2710 report_fatal_error("GHC functions return void only");
2711
2712 // Copy the result values into the output registers.
2713 SDValue Glue;
2715 RetOps.push_back(Chain);
2716 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
2717 CCValAssign &VA = RetLocs[I];
2718 SDValue RetValue = OutVals[I];
2719
2720 // Make the return register live on exit.
2721 assert(VA.isRegLoc() && "Can only return in registers!");
2722
2723 // Promote the value as required.
2724 RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
2725
2726 // Chain and glue the copies together.
2727 Register Reg = VA.getLocReg();
2728 Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
2729 Glue = Chain.getValue(1);
2730 RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
2731 }
2732
2733 // Update chain and glue.
2734 RetOps[0] = Chain;
2735 if (Glue.getNode())
2736 RetOps.push_back(Glue);
2737
2738 return DAG.getNode(SystemZISD::RET_GLUE, DL, MVT::Other, RetOps);
2739}
2740
2741// Return true if Op is an intrinsic node with chain that returns the CC value
2742// as its only (other) argument. Provide the associated SystemZISD opcode and
2743// the mask of valid CC values if so.
2744static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
2745 unsigned &CCValid) {
2746 unsigned Id = Op.getConstantOperandVal(1);
2747 switch (Id) {
2748 case Intrinsic::s390_tbegin:
2749 Opcode = SystemZISD::TBEGIN;
2750 CCValid = SystemZ::CCMASK_TBEGIN;
2751 return true;
2752
2753 case Intrinsic::s390_tbegin_nofloat:
2754 Opcode = SystemZISD::TBEGIN_NOFLOAT;
2755 CCValid = SystemZ::CCMASK_TBEGIN;
2756 return true;
2757
2758 case Intrinsic::s390_tend:
2759 Opcode = SystemZISD::TEND;
2760 CCValid = SystemZ::CCMASK_TEND;
2761 return true;
2762
2763 default:
2764 return false;
2765 }
2766}
2767
2768// Return true if Op is an intrinsic node without chain that returns the
2769// CC value as its final argument. Provide the associated SystemZISD
2770// opcode and the mask of valid CC values if so.
2771static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) {
2772 unsigned Id = Op.getConstantOperandVal(0);
2773 switch (Id) {
2774 case Intrinsic::s390_vpkshs:
2775 case Intrinsic::s390_vpksfs:
2776 case Intrinsic::s390_vpksgs:
2777 Opcode = SystemZISD::PACKS_CC;
2778 CCValid = SystemZ::CCMASK_VCMP;
2779 return true;
2780
2781 case Intrinsic::s390_vpklshs:
2782 case Intrinsic::s390_vpklsfs:
2783 case Intrinsic::s390_vpklsgs:
2784 Opcode = SystemZISD::PACKLS_CC;
2785 CCValid = SystemZ::CCMASK_VCMP;
2786 return true;
2787
2788 case Intrinsic::s390_vceqbs:
2789 case Intrinsic::s390_vceqhs:
2790 case Intrinsic::s390_vceqfs:
2791 case Intrinsic::s390_vceqgs:
2792 case Intrinsic::s390_vceqqs:
2793 Opcode = SystemZISD::VICMPES;
2794 CCValid = SystemZ::CCMASK_VCMP;
2795 return true;
2796
2797 case Intrinsic::s390_vchbs:
2798 case Intrinsic::s390_vchhs:
2799 case Intrinsic::s390_vchfs:
2800 case Intrinsic::s390_vchgs:
2801 case Intrinsic::s390_vchqs:
2802 Opcode = SystemZISD::VICMPHS;
2803 CCValid = SystemZ::CCMASK_VCMP;
2804 return true;
2805
2806 case Intrinsic::s390_vchlbs:
2807 case Intrinsic::s390_vchlhs:
2808 case Intrinsic::s390_vchlfs:
2809 case Intrinsic::s390_vchlgs:
2810 case Intrinsic::s390_vchlqs:
2811 Opcode = SystemZISD::VICMPHLS;
2812 CCValid = SystemZ::CCMASK_VCMP;
2813 return true;
2814
2815 case Intrinsic::s390_vtm:
2816 Opcode = SystemZISD::VTM;
2817 CCValid = SystemZ::CCMASK_VCMP;
2818 return true;
2819
2820 case Intrinsic::s390_vfaebs:
2821 case Intrinsic::s390_vfaehs:
2822 case Intrinsic::s390_vfaefs:
2823 Opcode = SystemZISD::VFAE_CC;
2824 CCValid = SystemZ::CCMASK_ANY;
2825 return true;
2826
2827 case Intrinsic::s390_vfaezbs:
2828 case Intrinsic::s390_vfaezhs:
2829 case Intrinsic::s390_vfaezfs:
2830 Opcode = SystemZISD::VFAEZ_CC;
2831 CCValid = SystemZ::CCMASK_ANY;
2832 return true;
2833
2834 case Intrinsic::s390_vfeebs:
2835 case Intrinsic::s390_vfeehs:
2836 case Intrinsic::s390_vfeefs:
2837 Opcode = SystemZISD::VFEE_CC;
2838 CCValid = SystemZ::CCMASK_ANY;
2839 return true;
2840
2841 case Intrinsic::s390_vfeezbs:
2842 case Intrinsic::s390_vfeezhs:
2843 case Intrinsic::s390_vfeezfs:
2844 Opcode = SystemZISD::VFEEZ_CC;
2845 CCValid = SystemZ::CCMASK_ANY;
2846 return true;
2847
2848 case Intrinsic::s390_vfenebs:
2849 case Intrinsic::s390_vfenehs:
2850 case Intrinsic::s390_vfenefs:
2851 Opcode = SystemZISD::VFENE_CC;
2852 CCValid = SystemZ::CCMASK_ANY;
2853 return true;
2854
2855 case Intrinsic::s390_vfenezbs:
2856 case Intrinsic::s390_vfenezhs:
2857 case Intrinsic::s390_vfenezfs:
2858 Opcode = SystemZISD::VFENEZ_CC;
2859 CCValid = SystemZ::CCMASK_ANY;
2860 return true;
2861
2862 case Intrinsic::s390_vistrbs:
2863 case Intrinsic::s390_vistrhs:
2864 case Intrinsic::s390_vistrfs:
2865 Opcode = SystemZISD::VISTR_CC;
2867 return true;
2868
2869 case Intrinsic::s390_vstrcbs:
2870 case Intrinsic::s390_vstrchs:
2871 case Intrinsic::s390_vstrcfs:
2872 Opcode = SystemZISD::VSTRC_CC;
2873 CCValid = SystemZ::CCMASK_ANY;
2874 return true;
2875
2876 case Intrinsic::s390_vstrczbs:
2877 case Intrinsic::s390_vstrczhs:
2878 case Intrinsic::s390_vstrczfs:
2879 Opcode = SystemZISD::VSTRCZ_CC;
2880 CCValid = SystemZ::CCMASK_ANY;
2881 return true;
2882
2883 case Intrinsic::s390_vstrsb:
2884 case Intrinsic::s390_vstrsh:
2885 case Intrinsic::s390_vstrsf:
2886 Opcode = SystemZISD::VSTRS_CC;
2887 CCValid = SystemZ::CCMASK_ANY;
2888 return true;
2889
2890 case Intrinsic::s390_vstrszb:
2891 case Intrinsic::s390_vstrszh:
2892 case Intrinsic::s390_vstrszf:
2893 Opcode = SystemZISD::VSTRSZ_CC;
2894 CCValid = SystemZ::CCMASK_ANY;
2895 return true;
2896
2897 case Intrinsic::s390_vfcedbs:
2898 case Intrinsic::s390_vfcesbs:
2899 Opcode = SystemZISD::VFCMPES;
2900 CCValid = SystemZ::CCMASK_VCMP;
2901 return true;
2902
2903 case Intrinsic::s390_vfchdbs:
2904 case Intrinsic::s390_vfchsbs:
2905 Opcode = SystemZISD::VFCMPHS;
2906 CCValid = SystemZ::CCMASK_VCMP;
2907 return true;
2908
2909 case Intrinsic::s390_vfchedbs:
2910 case Intrinsic::s390_vfchesbs:
2911 Opcode = SystemZISD::VFCMPHES;
2912 CCValid = SystemZ::CCMASK_VCMP;
2913 return true;
2914
2915 case Intrinsic::s390_vftcidb:
2916 case Intrinsic::s390_vftcisb:
2917 Opcode = SystemZISD::VFTCI;
2918 CCValid = SystemZ::CCMASK_VCMP;
2919 return true;
2920
2921 case Intrinsic::s390_tdc:
2922 Opcode = SystemZISD::TDC;
2923 CCValid = SystemZ::CCMASK_TDC;
2924 return true;
2925
2926 default:
2927 return false;
2928 }
2929}
2930
2931// Emit an intrinsic with chain and an explicit CC register result.
2933 unsigned Opcode) {
2934 // Copy all operands except the intrinsic ID.
2935 unsigned NumOps = Op.getNumOperands();
2937 Ops.reserve(NumOps - 1);
2938 Ops.push_back(Op.getOperand(0));
2939 for (unsigned I = 2; I < NumOps; ++I)
2940 Ops.push_back(Op.getOperand(I));
2941
2942 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
2943 SDVTList RawVTs = DAG.getVTList(MVT::i32, MVT::Other);
2944 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
2945 SDValue OldChain = SDValue(Op.getNode(), 1);
2946 SDValue NewChain = SDValue(Intr.getNode(), 1);
2947 DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
2948 return Intr.getNode();
2949}
2950
2951// Emit an intrinsic with an explicit CC register result.
2953 unsigned Opcode) {
2954 // Copy all operands except the intrinsic ID.
2955 SDLoc DL(Op);
2956 unsigned NumOps = Op.getNumOperands();
2958 Ops.reserve(NumOps - 1);
2959 for (unsigned I = 1; I < NumOps; ++I) {
2960 SDValue CurrOper = Op.getOperand(I);
2961 if (CurrOper.getValueType() == MVT::f16) {
2962 assert((Op.getConstantOperandVal(0) == Intrinsic::s390_tdc && I == 1) &&
2963 "Unhandled intrinsic with f16 operand.");
2964 CurrOper = DAG.getFPExtendOrRound(CurrOper, DL, MVT::f32);
2965 }
2966 Ops.push_back(CurrOper);
2967 }
2968
2969 SDValue Intr = DAG.getNode(Opcode, DL, Op->getVTList(), Ops);
2970 return Intr.getNode();
2971}
2972
2973// CC is a comparison that will be implemented using an integer or
2974// floating-point comparison. Return the condition code mask for
2975// a branch on true. In the integer case, CCMASK_CMP_UO is set for
2976// unsigned comparisons and clear for signed ones. In the floating-point
2977// case, CCMASK_CMP_UO has its normal mask meaning (unordered).
2979#define CONV(X) \
2980 case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
2981 case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
2982 case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
2983
2984 switch (CC) {
2985 default:
2986 llvm_unreachable("Invalid integer condition!");
2987
2988 CONV(EQ);
2989 CONV(NE);
2990 CONV(GT);
2991 CONV(GE);
2992 CONV(LT);
2993 CONV(LE);
2994
2995 case ISD::SETO: return SystemZ::CCMASK_CMP_O;
2997 }
2998#undef CONV
2999}
3000
3001// If C can be converted to a comparison against zero, adjust the operands
3002// as necessary.
3003static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
3004 if (C.ICmpType == SystemZICMP::UnsignedOnly)
3005 return;
3006
3007 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
3008 if (!ConstOp1 || ConstOp1->getValueSizeInBits(0) > 64)
3009 return;
3010
3011 int64_t Value = ConstOp1->getSExtValue();
3012 if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
3013 (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
3014 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
3015 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
3016 C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
3017 C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
3018 }
3019}
3020
3021// If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
3022// adjust the operands as necessary.
3023static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL,
3024 Comparison &C) {
3025 // For us to make any changes, it must a comparison between a single-use
3026 // load and a constant.
3027 if (!C.Op0.hasOneUse() ||
3028 C.Op0.getOpcode() != ISD::LOAD ||
3029 C.Op1.getOpcode() != ISD::Constant)
3030 return;
3031
3032 // We must have an 8- or 16-bit load.
3033 auto *Load = cast<LoadSDNode>(C.Op0);
3034 unsigned NumBits = Load->getMemoryVT().getSizeInBits();
3035 if ((NumBits != 8 && NumBits != 16) ||
3036 NumBits != Load->getMemoryVT().getStoreSizeInBits())
3037 return;
3038
3039 // The load must be an extending one and the constant must be within the
3040 // range of the unextended value.
3041 auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
3042 if (!ConstOp1 || ConstOp1->getValueSizeInBits(0) > 64)
3043 return;
3044 uint64_t Value = ConstOp1->getZExtValue();
3045 uint64_t Mask = (1 << NumBits) - 1;
3046 if (Load->getExtensionType() == ISD::SEXTLOAD) {
3047 // Make sure that ConstOp1 is in range of C.Op0.
3048 int64_t SignedValue = ConstOp1->getSExtValue();
3049 if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
3050 return;
3051 if (C.ICmpType != SystemZICMP::SignedOnly) {
3052 // Unsigned comparison between two sign-extended values is equivalent
3053 // to unsigned comparison between two zero-extended values.
3054 Value &= Mask;
3055 } else if (NumBits == 8) {
3056 // Try to treat the comparison as unsigned, so that we can use CLI.
3057 // Adjust CCMask and Value as necessary.
3058 if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
3059 // Test whether the high bit of the byte is set.
3060 Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
3061 else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
3062 // Test whether the high bit of the byte is clear.
3063 Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
3064 else
3065 // No instruction exists for this combination.
3066 return;
3067 C.ICmpType = SystemZICMP::UnsignedOnly;
3068 }
3069 } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
3070 if (Value > Mask)
3071 return;
3072 // If the constant is in range, we can use any comparison.
3073 C.ICmpType = SystemZICMP::Any;
3074 } else
3075 return;
3076
3077 // Make sure that the first operand is an i32 of the right extension type.
3078 ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
3081 if (C.Op0.getValueType() != MVT::i32 ||
3082 Load->getExtensionType() != ExtType) {
3083 C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32, Load->getChain(),
3084 Load->getBasePtr(), Load->getPointerInfo(),
3085 Load->getMemoryVT(), Load->getAlign(),
3086 Load->getMemOperand()->getFlags());
3087 // Update the chain uses.
3088 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), C.Op0.getValue(1));
3089 }
3090
3091 // Make sure that the second operand is an i32 with the right value.
3092 if (C.Op1.getValueType() != MVT::i32 ||
3093 Value != ConstOp1->getZExtValue())
3094 C.Op1 = DAG.getConstant((uint32_t)Value, DL, MVT::i32);
3095}
3096
3097// Return true if Op is either an unextended load, or a load suitable
3098// for integer register-memory comparisons of type ICmpType.
3099static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
3100 auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
3101 if (Load) {
3102 // There are no instructions to compare a register with a memory byte.
3103 if (Load->getMemoryVT() == MVT::i8)
3104 return false;
3105 // Otherwise decide on extension type.
3106 switch (Load->getExtensionType()) {
3107 case ISD::NON_EXTLOAD:
3108 return true;
3109 case ISD::SEXTLOAD:
3110 return ICmpType != SystemZICMP::UnsignedOnly;
3111 case ISD::ZEXTLOAD:
3112 return ICmpType != SystemZICMP::SignedOnly;
3113 default:
3114 break;
3115 }
3116 }
3117 return false;
3118}
3119
3120// Return true if it is better to swap the operands of C.
3121static bool shouldSwapCmpOperands(const Comparison &C) {
3122 // If one side of the compare is a load of the stackguard reference value,
3123 // then that load should be Op1.
3124 if (C.Op0.isMachineOpcode() &&
3125 (C.Op0.getMachineOpcode() == SystemZ::LOAD_STACK_GUARD))
3126 return true;
3127
3128 // Leave i128 and f128 comparisons alone, since they have no memory forms.
3129 if (C.Op0.getValueType() == MVT::i128)
3130 return false;
3131 if (C.Op0.getValueType() == MVT::f128)
3132 return false;
3133
3134 // Always keep a floating-point constant second, since comparisons with
3135 // zero can use LOAD TEST and comparisons with other constants make a
3136 // natural memory operand.
3137 if (isa<ConstantFPSDNode>(C.Op1))
3138 return false;
3139
3140 // Never swap comparisons with zero since there are many ways to optimize
3141 // those later.
3142 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
3143 if (ConstOp1 && ConstOp1->getZExtValue() == 0)
3144 return false;
3145
3146 // Also keep natural memory operands second if the loaded value is
3147 // only used here. Several comparisons have memory forms.
3148 if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
3149 return false;
3150
3151 // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
3152 // In that case we generally prefer the memory to be second.
3153 if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
3154 // The only exceptions are when the second operand is a constant and
3155 // we can use things like CHHSI.
3156 if (!ConstOp1)
3157 return true;
3158 // The unsigned memory-immediate instructions can handle 16-bit
3159 // unsigned integers.
3160 if (C.ICmpType != SystemZICMP::SignedOnly &&
3161 isUInt<16>(ConstOp1->getZExtValue()))
3162 return false;
3163 // The signed memory-immediate instructions can handle 16-bit
3164 // signed integers.
3165 if (C.ICmpType != SystemZICMP::UnsignedOnly &&
3166 isInt<16>(ConstOp1->getSExtValue()))
3167 return false;
3168 return true;
3169 }
3170
3171 // Try to promote the use of CGFR and CLGFR.
3172 unsigned Opcode0 = C.Op0.getOpcode();
3173 if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
3174 return true;
3175 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
3176 return true;
3177 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::AND &&
3178 C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
3179 C.Op0.getConstantOperandVal(1) == 0xffffffff)
3180 return true;
3181
3182 return false;
3183}
3184
3185// Check whether C tests for equality between X and Y and whether X - Y
3186// or Y - X is also computed. In that case it's better to compare the
3187// result of the subtraction against zero.
3189 Comparison &C) {
3190 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3191 C.CCMask == SystemZ::CCMASK_CMP_NE) {
3192 for (SDNode *N : C.Op0->users()) {
3193 if (N->getOpcode() == ISD::SUB &&
3194 ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
3195 (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
3196 // Disable the nsw and nuw flags: the backend needs to handle
3197 // overflow as well during comparison elimination.
3198 N->dropFlags(SDNodeFlags::NoWrap);
3199 C.Op0 = SDValue(N, 0);
3200 C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
3201 return;
3202 }
3203 }
3204 }
3205}
3206
3207// Check whether C compares a floating-point value with zero and if that
3208// floating-point value is also negated. In this case we can use the
3209// negation to set CC, so avoiding separate LOAD AND TEST and
3210// LOAD (NEGATIVE/COMPLEMENT) instructions.
3211static void adjustForFNeg(Comparison &C) {
3212 // This optimization is invalid for strict comparisons, since FNEG
3213 // does not raise any exceptions.
3214 if (C.Chain)
3215 return;
3216 auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
3217 if (C1 && C1->isZero()) {
3218 for (SDNode *N : C.Op0->users()) {
3219 if (N->getOpcode() == ISD::FNEG) {
3220 C.Op0 = SDValue(N, 0);
3221 C.CCMask = SystemZ::reverseCCMask(C.CCMask);
3222 return;
3223 }
3224 }
3225 }
3226}
3227
3228// Check whether C compares (shl X, 32) with 0 and whether X is
3229// also sign-extended. In that case it is better to test the result
3230// of the sign extension using LTGFR.
3231//
3232// This case is important because InstCombine transforms a comparison
3233// with (sext (trunc X)) into a comparison with (shl X, 32).
3234static void adjustForLTGFR(Comparison &C) {
3235 // Check for a comparison between (shl X, 32) and 0.
3236 if (C.Op0.getOpcode() == ISD::SHL && C.Op0.getValueType() == MVT::i64 &&
3237 C.Op1.getOpcode() == ISD::Constant && C.Op1->getAsZExtVal() == 0) {
3238 auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
3239 if (C1 && C1->getZExtValue() == 32) {
3240 SDValue ShlOp0 = C.Op0.getOperand(0);
3241 // See whether X has any SIGN_EXTEND_INREG uses.
3242 for (SDNode *N : ShlOp0->users()) {
3243 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
3244 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
3245 C.Op0 = SDValue(N, 0);
3246 return;
3247 }
3248 }
3249 }
3250 }
3251}
3252
3253// If C compares the truncation of an extending load, try to compare
3254// the untruncated value instead. This exposes more opportunities to
3255// reuse CC.
3256static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL,
3257 Comparison &C) {
3258 if (C.Op0.getOpcode() == ISD::TRUNCATE &&
3259 C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
3260 C.Op1.getOpcode() == ISD::Constant &&
3261 cast<ConstantSDNode>(C.Op1)->getValueSizeInBits(0) <= 64 &&
3262 C.Op1->getAsZExtVal() == 0) {
3263 auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
3264 if (L->getMemoryVT().getStoreSizeInBits().getFixedValue() <=
3265 C.Op0.getValueSizeInBits().getFixedValue()) {
3266 unsigned Type = L->getExtensionType();
3267 if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
3268 (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
3269 C.Op0 = C.Op0.getOperand(0);
3270 C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
3271 }
3272 }
3273 }
3274}
3275
3276// Adjust if a given Compare is a check of the stack guard against a stack
3277// guard instance on the stack. Specifically, this checks if:
3278// - The operands are a load of the stack guard, and a load from a stack slot
3279// - The original opcode is ICMP
3280// - ICMPType is compatible with unsigned comparison.
3282 Comparison &C) {
3283
3284 // Opcode must be ICMP.
3285 if (C.Opcode != SystemZISD::ICMP)
3286 return;
3287 // ICmpType must be Unsigned or Any.
3288 if (C.ICmpType == SystemZICMP::SignedOnly)
3289 return;
3290 // Op0 must be FrameIndex Load.
3291 if (!(ISD::isNormalLoad(C.Op0.getNode()) &&
3292 dyn_cast<FrameIndexSDNode>(C.Op0.getOperand(1))))
3293 return;
3294 // Op1 must be LOAD_STACK_GUARD.
3295 if (!C.Op1.isMachineOpcode() ||
3296 C.Op1.getMachineOpcode() != SystemZ::LOAD_STACK_GUARD)
3297 return;
3298
3299 // At this point we are sure that this is a proper CMP_STACKGUARD
3300 // case, update the opcode to reflect this.
3301 C.Opcode = SystemZISD::CMP_STACKGUARD;
3302 C.Op1 = SDValue();
3303}
3304
3305// Return true if shift operation N has an in-range constant shift value.
3306// Store it in ShiftVal if so.
3307static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
3308 auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
3309 if (!Shift)
3310 return false;
3311
3312 uint64_t Amount = Shift->getZExtValue();
3313 if (Amount >= N.getValueSizeInBits())
3314 return false;
3315
3316 ShiftVal = Amount;
3317 return true;
3318}
3319
3320// Check whether an AND with Mask is suitable for a TEST UNDER MASK
3321// instruction and whether the CC value is descriptive enough to handle
3322// a comparison of type Opcode between the AND result and CmpVal.
3323// CCMask says which comparison result is being tested and BitSize is
3324// the number of bits in the operands. If TEST UNDER MASK can be used,
3325// return the corresponding CC mask, otherwise return 0.
3326static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
3327 uint64_t Mask, uint64_t CmpVal,
3328 unsigned ICmpType) {
3329 assert(Mask != 0 && "ANDs with zero should have been removed by now");
3330
3331 // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
3332 if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
3333 !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
3334 return 0;
3335
3336 // Work out the masks for the lowest and highest bits.
3338 uint64_t Low = uint64_t(1) << llvm::countr_zero(Mask);
3339
3340 // Signed ordered comparisons are effectively unsigned if the sign
3341 // bit is dropped.
3342 bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
3343
3344 // Check for equality comparisons with 0, or the equivalent.
3345 if (CmpVal == 0) {
3346 if (CCMask == SystemZ::CCMASK_CMP_EQ)
3348 if (CCMask == SystemZ::CCMASK_CMP_NE)
3350 }
3351 if (EffectivelyUnsigned && CmpVal > 0 && CmpVal <= Low) {
3352 if (CCMask == SystemZ::CCMASK_CMP_LT)
3354 if (CCMask == SystemZ::CCMASK_CMP_GE)
3356 }
3357 if (EffectivelyUnsigned && CmpVal < Low) {
3358 if (CCMask == SystemZ::CCMASK_CMP_LE)
3360 if (CCMask == SystemZ::CCMASK_CMP_GT)
3362 }
3363
3364 // Check for equality comparisons with the mask, or the equivalent.
3365 if (CmpVal == Mask) {
3366 if (CCMask == SystemZ::CCMASK_CMP_EQ)
3368 if (CCMask == SystemZ::CCMASK_CMP_NE)
3370 }
3371 if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
3372 if (CCMask == SystemZ::CCMASK_CMP_GT)
3374 if (CCMask == SystemZ::CCMASK_CMP_LE)
3376 }
3377 if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
3378 if (CCMask == SystemZ::CCMASK_CMP_GE)
3380 if (CCMask == SystemZ::CCMASK_CMP_LT)
3382 }
3383
3384 // Check for ordered comparisons with the top bit.
3385 if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
3386 if (CCMask == SystemZ::CCMASK_CMP_LE)
3388 if (CCMask == SystemZ::CCMASK_CMP_GT)
3390 }
3391 if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
3392 if (CCMask == SystemZ::CCMASK_CMP_LT)
3394 if (CCMask == SystemZ::CCMASK_CMP_GE)
3396 }
3397
3398 // If there are just two bits, we can do equality checks for Low and High
3399 // as well.
3400 if (Mask == Low + High) {
3401 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
3403 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
3405 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
3407 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
3409 }
3410
3411 // Looks like we've exhausted our options.
3412 return 0;
3413}
3414
3415// See whether C can be implemented as a TEST UNDER MASK instruction.
3416// Update the arguments with the TM version if so.
3418 Comparison &C) {
3419 // Use VECTOR TEST UNDER MASK for i128 operations.
3420 if (C.Op0.getValueType() == MVT::i128) {
3421 // We can use VTM for EQ/NE comparisons of x & y against 0.
3422 if (C.Op0.getOpcode() == ISD::AND &&
3423 (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3424 C.CCMask == SystemZ::CCMASK_CMP_NE)) {
3425 auto *Mask = dyn_cast<ConstantSDNode>(C.Op1);
3426 if (Mask && Mask->getAPIntValue() == 0) {
3427 C.Opcode = SystemZISD::VTM;
3428 C.Op1 = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, C.Op0.getOperand(1));
3429 C.Op0 = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, C.Op0.getOperand(0));
3430 C.CCValid = SystemZ::CCMASK_VCMP;
3431 if (C.CCMask == SystemZ::CCMASK_CMP_EQ)
3432 C.CCMask = SystemZ::CCMASK_VCMP_ALL;
3433 else
3434 C.CCMask = SystemZ::CCMASK_VCMP_ALL ^ C.CCValid;
3435 }
3436 }
3437 return;
3438 }
3439
3440 // Check that we have a comparison with a constant.
3441 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
3442 if (!ConstOp1)
3443 return;
3444 uint64_t CmpVal = ConstOp1->getZExtValue();
3445
3446 // Check whether the nonconstant input is an AND with a constant mask.
3447 Comparison NewC(C);
3448 uint64_t MaskVal;
3449 ConstantSDNode *Mask = nullptr;
3450 if (C.Op0.getOpcode() == ISD::AND) {
3451 NewC.Op0 = C.Op0.getOperand(0);
3452 NewC.Op1 = C.Op0.getOperand(1);
3453 Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
3454 if (!Mask)
3455 return;
3456 MaskVal = Mask->getZExtValue();
3457 } else {
3458 // There is no instruction to compare with a 64-bit immediate
3459 // so use TMHH instead if possible. We need an unsigned ordered
3460 // comparison with an i64 immediate.
3461 if (NewC.Op0.getValueType() != MVT::i64 ||
3462 NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
3463 NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
3464 NewC.ICmpType == SystemZICMP::SignedOnly)
3465 return;
3466 // Convert LE and GT comparisons into LT and GE.
3467 if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
3468 NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
3469 if (CmpVal == uint64_t(-1))
3470 return;
3471 CmpVal += 1;
3472 NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
3473 }
3474 // If the low N bits of Op1 are zero than the low N bits of Op0 can
3475 // be masked off without changing the result.
3476 MaskVal = -(CmpVal & -CmpVal);
3477 NewC.ICmpType = SystemZICMP::UnsignedOnly;
3478 }
3479 if (!MaskVal)
3480 return;
3481
3482 // Check whether the combination of mask, comparison value and comparison
3483 // type are suitable.
3484 unsigned BitSize = NewC.Op0.getValueSizeInBits();
3485 unsigned NewCCMask, ShiftVal;
3486 if (NewC.ICmpType != SystemZICMP::SignedOnly &&
3487 NewC.Op0.getOpcode() == ISD::SHL &&
3488 isSimpleShift(NewC.Op0, ShiftVal) &&
3489 (MaskVal >> ShiftVal != 0) &&
3490 ((CmpVal >> ShiftVal) << ShiftVal) == CmpVal &&
3491 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
3492 MaskVal >> ShiftVal,
3493 CmpVal >> ShiftVal,
3494 SystemZICMP::Any))) {
3495 NewC.Op0 = NewC.Op0.getOperand(0);
3496 MaskVal >>= ShiftVal;
3497 } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
3498 NewC.Op0.getOpcode() == ISD::SRL &&
3499 isSimpleShift(NewC.Op0, ShiftVal) &&
3500 (MaskVal << ShiftVal != 0) &&
3501 ((CmpVal << ShiftVal) >> ShiftVal) == CmpVal &&
3502 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
3503 MaskVal << ShiftVal,
3504 CmpVal << ShiftVal,
3506 NewC.Op0 = NewC.Op0.getOperand(0);
3507 MaskVal <<= ShiftVal;
3508 } else {
3509 NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
3510 NewC.ICmpType);
3511 if (!NewCCMask)
3512 return;
3513 }
3514
3515 // Go ahead and make the change.
3516 C.Opcode = SystemZISD::TM;
3517 C.Op0 = NewC.Op0;
3518 if (Mask && Mask->getZExtValue() == MaskVal)
3519 C.Op1 = SDValue(Mask, 0);
3520 else
3521 C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
3522 C.CCValid = SystemZ::CCMASK_TM;
3523 C.CCMask = NewCCMask;
3524}
3525
3526// Implement i128 comparison in vector registers.
3527static void adjustICmp128(SelectionDAG &DAG, const SDLoc &DL,
3528 Comparison &C) {
3529 if (C.Opcode != SystemZISD::ICMP)
3530 return;
3531 if (C.Op0.getValueType() != MVT::i128)
3532 return;
3533
3534 // Recognize vector comparison reductions.
3535 if ((C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3536 C.CCMask == SystemZ::CCMASK_CMP_NE) &&
3537 (isNullConstant(C.Op1) || isAllOnesConstant(C.Op1))) {
3538 bool CmpEq = C.CCMask == SystemZ::CCMASK_CMP_EQ;
3539 bool CmpNull = isNullConstant(C.Op1);
3540 SDValue Src = peekThroughBitcasts(C.Op0);
3541 if (Src.hasOneUse() && isBitwiseNot(Src)) {
3542 Src = Src.getOperand(0);
3543 CmpNull = !CmpNull;
3544 }
3545 unsigned Opcode = 0;
3546 if (Src.hasOneUse()) {
3547 switch (Src.getOpcode()) {
3548 case SystemZISD::VICMPE: Opcode = SystemZISD::VICMPES; break;
3549 case SystemZISD::VICMPH: Opcode = SystemZISD::VICMPHS; break;
3550 case SystemZISD::VICMPHL: Opcode = SystemZISD::VICMPHLS; break;
3551 case SystemZISD::VFCMPE: Opcode = SystemZISD::VFCMPES; break;
3552 case SystemZISD::VFCMPH: Opcode = SystemZISD::VFCMPHS; break;
3553 case SystemZISD::VFCMPHE: Opcode = SystemZISD::VFCMPHES; break;
3554 default: break;
3555 }
3556 }
3557 if (Opcode) {
3558 C.Opcode = Opcode;
3559 C.Op0 = Src->getOperand(0);
3560 C.Op1 = Src->getOperand(1);
3561 C.CCValid = SystemZ::CCMASK_VCMP;
3563 if (!CmpEq)
3564 C.CCMask ^= C.CCValid;
3565 return;
3566 }
3567 }
3568
3569 // Everything below here is not useful if we have native i128 compares.
3570 if (DAG.getSubtarget<SystemZSubtarget>().hasVectorEnhancements3())
3571 return;
3572
3573 // (In-)Equality comparisons can be implemented via VCEQGS.
3574 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3575 C.CCMask == SystemZ::CCMASK_CMP_NE) {
3576 C.Opcode = SystemZISD::VICMPES;
3577 C.Op0 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, C.Op0);
3578 C.Op1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, C.Op1);
3579 C.CCValid = SystemZ::CCMASK_VCMP;
3580 if (C.CCMask == SystemZ::CCMASK_CMP_EQ)
3581 C.CCMask = SystemZ::CCMASK_VCMP_ALL;
3582 else
3583 C.CCMask = SystemZ::CCMASK_VCMP_ALL ^ C.CCValid;
3584 return;
3585 }
3586
3587 // Normalize other comparisons to GT.
3588 bool Swap = false, Invert = false;
3589 switch (C.CCMask) {
3590 case SystemZ::CCMASK_CMP_GT: break;
3591 case SystemZ::CCMASK_CMP_LT: Swap = true; break;
3592 case SystemZ::CCMASK_CMP_LE: Invert = true; break;
3593 case SystemZ::CCMASK_CMP_GE: Swap = Invert = true; break;
3594 default: llvm_unreachable("Invalid integer condition!");
3595 }
3596 if (Swap)
3597 std::swap(C.Op0, C.Op1);
3598
3599 if (C.ICmpType == SystemZICMP::UnsignedOnly)
3600 C.Opcode = SystemZISD::UCMP128HI;
3601 else
3602 C.Opcode = SystemZISD::SCMP128HI;
3603 C.CCValid = SystemZ::CCMASK_ANY;
3604 C.CCMask = SystemZ::CCMASK_1;
3605
3606 if (Invert)
3607 C.CCMask ^= C.CCValid;
3608}
3609
3610// See whether the comparison argument contains a redundant AND
3611// and remove it if so. This sometimes happens due to the generic
3612// BRCOND expansion.
3614 Comparison &C) {
3615 if (C.Op0.getOpcode() != ISD::AND)
3616 return;
3617 auto *Mask = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
3618 if (!Mask || Mask->getValueSizeInBits(0) > 64)
3619 return;
3620 KnownBits Known = DAG.computeKnownBits(C.Op0.getOperand(0));
3621 if ((~Known.Zero).getZExtValue() & ~Mask->getZExtValue())
3622 return;
3623
3624 C.Op0 = C.Op0.getOperand(0);
3625}
3626
3627// Return a Comparison that tests the condition-code result of intrinsic
3628// node Call against constant integer CC using comparison code Cond.
3629// Opcode is the opcode of the SystemZISD operation for the intrinsic
3630// and CCValid is the set of possible condition-code results.
3631static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
3632 SDValue Call, unsigned CCValid, uint64_t CC,
3634 Comparison C(Call, SDValue(), SDValue());
3635 C.Opcode = Opcode;
3636 C.CCValid = CCValid;
3637 if (Cond == ISD::SETEQ)
3638 // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
3639 C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
3640 else if (Cond == ISD::SETNE)
3641 // ...and the inverse of that.
3642 C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
3643 else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
3644 // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
3645 // always true for CC>3.
3646 C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1;
3647 else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
3648 // ...and the inverse of that.
3649 C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0;
3650 else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
3651 // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
3652 // always true for CC>3.
3653 C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1;
3654 else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
3655 // ...and the inverse of that.
3656 C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0;
3657 else
3658 llvm_unreachable("Unexpected integer comparison type");
3659 C.CCMask &= CCValid;
3660 return C;
3661}
3662
3663// Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
3664static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
3665 ISD::CondCode Cond, const SDLoc &DL,
3666 SDValue Chain = SDValue(),
3667 bool IsSignaling = false) {
3668 if (CmpOp1.getOpcode() == ISD::Constant) {
3669 assert(!Chain);
3670 unsigned Opcode, CCValid;
3671 if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
3672 CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
3673 isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
3674 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid,
3675 CmpOp1->getAsZExtVal(), Cond);
3676 if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
3677 CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 &&
3678 isIntrinsicWithCC(CmpOp0, Opcode, CCValid))
3679 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid,
3680 CmpOp1->getAsZExtVal(), Cond);
3681 }
3682 Comparison C(CmpOp0, CmpOp1, Chain);
3683 C.CCMask = CCMaskForCondCode(Cond);
3684 if (C.Op0.getValueType().isFloatingPoint()) {
3685 C.CCValid = SystemZ::CCMASK_FCMP;
3686 if (!C.Chain)
3687 C.Opcode = SystemZISD::FCMP;
3688 else if (!IsSignaling)
3689 C.Opcode = SystemZISD::STRICT_FCMP;
3690 else
3691 C.Opcode = SystemZISD::STRICT_FCMPS;
3693 } else {
3694 assert(!C.Chain);
3695 C.CCValid = SystemZ::CCMASK_ICMP;
3696 C.Opcode = SystemZISD::ICMP;
3697 // Choose the type of comparison. Equality and inequality tests can
3698 // use either signed or unsigned comparisons. The choice also doesn't
3699 // matter if both sign bits are known to be clear. In those cases we
3700 // want to give the main isel code the freedom to choose whichever
3701 // form fits best.
3702 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3703 C.CCMask == SystemZ::CCMASK_CMP_NE ||
3704 (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
3705 C.ICmpType = SystemZICMP::Any;
3706 else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
3707 C.ICmpType = SystemZICMP::UnsignedOnly;
3708 else
3709 C.ICmpType = SystemZICMP::SignedOnly;
3710 C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
3711 adjustForRedundantAnd(DAG, DL, C);
3712 adjustZeroCmp(DAG, DL, C);
3713 adjustSubwordCmp(DAG, DL, C);
3714 adjustForSubtraction(DAG, DL, C);
3716 adjustICmpTruncate(DAG, DL, C);
3717 }
3718
3719 if (shouldSwapCmpOperands(C)) {
3720 std::swap(C.Op0, C.Op1);
3721 C.CCMask = SystemZ::reverseCCMask(C.CCMask);
3722 }
3723
3725 adjustICmp128(DAG, DL, C);
3727 return C;
3728}
3729
3730// Emit the comparison instruction described by C.
3731static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
3732 if (!C.Op1.getNode()) {
3733 if (C.Opcode == SystemZISD::CMP_STACKGUARD)
3734 return DAG.getNode(SystemZISD::CMP_STACKGUARD, DL, MVT::i32, C.Op0);
3735 SDNode *Node;
3736 switch (C.Op0.getOpcode()) {
3738 Node = emitIntrinsicWithCCAndChain(DAG, C.Op0, C.Opcode);
3739 return SDValue(Node, 0);
3741 Node = emitIntrinsicWithCC(DAG, C.Op0, C.Opcode);
3742 return SDValue(Node, Node->getNumValues() - 1);
3743 default:
3744 llvm_unreachable("Invalid comparison operands");
3745 }
3746 }
3747 if (C.Opcode == SystemZISD::ICMP)
3748 return DAG.getNode(SystemZISD::ICMP, DL, MVT::i32, C.Op0, C.Op1,
3749 DAG.getTargetConstant(C.ICmpType, DL, MVT::i32));
3750 if (C.Opcode == SystemZISD::TM) {
3751 bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
3753 return DAG.getNode(SystemZISD::TM, DL, MVT::i32, C.Op0, C.Op1,
3754 DAG.getTargetConstant(RegisterOnly, DL, MVT::i32));
3755 }
3756 if (C.Opcode == SystemZISD::VICMPES ||
3757 C.Opcode == SystemZISD::VICMPHS ||
3758 C.Opcode == SystemZISD::VICMPHLS ||
3759 C.Opcode == SystemZISD::VFCMPES ||
3760 C.Opcode == SystemZISD::VFCMPHS ||
3761 C.Opcode == SystemZISD::VFCMPHES) {
3762 EVT IntVT = C.Op0.getValueType().changeVectorElementTypeToInteger();
3763 SDVTList VTs = DAG.getVTList(IntVT, MVT::i32);
3764 SDValue Val = DAG.getNode(C.Opcode, DL, VTs, C.Op0, C.Op1);
3765 return SDValue(Val.getNode(), 1);
3766 }
3767 if (C.Chain) {
3768 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
3769 return DAG.getNode(C.Opcode, DL, VTs, C.Chain, C.Op0, C.Op1);
3770 }
3771 return DAG.getNode(C.Opcode, DL, MVT::i32, C.Op0, C.Op1);
3772}
3773
3774// Implement a 32-bit *MUL_LOHI operation by extending both operands to
3775// 64 bits. Extend is the extension type to use. Store the high part
3776// in Hi and the low part in Lo.
3777static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend,
3778 SDValue Op0, SDValue Op1, SDValue &Hi,
3779 SDValue &Lo) {
3780 Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
3781 Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
3782 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
3783 Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
3784 DAG.getConstant(32, DL, MVT::i64));
3785 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
3786 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
3787}
3788
3789// Lower a binary operation that produces two VT results, one in each
3790// half of a GR128 pair. Op0 and Op1 are the VT operands to the operation,
3791// and Opcode performs the GR128 operation. Store the even register result
3792// in Even and the odd register result in Odd.
3793static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
3794 unsigned Opcode, SDValue Op0, SDValue Op1,
3795 SDValue &Even, SDValue &Odd) {
3796 SDValue Result = DAG.getNode(Opcode, DL, MVT::v2i64, Op0, Op1);
3797 bool Is32Bit = is32Bit(VT);
3798 Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
3799 Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
3800}
3801
3802// Return an i32 value that is 1 if the CC value produced by CCReg is
3803// in the mask CCMask and 0 otherwise. CC is known to have a value
3804// in CCValid, so other values can be ignored.
3805static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue CCReg,
3806 unsigned CCValid, unsigned CCMask) {
3807 SDValue Ops[] = {DAG.getConstant(1, DL, MVT::i32),
3808 DAG.getConstant(0, DL, MVT::i32),
3809 DAG.getTargetConstant(CCValid, DL, MVT::i32),
3810 DAG.getTargetConstant(CCMask, DL, MVT::i32), CCReg};
3811 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, MVT::i32, Ops);
3812}
3813
3814// Return the SystemISD vector comparison operation for CC, or 0 if it cannot
3815// be done directly. Mode is CmpMode::Int for integer comparisons, CmpMode::FP
3816// for regular floating-point comparisons, CmpMode::StrictFP for strict (quiet)
3817// floating-point comparisons, and CmpMode::SignalingFP for strict signaling
3818// floating-point comparisons.
3821 switch (CC) {
3822 case ISD::SETOEQ:
3823 case ISD::SETEQ:
3824 switch (Mode) {
3825 case CmpMode::Int: return SystemZISD::VICMPE;
3826 case CmpMode::FP: return SystemZISD::VFCMPE;
3827 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPE;
3828 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPES;
3829 }
3830 llvm_unreachable("Bad mode");
3831
3832 case ISD::SETOGE:
3833 case ISD::SETGE:
3834 switch (Mode) {
3835 case CmpMode::Int: return 0;
3836 case CmpMode::FP: return SystemZISD::VFCMPHE;
3837 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPHE;
3838 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHES;
3839 }
3840 llvm_unreachable("Bad mode");
3841
3842 case ISD::SETOGT:
3843 case ISD::SETGT:
3844 switch (Mode) {
3845 case CmpMode::Int: return SystemZISD::VICMPH;
3846 case CmpMode::FP: return SystemZISD::VFCMPH;
3847 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPH;
3848 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHS;
3849 }
3850 llvm_unreachable("Bad mode");
3851
3852 case ISD::SETUGT:
3853 switch (Mode) {
3854 case CmpMode::Int: return SystemZISD::VICMPHL;
3855 case CmpMode::FP: return 0;
3856 case CmpMode::StrictFP: return 0;
3857 case CmpMode::SignalingFP: return 0;
3858 }
3859 llvm_unreachable("Bad mode");
3860
3861 default:
3862 return 0;
3863 }
3864}
3865
3866// Return the SystemZISD vector comparison operation for CC or its inverse,
3867// or 0 if neither can be done directly. Indicate in Invert whether the
3868// result is for the inverse of CC. Mode is as above.
3870 bool &Invert) {
3871 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
3872 Invert = false;
3873 return Opcode;
3874 }
3875
3876 CC = ISD::getSetCCInverse(CC, Mode == CmpMode::Int ? MVT::i32 : MVT::f32);
3877 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
3878 Invert = true;
3879 return Opcode;
3880 }
3881
3882 return 0;
3883}
3884
3885// Return a v2f64 that contains the extended form of elements Start and Start+1
3886// of v4f32 value Op. If Chain is nonnull, return the strict form.
3887static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL,
3888 SDValue Op, SDValue Chain) {
3889 int Mask[] = { Start, -1, Start + 1, -1 };
3890 Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
3891 if (Chain) {
3892 SDVTList VTs = DAG.getVTList(MVT::v2f64, MVT::Other);
3893 return DAG.getNode(SystemZISD::STRICT_VEXTEND, DL, VTs, Chain, Op);
3894 }
3895 return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
3896}
3897
3898// Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
3899// producing a result of type VT. If Chain is nonnull, return the strict form.
3900SDValue SystemZTargetLowering::getVectorCmp(SelectionDAG &DAG, unsigned Opcode,
3901 const SDLoc &DL, EVT VT,
3902 SDValue CmpOp0,
3903 SDValue CmpOp1,
3904 SDValue Chain) const {
3905 // There is no hardware support for v4f32 (unless we have the vector
3906 // enhancements facility 1), so extend the vector into two v2f64s
3907 // and compare those.
3908 if (CmpOp0.getValueType() == MVT::v4f32 &&
3909 !Subtarget.hasVectorEnhancements1()) {
3910 SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0, Chain);
3911 SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0, Chain);
3912 SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1, Chain);
3913 SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1, Chain);
3914 if (Chain) {
3915 SDVTList VTs = DAG.getVTList(MVT::v2i64, MVT::Other);
3916 SDValue HRes = DAG.getNode(Opcode, DL, VTs, Chain, H0, H1);
3917 SDValue LRes = DAG.getNode(Opcode, DL, VTs, Chain, L0, L1);
3918 SDValue Res = DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
3919 SDValue Chains[6] = { H0.getValue(1), L0.getValue(1),
3920 H1.getValue(1), L1.getValue(1),
3921 HRes.getValue(1), LRes.getValue(1) };
3922 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
3923 SDValue Ops[2] = { Res, NewChain };
3924 return DAG.getMergeValues(Ops, DL);
3925 }
3926 SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
3927 SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
3928 return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
3929 }
3930 if (Chain) {
3931 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3932 return DAG.getNode(Opcode, DL, VTs, Chain, CmpOp0, CmpOp1);
3933 }
3934 return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
3935}
3936
3937// Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
3938// an integer mask of type VT. If Chain is nonnull, we have a strict
3939// floating-point comparison. If in addition IsSignaling is true, we have
3940// a strict signaling floating-point comparison.
3941SDValue SystemZTargetLowering::lowerVectorSETCC(SelectionDAG &DAG,
3942 const SDLoc &DL, EVT VT,
3943 ISD::CondCode CC,
3944 SDValue CmpOp0,
3945 SDValue CmpOp1,
3946 SDValue Chain,
3947 bool IsSignaling) const {
3948 bool IsFP = CmpOp0.getValueType().isFloatingPoint();
3949 assert (!Chain || IsFP);
3950 assert (!IsSignaling || Chain);
3951 CmpMode Mode = IsSignaling ? CmpMode::SignalingFP :
3952 Chain ? CmpMode::StrictFP : IsFP ? CmpMode::FP : CmpMode::Int;
3953 bool Invert = false;
3954 SDValue Cmp;
3955 switch (CC) {
3956 // Handle tests for order using (or (ogt y x) (oge x y)).
3957 case ISD::SETUO:
3958 Invert = true;
3959 [[fallthrough]];
3960 case ISD::SETO: {
3961 assert(IsFP && "Unexpected integer comparison");
3962 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
3963 DL, VT, CmpOp1, CmpOp0, Chain);
3964 SDValue GE = getVectorCmp(DAG, getVectorComparison(ISD::SETOGE, Mode),
3965 DL, VT, CmpOp0, CmpOp1, Chain);
3966 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
3967 if (Chain)
3968 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
3969 LT.getValue(1), GE.getValue(1));
3970 break;
3971 }
3972
3973 // Handle <> tests using (or (ogt y x) (ogt x y)).
3974 case ISD::SETUEQ:
3975 Invert = true;
3976 [[fallthrough]];
3977 case ISD::SETONE: {
3978 assert(IsFP && "Unexpected integer comparison");
3979 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
3980 DL, VT, CmpOp1, CmpOp0, Chain);
3981 SDValue GT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
3982 DL, VT, CmpOp0, CmpOp1, Chain);
3983 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
3984 if (Chain)
3985 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
3986 LT.getValue(1), GT.getValue(1));
3987 break;
3988 }
3989
3990 // Otherwise a single comparison is enough. It doesn't really
3991 // matter whether we try the inversion or the swap first, since
3992 // there are no cases where both work.
3993 default:
3994 // Optimize sign-bit comparisons to signed compares.
3995 if (Mode == CmpMode::Int && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
3997 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3998 APInt Mask;
3999 if (CmpOp0.getOpcode() == ISD::AND
4000 && ISD::isConstantSplatVector(CmpOp0.getOperand(1).getNode(), Mask)
4001 && Mask == APInt::getSignMask(EltSize)) {
4002 CC = CC == ISD::SETEQ ? ISD::SETGE : ISD::SETLT;
4003 CmpOp0 = CmpOp0.getOperand(0);
4004 }
4005 }
4006 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
4007 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1, Chain);
4008 else {
4010 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
4011 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0, Chain);
4012 else
4013 llvm_unreachable("Unhandled comparison");
4014 }
4015 if (Chain)
4016 Chain = Cmp.getValue(1);
4017 break;
4018 }
4019 if (Invert) {
4020 SDValue Mask =
4021 DAG.getSplatBuildVector(VT, DL, DAG.getAllOnesConstant(DL, MVT::i64));
4022 Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
4023 }
4024 if (Chain && Chain.getNode() != Cmp.getNode()) {
4025 SDValue Ops[2] = { Cmp, Chain };
4026 Cmp = DAG.getMergeValues(Ops, DL);
4027 }
4028 return Cmp;
4029}
4030
4031SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
4032 SelectionDAG &DAG) const {
4033 SDValue CmpOp0 = Op.getOperand(0);
4034 SDValue CmpOp1 = Op.getOperand(1);
4035 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4036 SDLoc DL(Op);
4037 EVT VT = Op.getValueType();
4038 if (VT.isVector())
4039 return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
4040
4041 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
4042 SDValue CCReg = emitCmp(DAG, DL, C);
4043 return emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
4044}
4045
4046SDValue SystemZTargetLowering::lowerSTRICT_FSETCC(SDValue Op,
4047 SelectionDAG &DAG,
4048 bool IsSignaling) const {
4049 SDValue Chain = Op.getOperand(0);
4050 SDValue CmpOp0 = Op.getOperand(1);
4051 SDValue CmpOp1 = Op.getOperand(2);
4052 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
4053 SDLoc DL(Op);
4054 EVT VT = Op.getNode()->getValueType(0);
4055 if (VT.isVector()) {
4056 SDValue Res = lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1,
4057 Chain, IsSignaling);
4058 return Res.getValue(Op.getResNo());
4059 }
4060
4061 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL, Chain, IsSignaling));
4062 SDValue CCReg = emitCmp(DAG, DL, C);
4063 CCReg->setFlags(Op->getFlags());
4064 SDValue Result = emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
4065 SDValue Ops[2] = { Result, CCReg.getValue(1) };
4066 return DAG.getMergeValues(Ops, DL);
4067}
4068
4069SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4070 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4071 SDValue CmpOp0 = Op.getOperand(2);
4072 SDValue CmpOp1 = Op.getOperand(3);
4073 SDValue Dest = Op.getOperand(4);
4074 SDLoc DL(Op);
4075
4076 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
4077 SDValue CCReg = emitCmp(DAG, DL, C);
4078 return DAG.getNode(
4079 SystemZISD::BR_CCMASK, DL, Op.getValueType(), Op.getOperand(0),
4080 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
4081 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), Dest, CCReg);
4082}
4083
4084// Return true if Pos is CmpOp and Neg is the negative of CmpOp,
4085// allowing Pos and Neg to be wider than CmpOp.
4086static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
4087 return (Neg.getOpcode() == ISD::SUB &&
4088 Neg.getOperand(0).getOpcode() == ISD::Constant &&
4089 Neg.getConstantOperandVal(0) == 0 && Neg.getOperand(1) == Pos &&
4090 (Pos == CmpOp || (Pos.getOpcode() == ISD::SIGN_EXTEND &&
4091 Pos.getOperand(0) == CmpOp)));
4092}
4093
4094// Return the absolute or negative absolute of Op; IsNegative decides which.
4096 bool IsNegative) {
4097 Op = DAG.getNode(ISD::ABS, DL, Op.getValueType(), Op);
4098 if (IsNegative)
4099 Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
4100 DAG.getConstant(0, DL, Op.getValueType()), Op);
4101 return Op;
4102}
4103
4105 Comparison C, SDValue TrueOp, SDValue FalseOp) {
4106 EVT VT = MVT::i128;
4107 unsigned Op;
4108
4109 if (C.CCMask == SystemZ::CCMASK_CMP_NE ||
4110 C.CCMask == SystemZ::CCMASK_CMP_GE ||
4111 C.CCMask == SystemZ::CCMASK_CMP_LE) {
4112 std::swap(TrueOp, FalseOp);
4113 C.CCMask ^= C.CCValid;
4114 }
4115 if (C.CCMask == SystemZ::CCMASK_CMP_LT) {
4116 std::swap(C.Op0, C.Op1);
4117 C.CCMask = SystemZ::CCMASK_CMP_GT;
4118 }
4119 switch (C.CCMask) {
4121 Op = SystemZISD::VICMPE;
4122 break;
4124 if (C.ICmpType == SystemZICMP::UnsignedOnly)
4125 Op = SystemZISD::VICMPHL;
4126 else
4127 Op = SystemZISD::VICMPH;
4128 break;
4129 default:
4130 llvm_unreachable("Unhandled comparison");
4131 break;
4132 }
4133
4134 SDValue Mask = DAG.getNode(Op, DL, VT, C.Op0, C.Op1);
4135 TrueOp = DAG.getNode(ISD::AND, DL, VT, TrueOp, Mask);
4136 FalseOp = DAG.getNode(ISD::AND, DL, VT, FalseOp, DAG.getNOT(DL, Mask, VT));
4137 return DAG.getNode(ISD::OR, DL, VT, TrueOp, FalseOp);
4138}
4139
4140SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
4141 SelectionDAG &DAG) const {
4142 SDValue CmpOp0 = Op.getOperand(0);
4143 SDValue CmpOp1 = Op.getOperand(1);
4144 SDValue TrueOp = Op.getOperand(2);
4145 SDValue FalseOp = Op.getOperand(3);
4146 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4147 SDLoc DL(Op);
4148
4149 // SELECT_CC involving f16 will not have the cmp-ops promoted by the
4150 // legalizer, as it will be handled according to the type of the resulting
4151 // value. Extend them here if needed.
4152 if (CmpOp0.getSimpleValueType() == MVT::f16) {
4153 CmpOp0 = DAG.getFPExtendOrRound(CmpOp0, SDLoc(CmpOp0), MVT::f32);
4154 CmpOp1 = DAG.getFPExtendOrRound(CmpOp1, SDLoc(CmpOp1), MVT::f32);
4155 }
4156
4157 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
4158
4159 // Check for absolute and negative-absolute selections, including those
4160 // where the comparison value is sign-extended (for LPGFR and LNGFR).
4161 // This check supplements the one in DAGCombiner.
4162 if (C.Opcode == SystemZISD::ICMP && C.CCMask != SystemZ::CCMASK_CMP_EQ &&
4163 C.CCMask != SystemZ::CCMASK_CMP_NE &&
4164 C.Op1.getOpcode() == ISD::Constant &&
4165 cast<ConstantSDNode>(C.Op1)->getValueSizeInBits(0) <= 64 &&
4166 C.Op1->getAsZExtVal() == 0) {
4167 if (isAbsolute(C.Op0, TrueOp, FalseOp))
4168 return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
4169 if (isAbsolute(C.Op0, FalseOp, TrueOp))
4170 return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
4171 }
4172
4173 if (Subtarget.hasVectorEnhancements3() &&
4174 C.Opcode == SystemZISD::ICMP &&
4175 C.Op0.getValueType() == MVT::i128 &&
4176 TrueOp.getValueType() == MVT::i128) {
4177 return getI128Select(DAG, DL, C, TrueOp, FalseOp);
4178 }
4179
4180 SDValue CCReg = emitCmp(DAG, DL, C);
4181 SDValue Ops[] = {TrueOp, FalseOp,
4182 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
4183 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), CCReg};
4184
4185 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, Op.getValueType(), Ops);
4186}
4187
4188SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
4189 SelectionDAG &DAG) const {
4190 SDLoc DL(Node);
4191 const GlobalValue *GV = Node->getGlobal();
4192 int64_t Offset = Node->getOffset();
4193 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4195
4196 SDValue Result;
4197 if (Subtarget.isPC32DBLSymbol(GV, CM)) {
4198 if (isInt<32>(Offset)) {
4199 // Assign anchors at 1<<12 byte boundaries.
4200 uint64_t Anchor = Offset & ~uint64_t(0xfff);
4201 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
4202 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4203
4204 // The offset can be folded into the address if it is aligned to a
4205 // halfword.
4206 Offset -= Anchor;
4207 if (Offset != 0 && (Offset & 1) == 0) {
4208 SDValue Full =
4209 DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
4210 Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
4211 Offset = 0;
4212 }
4213 } else {
4214 // Conservatively load a constant offset greater than 32 bits into a
4215 // register below.
4216 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT);
4217 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4218 }
4219 } else if (Subtarget.isTargetELF()) {
4220 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
4221 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4222 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4224 } else if (Subtarget.isTargetzOS()) {
4225 Result = getADAEntry(DAG, GV, DL, PtrVT);
4226 } else
4227 llvm_unreachable("Unexpected Subtarget");
4228
4229 // If there was a non-zero offset that we didn't fold, create an explicit
4230 // addition for it.
4231 if (Offset != 0)
4232 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
4233 DAG.getSignedConstant(Offset, DL, PtrVT));
4234
4235 return Result;
4236}
4237
4238SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
4239 SelectionDAG &DAG,
4240 unsigned Opcode,
4241 SDValue GOTOffset) const {
4242 SDLoc DL(Node);
4243 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4244 SDValue Chain = DAG.getEntryNode();
4245 SDValue Glue;
4246
4249 report_fatal_error("In GHC calling convention TLS is not supported");
4250
4251 // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
4252 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
4253 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
4254 Glue = Chain.getValue(1);
4255 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
4256 Glue = Chain.getValue(1);
4257
4258 // The first call operand is the chain and the second is the TLS symbol.
4260 Ops.push_back(Chain);
4261 Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
4262 Node->getValueType(0),
4263 0, 0));
4264
4265 // Add argument registers to the end of the list so that they are
4266 // known live into the call.
4267 Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
4268 Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
4269
4270 // Add a register mask operand representing the call-preserved registers.
4271 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4272 const uint32_t *Mask =
4273 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
4274 assert(Mask && "Missing call preserved mask for calling convention");
4275 Ops.push_back(DAG.getRegisterMask(Mask));
4276
4277 // Glue the call to the argument copies.
4278 Ops.push_back(Glue);
4279
4280 // Emit the call.
4281 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4282 Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
4283 Glue = Chain.getValue(1);
4284
4285 // Copy the return value from %r2.
4286 return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
4287}
4288
4289SDValue SystemZTargetLowering::lowerThreadPointer(const SDLoc &DL,
4290 SelectionDAG &DAG) const {
4291 SDValue Chain = DAG.getEntryNode();
4292 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4293
4294 // The high part of the thread pointer is in access register 0.
4295 SDValue TPHi = DAG.getCopyFromReg(Chain, DL, SystemZ::A0, MVT::i32);
4296 TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
4297
4298 // The low part of the thread pointer is in access register 1.
4299 SDValue TPLo = DAG.getCopyFromReg(Chain, DL, SystemZ::A1, MVT::i32);
4300 TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
4301
4302 // Merge them into a single 64-bit address.
4303 SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
4304 DAG.getConstant(32, DL, PtrVT));
4305 return DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
4306}
4307
4308SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
4309 SelectionDAG &DAG) const {
4310 if (DAG.getTarget().useEmulatedTLS())
4311 return LowerToTLSEmulatedModel(Node, DAG);
4312 SDLoc DL(Node);
4313 const GlobalValue *GV = Node->getGlobal();
4314 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4315 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
4316
4319 report_fatal_error("In GHC calling convention TLS is not supported");
4320
4321 SDValue TP = lowerThreadPointer(DL, DAG);
4322
4323 // Get the offset of GA from the thread pointer, based on the TLS model.
4324 SDValue Offset;
4325 switch (model) {
4327 // Load the GOT offset of the tls_index (module ID / per-symbol offset).
4328 SystemZConstantPoolValue *CPV =
4330
4331 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4332 Offset = DAG.getLoad(
4333 PtrVT, DL, DAG.getEntryNode(), Offset,
4335
4336 // Call __tls_get_offset to retrieve the offset.
4337 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
4338 break;
4339 }
4340
4342 // Load the GOT offset of the module ID.
4343 SystemZConstantPoolValue *CPV =
4345
4346 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4347 Offset = DAG.getLoad(
4348 PtrVT, DL, DAG.getEntryNode(), Offset,
4350
4351 // Call __tls_get_offset to retrieve the module base offset.
4352 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
4353
4354 // Note: The SystemZLDCleanupPass will remove redundant computations
4355 // of the module base offset. Count total number of local-dynamic
4356 // accesses to trigger execution of that pass.
4357 SystemZMachineFunctionInfo* MFI =
4358 DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>();
4360
4361 // Add the per-symbol offset.
4363
4364 SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4365 DTPOffset = DAG.getLoad(
4366 PtrVT, DL, DAG.getEntryNode(), DTPOffset,
4368
4369 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
4370 break;
4371 }
4372
4373 case TLSModel::InitialExec: {
4374 // Load the offset from the GOT.
4375 Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
4377 Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
4378 Offset =
4379 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset,
4381 break;
4382 }
4383
4384 case TLSModel::LocalExec: {
4385 // Force the offset into the constant pool and load it from there.
4386 SystemZConstantPoolValue *CPV =
4388
4389 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4390 Offset = DAG.getLoad(
4391 PtrVT, DL, DAG.getEntryNode(), Offset,
4393 break;
4394 }
4395 }
4396
4397 // Add the base and offset together.
4398 return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
4399}
4400
4401SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
4402 SelectionDAG &DAG) const {
4403 SDLoc DL(Node);
4404 const BlockAddress *BA = Node->getBlockAddress();
4405 int64_t Offset = Node->getOffset();
4406 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4407
4408 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
4409 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4410 return Result;
4411}
4412
4413SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
4414 SelectionDAG &DAG) const {
4415 SDLoc DL(JT);
4416 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4417 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
4418
4419 // Use LARL to load the address of the table.
4420 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4421}
4422
4423SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
4424 SelectionDAG &DAG) const {
4425 SDLoc DL(CP);
4426 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4427
4428 SDValue Result;
4430 Result =
4431 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign());
4432 else
4433 Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign(),
4434 CP->getOffset());
4435
4436 // Use LARL to load the address of the constant pool entry.
4437 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4438}
4439
4440SDValue SystemZTargetLowering::lowerFRAMEADDR(SDValue Op,
4441 SelectionDAG &DAG) const {
4442 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
4444 MachineFrameInfo &MFI = MF.getFrameInfo();
4445 MFI.setFrameAddressIsTaken(true);
4446
4447 SDLoc DL(Op);
4448 unsigned Depth = Op.getConstantOperandVal(0);
4449 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4450
4451 // By definition, the frame address is the address of the back chain. (In
4452 // the case of packed stack without backchain, return the address where the
4453 // backchain would have been stored. This will either be an unused space or
4454 // contain a saved register).
4455 int BackChainIdx = TFL->getOrCreateFramePointerSaveIndex(MF);
4456 SDValue BackChain = DAG.getFrameIndex(BackChainIdx, PtrVT);
4457
4458 if (Depth > 0) {
4459 // FIXME The frontend should detect this case.
4460 if (!MF.getSubtarget<SystemZSubtarget>().hasBackChain())
4461 report_fatal_error("Unsupported stack frame traversal count");
4462
4463 SDValue Offset = DAG.getConstant(TFL->getBackchainOffset(MF), DL, PtrVT);
4464 while (Depth--) {
4465 BackChain = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), BackChain,
4466 MachinePointerInfo());
4467 BackChain = DAG.getNode(ISD::ADD, DL, PtrVT, BackChain, Offset);
4468 }
4469 }
4470
4471 return BackChain;
4472}
4473
4474SDValue SystemZTargetLowering::lowerRETURNADDR(SDValue Op,
4475 SelectionDAG &DAG) const {
4477 MachineFrameInfo &MFI = MF.getFrameInfo();
4478 MFI.setReturnAddressIsTaken(true);
4479
4480 SDLoc DL(Op);
4481 unsigned Depth = Op.getConstantOperandVal(0);
4482 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4483
4484 if (Depth > 0) {
4485 // FIXME The frontend should detect this case.
4486 if (!MF.getSubtarget<SystemZSubtarget>().hasBackChain())
4487 report_fatal_error("Unsupported stack frame traversal count");
4488
4489 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
4490 const auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
4491 int Offset = TFL->getReturnAddressOffset(MF);
4492 SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, FrameAddr,
4493 DAG.getSignedConstant(Offset, DL, PtrVT));
4494 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr,
4495 MachinePointerInfo());
4496 }
4497
4498 // Return R14D (Elf) / R7D (XPLINK), which has the return address. Mark it an
4499 // implicit live-in.
4500 SystemZCallingConventionRegisters *CCR = Subtarget.getSpecialRegisters();
4502 &SystemZ::GR64BitRegClass);
4503 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, LinkReg, PtrVT);
4504}
4505
4506SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
4507 SelectionDAG &DAG) const {
4508 SDLoc DL(Op);
4509 SDValue In = Op.getOperand(0);
4510 EVT InVT = In.getValueType();
4511 EVT ResVT = Op.getValueType();
4512
4513 // Convert loads directly. This is normally done by DAGCombiner,
4514 // but we need this case for bitcasts that are created during lowering
4515 // and which are then lowered themselves.
4516 if (auto *LoadN = dyn_cast<LoadSDNode>(In))
4517 if (ISD::isNormalLoad(LoadN)) {
4518 SDValue NewLoad = DAG.getLoad(ResVT, DL, LoadN->getChain(),
4519 LoadN->getBasePtr(), LoadN->getMemOperand());
4520 // Update the chain uses.
4521 DAG.ReplaceAllUsesOfValueWith(SDValue(LoadN, 1), NewLoad.getValue(1));
4522 return NewLoad;
4523 }
4524
4525 if (InVT == MVT::i32 && ResVT == MVT::f32) {
4526 SDValue In64;
4527 if (Subtarget.hasHighWord()) {
4528 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
4529 MVT::i64);
4530 In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
4531 MVT::i64, SDValue(U64, 0), In);
4532 } else {
4533 In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
4534 In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
4535 DAG.getConstant(32, DL, MVT::i64));
4536 }
4537 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
4538 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32,
4539 DL, MVT::f32, Out64);
4540 }
4541 if (InVT == MVT::f32 && ResVT == MVT::i32) {
4542 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
4543 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
4544 MVT::f64, SDValue(U64, 0), In);
4545 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
4546 if (Subtarget.hasHighWord())
4547 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
4548 MVT::i32, Out64);
4549 SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
4550 DAG.getConstant(32, DL, MVT::i64));
4551 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
4552 }
4553 llvm_unreachable("Unexpected bitcast combination");
4554}
4555
4556SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
4557 SelectionDAG &DAG) const {
4558
4559 if (Subtarget.isTargetXPLINK64())
4560 return lowerVASTART_XPLINK(Op, DAG);
4561 else
4562 return lowerVASTART_ELF(Op, DAG);
4563}
4564
4565SDValue SystemZTargetLowering::lowerVASTART_XPLINK(SDValue Op,
4566 SelectionDAG &DAG) const {
4568 SystemZMachineFunctionInfo *FuncInfo =
4569 MF.getInfo<SystemZMachineFunctionInfo>();
4570
4571 SDLoc DL(Op);
4572
4573 // vastart just stores the address of the VarArgsFrameIndex slot into the
4574 // memory location argument.
4575 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4576 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4577 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4578 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4579 MachinePointerInfo(SV));
4580}
4581
4582SDValue SystemZTargetLowering::lowerVASTART_ELF(SDValue Op,
4583 SelectionDAG &DAG) const {
4585 SystemZMachineFunctionInfo *FuncInfo =
4586 MF.getInfo<SystemZMachineFunctionInfo>();
4587 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4588
4589 SDValue Chain = Op.getOperand(0);
4590 SDValue Addr = Op.getOperand(1);
4591 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4592 SDLoc DL(Op);
4593
4594 // The initial values of each field.
4595 const unsigned NumFields = 4;
4596 SDValue Fields[NumFields] = {
4597 DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
4598 DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
4599 DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
4600 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
4601 };
4602
4603 // Store each field into its respective slot.
4604 SDValue MemOps[NumFields];
4605 unsigned Offset = 0;
4606 for (unsigned I = 0; I < NumFields; ++I) {
4607 SDValue FieldAddr = Addr;
4608 if (Offset != 0)
4609 FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
4611 MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
4612 MachinePointerInfo(SV, Offset));
4613 Offset += 8;
4614 }
4615 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4616}
4617
4618SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
4619 SelectionDAG &DAG) const {
4620 SDValue Chain = Op.getOperand(0);
4621 SDValue DstPtr = Op.getOperand(1);
4622 SDValue SrcPtr = Op.getOperand(2);
4623 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4624 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4625 SDLoc DL(Op);
4626
4627 uint32_t Sz =
4628 Subtarget.isTargetXPLINK64() ? DAG.getDataLayout().getPointerSize(0) : 32;
4629 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(Sz, DL),
4630 Align(8), Align(8), /*isVolatile*/ false,
4631 /*AlwaysInline*/ false,
4632 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(DstSV),
4633 MachinePointerInfo(SrcSV));
4634}
4635
4636SDValue
4637SystemZTargetLowering::lowerDYNAMIC_STACKALLOC(SDValue Op,
4638 SelectionDAG &DAG) const {
4639 if (Subtarget.isTargetXPLINK64())
4640 return lowerDYNAMIC_STACKALLOC_XPLINK(Op, DAG);
4641 else
4642 return lowerDYNAMIC_STACKALLOC_ELF(Op, DAG);
4643}
4644
4645SDValue
4646SystemZTargetLowering::lowerDYNAMIC_STACKALLOC_XPLINK(SDValue Op,
4647 SelectionDAG &DAG) const {
4648 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
4650 bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack");
4651 SDValue Chain = Op.getOperand(0);
4652 SDValue Size = Op.getOperand(1);
4653 SDValue Align = Op.getOperand(2);
4654 SDLoc DL(Op);
4655
4656 // If user has set the no alignment function attribute, ignore
4657 // alloca alignments.
4658 uint64_t AlignVal = (RealignOpt ? Align->getAsZExtVal() : 0);
4659
4660 uint64_t StackAlign = TFI->getStackAlignment();
4661 uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
4662 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
4663
4664 SDValue NeededSpace = Size;
4665
4666 // Add extra space for alignment if needed.
4667 EVT PtrVT = getPointerTy(MF.getDataLayout());
4668 if (ExtraAlignSpace)
4669 NeededSpace = DAG.getNode(ISD::ADD, DL, PtrVT, NeededSpace,
4670 DAG.getConstant(ExtraAlignSpace, DL, PtrVT));
4671
4672 bool IsSigned = false;
4673 bool DoesNotReturn = false;
4674 bool IsReturnValueUsed = false;
4675 EVT VT = Op.getValueType();
4676 SDValue AllocaCall =
4677 makeExternalCall(Chain, DAG, "@@ALCAXP", VT, ArrayRef(NeededSpace),
4678 CallingConv::C, IsSigned, DL, DoesNotReturn,
4679 IsReturnValueUsed)
4680 .first;
4681
4682 // Perform a CopyFromReg from %GPR4 (stack pointer register). Chain and Glue
4683 // to end of call in order to ensure it isn't broken up from the call
4684 // sequence.
4685 auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
4686 Register SPReg = Regs.getStackPointerRegister();
4687 Chain = AllocaCall.getValue(1);
4688 SDValue Glue = AllocaCall.getValue(2);
4689 SDValue NewSPRegNode = DAG.getCopyFromReg(Chain, DL, SPReg, PtrVT, Glue);
4690 Chain = NewSPRegNode.getValue(1);
4691
4692 MVT PtrMVT = getPointerMemTy(MF.getDataLayout());
4693 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, PtrMVT);
4694 SDValue Result = DAG.getNode(ISD::ADD, DL, PtrMVT, NewSPRegNode, ArgAdjust);
4695
4696 // Dynamically realign if needed.
4697 if (ExtraAlignSpace) {
4698 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
4699 DAG.getConstant(ExtraAlignSpace, DL, PtrVT));
4700 Result = DAG.getNode(ISD::AND, DL, PtrVT, Result,
4701 DAG.getConstant(~(RequiredAlign - 1), DL, PtrVT));
4702 }
4703
4704 SDValue Ops[2] = {Result, Chain};
4705 return DAG.getMergeValues(Ops, DL);
4706}
4707
4708SDValue
4709SystemZTargetLowering::lowerDYNAMIC_STACKALLOC_ELF(SDValue Op,
4710 SelectionDAG &DAG) const {
4711 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
4713 bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack");
4714 bool StoreBackchain = MF.getSubtarget<SystemZSubtarget>().hasBackChain();
4715
4716 SDValue Chain = Op.getOperand(0);
4717 SDValue Size = Op.getOperand(1);
4718 SDValue Align = Op.getOperand(2);
4719 SDLoc DL(Op);
4720
4721 // If user has set the no alignment function attribute, ignore
4722 // alloca alignments.
4723 uint64_t AlignVal = (RealignOpt ? Align->getAsZExtVal() : 0);
4724
4725 uint64_t StackAlign = TFI->getStackAlignment();
4726 uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
4727 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
4728
4730 SDValue NeededSpace = Size;
4731
4732 // Get a reference to the stack pointer.
4733 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
4734
4735 // If we need a backchain, save it now.
4736 SDValue Backchain;
4737 if (StoreBackchain)
4738 Backchain = DAG.getLoad(MVT::i64, DL, Chain, getBackchainAddress(OldSP, DAG),
4739 MachinePointerInfo());
4740
4741 // Add extra space for alignment if needed.
4742 if (ExtraAlignSpace)
4743 NeededSpace = DAG.getNode(ISD::ADD, DL, MVT::i64, NeededSpace,
4744 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
4745
4746 // Get the new stack pointer value.
4747 SDValue NewSP;
4748 if (hasInlineStackProbe(MF)) {
4749 NewSP = DAG.getNode(SystemZISD::PROBED_ALLOCA, DL,
4750 DAG.getVTList(MVT::i64, MVT::Other), Chain, OldSP, NeededSpace);
4751 Chain = NewSP.getValue(1);
4752 }
4753 else {
4754 NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, NeededSpace);
4755 // Copy the new stack pointer back.
4756 Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
4757 }
4758
4759 // The allocated data lives above the 160 bytes allocated for the standard
4760 // frame, plus any outgoing stack arguments. We don't know how much that
4761 // amounts to yet, so emit a special ADJDYNALLOC placeholder.
4762 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
4763 SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
4764
4765 // Dynamically realign if needed.
4766 if (RequiredAlign > StackAlign) {
4767 Result =
4768 DAG.getNode(ISD::ADD, DL, MVT::i64, Result,
4769 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
4770 Result =
4771 DAG.getNode(ISD::AND, DL, MVT::i64, Result,
4772 DAG.getConstant(~(RequiredAlign - 1), DL, MVT::i64));
4773 }
4774
4775 if (StoreBackchain)
4776 Chain = DAG.getStore(Chain, DL, Backchain, getBackchainAddress(NewSP, DAG),
4777 MachinePointerInfo());
4778
4779 SDValue Ops[2] = { Result, Chain };
4780 return DAG.getMergeValues(Ops, DL);
4781}
4782
4783SDValue SystemZTargetLowering::lowerGET_DYNAMIC_AREA_OFFSET(
4784 SDValue Op, SelectionDAG &DAG) const {
4785 SDLoc DL(Op);
4786
4787 return DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
4788}
4789
4790SDValue SystemZTargetLowering::lowerMULH(SDValue Op,
4791 SelectionDAG &DAG,
4792 unsigned Opcode) const {
4793 EVT VT = Op.getValueType();
4794 SDLoc DL(Op);
4795 SDValue Even, Odd;
4796
4797 // This custom expander is only used on z17 and later for 64-bit types.
4798 assert(!is32Bit(VT));
4799 assert(Subtarget.hasMiscellaneousExtensions2());
4800
4801 // SystemZISD::xMUL_LOHI returns the low result in the odd register and
4802 // the high result in the even register. Return the latter.
4803 lowerGR128Binary(DAG, DL, VT, Opcode,
4804 Op.getOperand(0), Op.getOperand(1), Even, Odd);
4805 return Even;
4806}
4807
4808SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
4809 SelectionDAG &DAG) const {
4810 EVT VT = Op.getValueType();
4811 SDLoc DL(Op);
4812 SDValue Ops[2];
4813 if (is32Bit(VT))
4814 // Just do a normal 64-bit multiplication and extract the results.
4815 // We define this so that it can be used for constant division.
4816 lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
4817 Op.getOperand(1), Ops[1], Ops[0]);
4818 else if (Subtarget.hasMiscellaneousExtensions2())
4819 // SystemZISD::SMUL_LOHI returns the low result in the odd register and
4820 // the high result in the even register. ISD::SMUL_LOHI is defined to
4821 // return the low half first, so the results are in reverse order.
4822 lowerGR128Binary(DAG, DL, VT, SystemZISD::SMUL_LOHI,
4823 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
4824 else {
4825 // Do a full 128-bit multiplication based on SystemZISD::UMUL_LOHI:
4826 //
4827 // (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
4828 //
4829 // but using the fact that the upper halves are either all zeros
4830 // or all ones:
4831 //
4832 // (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
4833 //
4834 // and grouping the right terms together since they are quicker than the
4835 // multiplication:
4836 //
4837 // (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
4838 SDValue C63 = DAG.getConstant(63, DL, MVT::i64);
4839 SDValue LL = Op.getOperand(0);
4840 SDValue RL = Op.getOperand(1);
4841 SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
4842 SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
4843 // SystemZISD::UMUL_LOHI returns the low result in the odd register and
4844 // the high result in the even register. ISD::SMUL_LOHI is defined to
4845 // return the low half first, so the results are in reverse order.
4846 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
4847 LL, RL, Ops[1], Ops[0]);
4848 SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
4849 SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
4850 SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
4851 Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
4852 }
4853 return DAG.getMergeValues(Ops, DL);
4854}
4855
4856SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
4857 SelectionDAG &DAG) const {
4858 EVT VT = Op.getValueType();
4859 SDLoc DL(Op);
4860 SDValue Ops[2];
4861 if (is32Bit(VT))
4862 // Just do a normal 64-bit multiplication and extract the results.
4863 // We define this so that it can be used for constant division.
4864 lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
4865 Op.getOperand(1), Ops[1], Ops[0]);
4866 else
4867 // SystemZISD::UMUL_LOHI returns the low result in the odd register and
4868 // the high result in the even register. ISD::UMUL_LOHI is defined to
4869 // return the low half first, so the results are in reverse order.
4870 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
4871 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
4872 return DAG.getMergeValues(Ops, DL);
4873}
4874
4875SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
4876 SelectionDAG &DAG) const {
4877 SDValue Op0 = Op.getOperand(0);
4878 SDValue Op1 = Op.getOperand(1);
4879 EVT VT = Op.getValueType();
4880 SDLoc DL(Op);
4881
4882 // We use DSGF for 32-bit division. This means the first operand must
4883 // always be 64-bit, and the second operand should be 32-bit whenever
4884 // that is possible, to improve performance.
4885 if (is32Bit(VT))
4886 Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
4887 else if (DAG.ComputeNumSignBits(Op1) > 32)
4888 Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
4889
4890 // DSG(F) returns the remainder in the even register and the
4891 // quotient in the odd register.
4892 SDValue Ops[2];
4893 lowerGR128Binary(DAG, DL, VT, SystemZISD::SDIVREM, Op0, Op1, Ops[1], Ops[0]);
4894 return DAG.getMergeValues(Ops, DL);
4895}
4896
4897SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
4898 SelectionDAG &DAG) const {
4899 EVT VT = Op.getValueType();
4900 SDLoc DL(Op);
4901
4902 // DL(G) returns the remainder in the even register and the
4903 // quotient in the odd register.
4904 SDValue Ops[2];
4905 lowerGR128Binary(DAG, DL, VT, SystemZISD::UDIVREM,
4906 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
4907 return DAG.getMergeValues(Ops, DL);
4908}
4909
4910SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
4911 assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
4912
4913 // Get the known-zero masks for each operand.
4914 SDValue Ops[] = {Op.getOperand(0), Op.getOperand(1)};
4915 KnownBits Known[2] = {DAG.computeKnownBits(Ops[0]),
4916 DAG.computeKnownBits(Ops[1])};
4917
4918 // See if the upper 32 bits of one operand and the lower 32 bits of the
4919 // other are known zero. They are the low and high operands respectively.
4920 uint64_t Masks[] = { Known[0].Zero.getZExtValue(),
4921 Known[1].Zero.getZExtValue() };
4922 unsigned High, Low;
4923 if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
4924 High = 1, Low = 0;
4925 else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
4926 High = 0, Low = 1;
4927 else
4928 return Op;
4929
4930 SDValue LowOp = Ops[Low];
4931 SDValue HighOp = Ops[High];
4932
4933 // If the high part is a constant, we're better off using IILH.
4934 if (HighOp.getOpcode() == ISD::Constant)
4935 return Op;
4936
4937 // If the low part is a constant that is outside the range of LHI,
4938 // then we're better off using IILF.
4939 if (LowOp.getOpcode() == ISD::Constant) {
4940 int64_t Value = int32_t(LowOp->getAsZExtVal());
4941 if (!isInt<16>(Value))
4942 return Op;
4943 }
4944
4945 // Check whether the high part is an AND that doesn't change the
4946 // high 32 bits and just masks out low bits. We can skip it if so.
4947 if (HighOp.getOpcode() == ISD::AND &&
4948 HighOp.getOperand(1).getOpcode() == ISD::Constant) {
4949 SDValue HighOp0 = HighOp.getOperand(0);
4951 if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
4952 HighOp = HighOp0;
4953 }
4954
4955 // Take advantage of the fact that all GR32 operations only change the
4956 // low 32 bits by truncating Low to an i32 and inserting it directly
4957 // using a subreg. The interesting cases are those where the truncation
4958 // can be folded.
4959 SDLoc DL(Op);
4960 SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
4961 return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
4962 MVT::i64, HighOp, Low32);
4963}
4964
4965// Lower SADDO/SSUBO/UADDO/USUBO nodes.
4966SDValue SystemZTargetLowering::lowerXALUO(SDValue Op,
4967 SelectionDAG &DAG) const {
4968 SDNode *N = Op.getNode();
4969 SDValue LHS = N->getOperand(0);
4970 SDValue RHS = N->getOperand(1);
4971 SDLoc DL(N);
4972
4973 if (N->getValueType(0) == MVT::i128) {
4974 unsigned BaseOp = 0;
4975 unsigned FlagOp = 0;
4976 bool IsBorrow = false;
4977 switch (Op.getOpcode()) {
4978 default: llvm_unreachable("Unknown instruction!");
4979 case ISD::UADDO:
4980 BaseOp = ISD::ADD;
4981 FlagOp = SystemZISD::VACC;
4982 break;
4983 case ISD::USUBO:
4984 BaseOp = ISD::SUB;
4985 FlagOp = SystemZISD::VSCBI;
4986 IsBorrow = true;
4987 break;
4988 }
4989 SDValue Result = DAG.getNode(BaseOp, DL, MVT::i128, LHS, RHS);
4990 SDValue Flag = DAG.getNode(FlagOp, DL, MVT::i128, LHS, RHS);
4991 Flag = DAG.getNode(ISD::AssertZext, DL, MVT::i128, Flag,
4992 DAG.getValueType(MVT::i1));
4993 Flag = DAG.getZExtOrTrunc(Flag, DL, N->getValueType(1));
4994 if (IsBorrow)
4995 Flag = DAG.getNode(ISD::XOR, DL, Flag.getValueType(),
4996 Flag, DAG.getConstant(1, DL, Flag.getValueType()));
4997 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Flag);
4998 }
4999
5000 unsigned BaseOp = 0;
5001 unsigned CCValid = 0;
5002 unsigned CCMask = 0;
5003
5004 switch (Op.getOpcode()) {
5005 default: llvm_unreachable("Unknown instruction!");
5006 case ISD::SADDO:
5007 BaseOp = SystemZISD::SADDO;
5008 CCValid = SystemZ::CCMASK_ARITH;
5010 break;
5011 case ISD::SSUBO:
5012 BaseOp = SystemZISD::SSUBO;
5013 CCValid = SystemZ::CCMASK_ARITH;
5015 break;
5016 case ISD::UADDO:
5017 BaseOp = SystemZISD::UADDO;
5018 CCValid = SystemZ::CCMASK_LOGICAL;
5020 break;
5021 case ISD::USUBO:
5022 BaseOp = SystemZISD::USUBO;
5023 CCValid = SystemZ::CCMASK_LOGICAL;
5025 break;
5026 }
5027
5028 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
5029 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
5030
5031 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
5032 if (N->getValueType(1) == MVT::i1)
5033 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
5034
5035 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
5036}
5037
5038static bool isAddCarryChain(SDValue Carry) {
5039 while (Carry.getOpcode() == ISD::UADDO_CARRY &&
5040 Carry->getValueType(0) != MVT::i128)
5041 Carry = Carry.getOperand(2);
5042 return Carry.getOpcode() == ISD::UADDO &&
5043 Carry->getValueType(0) != MVT::i128;
5044}
5045
5046static bool isSubBorrowChain(SDValue Carry) {
5047 while (Carry.getOpcode() == ISD::USUBO_CARRY &&
5048 Carry->getValueType(0) != MVT::i128)
5049 Carry = Carry.getOperand(2);
5050 return Carry.getOpcode() == ISD::USUBO &&
5051 Carry->getValueType(0) != MVT::i128;
5052}
5053
5054// Lower UADDO_CARRY/USUBO_CARRY nodes.
5055SDValue SystemZTargetLowering::lowerUADDSUBO_CARRY(SDValue Op,
5056 SelectionDAG &DAG) const {
5057
5058 SDNode *N = Op.getNode();
5059 MVT VT = N->getSimpleValueType(0);
5060
5061 // Let legalize expand this if it isn't a legal type yet.
5062 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
5063 return SDValue();
5064
5065 SDValue LHS = N->getOperand(0);
5066 SDValue RHS = N->getOperand(1);
5067 SDValue Carry = Op.getOperand(2);
5068 SDLoc DL(N);
5069
5070 if (VT == MVT::i128) {
5071 unsigned BaseOp = 0;
5072 unsigned FlagOp = 0;
5073 bool IsBorrow = false;
5074 switch (Op.getOpcode()) {
5075 default: llvm_unreachable("Unknown instruction!");
5076 case ISD::UADDO_CARRY:
5077 BaseOp = SystemZISD::VAC;
5078 FlagOp = SystemZISD::VACCC;
5079 break;
5080 case ISD::USUBO_CARRY:
5081 BaseOp = SystemZISD::VSBI;
5082 FlagOp = SystemZISD::VSBCBI;
5083 IsBorrow = true;
5084 break;
5085 }
5086 if (IsBorrow)
5087 Carry = DAG.getNode(ISD::XOR, DL, Carry.getValueType(),
5088 Carry, DAG.getConstant(1, DL, Carry.getValueType()));
5089 Carry = DAG.getZExtOrTrunc(Carry, DL, MVT::i128);
5090 SDValue Result = DAG.getNode(BaseOp, DL, MVT::i128, LHS, RHS, Carry);
5091 SDValue Flag = DAG.getNode(FlagOp, DL, MVT::i128, LHS, RHS, Carry);
5092 Flag = DAG.getNode(ISD::AssertZext, DL, MVT::i128, Flag,
5093 DAG.getValueType(MVT::i1));
5094 Flag = DAG.getZExtOrTrunc(Flag, DL, N->getValueType(1));
5095 if (IsBorrow)
5096 Flag = DAG.getNode(ISD::XOR, DL, Flag.getValueType(),
5097 Flag, DAG.getConstant(1, DL, Flag.getValueType()));
5098 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Flag);
5099 }
5100
5101 unsigned BaseOp = 0;
5102 unsigned CCValid = 0;
5103 unsigned CCMask = 0;
5104
5105 switch (Op.getOpcode()) {
5106 default: llvm_unreachable("Unknown instruction!");
5107 case ISD::UADDO_CARRY:
5108 if (!isAddCarryChain(Carry))
5109 return SDValue();
5110
5111 BaseOp = SystemZISD::ADDCARRY;
5112 CCValid = SystemZ::CCMASK_LOGICAL;
5114 break;
5115 case ISD::USUBO_CARRY:
5116 if (!isSubBorrowChain(Carry))
5117 return SDValue();
5118
5119 BaseOp = SystemZISD::SUBCARRY;
5120 CCValid = SystemZ::CCMASK_LOGICAL;
5122 break;
5123 }
5124
5125 // Set the condition code from the carry flag.
5126 Carry = DAG.getNode(SystemZISD::GET_CCMASK, DL, MVT::i32, Carry,
5127 DAG.getConstant(CCValid, DL, MVT::i32),
5128 DAG.getConstant(CCMask, DL, MVT::i32));
5129
5130 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5131 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS, Carry);
5132
5133 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
5134 if (N->getValueType(1) == MVT::i1)
5135 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
5136
5137 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
5138}
5139
5140SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op,
5141 SelectionDAG &DAG) const {
5142 EVT VT = Op.getValueType();
5143 SDLoc DL(Op);
5144 Op = Op.getOperand(0);
5145
5146 if (VT.getScalarSizeInBits() == 128) {
5147 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op);
5148 Op = DAG.getNode(ISD::CTPOP, DL, MVT::v2i64, Op);
5149 SDValue Tmp = DAG.getSplatBuildVector(MVT::v2i64, DL,
5150 DAG.getConstant(0, DL, MVT::i64));
5151 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
5152 return Op;
5153 }
5154
5155 // Handle vector types via VPOPCT.
5156 if (VT.isVector()) {
5157 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op);
5158 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op);
5159 switch (VT.getScalarSizeInBits()) {
5160 case 8:
5161 break;
5162 case 16: {
5163 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
5164 SDValue Shift = DAG.getConstant(8, DL, MVT::i32);
5165 SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift);
5166 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
5167 Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift);
5168 break;
5169 }
5170 case 32: {
5171 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
5172 DAG.getConstant(0, DL, MVT::i32));
5173 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
5174 break;
5175 }
5176 case 64: {
5177 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
5178 DAG.getConstant(0, DL, MVT::i32));
5179 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp);
5180 Tmp = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, Tmp);
5181 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
5182 break;
5183 }
5184 default:
5185 llvm_unreachable("Unexpected type");
5186 }
5187 return Op;
5188 }
5189
5190 // Get the known-zero mask for the operand.
5191 KnownBits Known = DAG.computeKnownBits(Op);
5192 unsigned NumSignificantBits = Known.getMaxValue().getActiveBits();
5193 if (NumSignificantBits == 0)
5194 return DAG.getConstant(0, DL, VT);
5195
5196 // Skip known-zero high parts of the operand.
5197 int64_t OrigBitSize = VT.getSizeInBits();
5198 int64_t BitSize = llvm::bit_ceil(NumSignificantBits);
5199 BitSize = std::min(BitSize, OrigBitSize);
5200
5201 // The POPCNT instruction counts the number of bits in each byte.
5202 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op);
5203 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op);
5204 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
5205
5206 // Add up per-byte counts in a binary tree. All bits of Op at
5207 // position larger than BitSize remain zero throughout.
5208 for (int64_t I = BitSize / 2; I >= 8; I = I / 2) {
5209 SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT));
5210 if (BitSize != OrigBitSize)
5211 Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp,
5212 DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT));
5213 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
5214 }
5215
5216 // Extract overall result from high byte.
5217 if (BitSize > 8)
5218 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5219 DAG.getConstant(BitSize - 8, DL, VT));
5220
5221 return Op;
5222}
5223
5224SDValue SystemZTargetLowering::lowerATOMIC_FENCE(SDValue Op,
5225 SelectionDAG &DAG) const {
5226 SDLoc DL(Op);
5227 AtomicOrdering FenceOrdering =
5228 static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
5229 SyncScope::ID FenceSSID =
5230 static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
5231
5232 // The only fence that needs an instruction is a sequentially-consistent
5233 // cross-thread fence.
5234 if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
5235 FenceSSID == SyncScope::System) {
5236 return SDValue(DAG.getMachineNode(SystemZ::Serialize, DL, MVT::Other,
5237 Op.getOperand(0)),
5238 0);
5239 }
5240
5241 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
5242 return DAG.getNode(ISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
5243}
5244
5245SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
5246 SelectionDAG &DAG) const {
5247 EVT RegVT = Op.getValueType();
5248 if (RegVT.getSizeInBits() == 128)
5249 return lowerATOMIC_LDST_I128(Op, DAG);
5250 return lowerLoadF16(Op, DAG);
5251}
5252
5253SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
5254 SelectionDAG &DAG) const {
5255 auto *Node = cast<AtomicSDNode>(Op.getNode());
5256 if (Node->getMemoryVT().getSizeInBits() == 128)
5257 return lowerATOMIC_LDST_I128(Op, DAG);
5258 return lowerStoreF16(Op, DAG);
5259}
5260
5261SDValue SystemZTargetLowering::lowerATOMIC_LDST_I128(SDValue Op,
5262 SelectionDAG &DAG) const {
5263 auto *Node = cast<AtomicSDNode>(Op.getNode());
5264 assert(
5265 (Node->getMemoryVT() == MVT::i128 || Node->getMemoryVT() == MVT::f128) &&
5266 "Only custom lowering i128 or f128.");
5267 // Use same code to handle both legal and non-legal i128 types.
5269 LowerOperationWrapper(Node, Results, DAG);
5270 return DAG.getMergeValues(Results, SDLoc(Op));
5271}
5272
5273// Prepare for a Compare And Swap for a subword operation. This needs to be
5274// done in memory with 4 bytes at natural alignment.
5276 SDValue &AlignedAddr, SDValue &BitShift,
5277 SDValue &NegBitShift) {
5278 EVT PtrVT = Addr.getValueType();
5279 EVT WideVT = MVT::i32;
5280
5281 // Get the address of the containing word.
5282 AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
5283 DAG.getSignedConstant(-4, DL, PtrVT));
5284
5285 // Get the number of bits that the word must be rotated left in order
5286 // to bring the field to the top bits of a GR32.
5287 BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
5288 DAG.getConstant(3, DL, PtrVT));
5289 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
5290
5291 // Get the complementing shift amount, for rotating a field in the top
5292 // bits back to its proper position.
5293 NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
5294 DAG.getConstant(0, DL, WideVT), BitShift);
5295
5296}
5297
5298// Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation. Lower the first
5299// two into the fullword ATOMIC_LOADW_* operation given by Opcode.
5300SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op,
5301 SelectionDAG &DAG,
5302 unsigned Opcode) const {
5303 auto *Node = cast<AtomicSDNode>(Op.getNode());
5304
5305 // 32-bit operations need no special handling.
5306 EVT NarrowVT = Node->getMemoryVT();
5307 EVT WideVT = MVT::i32;
5308 if (NarrowVT == WideVT)
5309 return Op;
5310
5311 int64_t BitSize = NarrowVT.getSizeInBits();
5312 SDValue ChainIn = Node->getChain();
5313 SDValue Addr = Node->getBasePtr();
5314 SDValue Src2 = Node->getVal();
5315 MachineMemOperand *MMO = Node->getMemOperand();
5316 SDLoc DL(Node);
5317
5318 // Convert atomic subtracts of constants into additions.
5319 if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
5320 if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
5321 Opcode = SystemZISD::ATOMIC_LOADW_ADD;
5322 Src2 = DAG.getSignedConstant(-Const->getSExtValue(), DL,
5323 Src2.getValueType());
5324 }
5325
5326 SDValue AlignedAddr, BitShift, NegBitShift;
5327 getCSAddressAndShifts(Addr, DAG, DL, AlignedAddr, BitShift, NegBitShift);
5328
5329 // Extend the source operand to 32 bits and prepare it for the inner loop.
5330 // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
5331 // operations require the source to be shifted in advance. (This shift
5332 // can be folded if the source is constant.) For AND and NAND, the lower
5333 // bits must be set, while for other opcodes they should be left clear.
5334 if (Opcode != SystemZISD::ATOMIC_SWAPW)
5335 Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
5336 DAG.getConstant(32 - BitSize, DL, WideVT));
5337 if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
5338 Opcode == SystemZISD::ATOMIC_LOADW_NAND)
5339 Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
5340 DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT));
5341
5342 // Construct the ATOMIC_LOADW_* node.
5343 SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
5344 SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
5345 DAG.getConstant(BitSize, DL, WideVT) };
5346 SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
5347 NarrowVT, MMO);
5348
5349 // Rotate the result of the final CS so that the field is in the lower
5350 // bits of a GR32, then truncate it.
5351 SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
5352 DAG.getConstant(BitSize, DL, WideVT));
5353 SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
5354
5355 SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
5356 return DAG.getMergeValues(RetOps, DL);
5357}
5358
5359// Op is an ATOMIC_LOAD_SUB operation. Lower 8- and 16-bit operations into
5360// ATOMIC_LOADW_SUBs and convert 32- and 64-bit operations into additions.
5361SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
5362 SelectionDAG &DAG) const {
5363 auto *Node = cast<AtomicSDNode>(Op.getNode());
5364 EVT MemVT = Node->getMemoryVT();
5365 if (MemVT == MVT::i32 || MemVT == MVT::i64) {
5366 // A full-width operation: negate and use LAA(G).
5367 assert(Op.getValueType() == MemVT && "Mismatched VTs");
5368 assert(Subtarget.hasInterlockedAccess1() &&
5369 "Should have been expanded by AtomicExpand pass.");
5370 SDValue Src2 = Node->getVal();
5371 SDLoc DL(Src2);
5372 SDValue NegSrc2 =
5373 DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT), Src2);
5374 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT,
5375 Node->getChain(), Node->getBasePtr(), NegSrc2,
5376 Node->getMemOperand());
5377 }
5378
5379 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
5380}
5381
5382// Lower 8/16/32/64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS node.
5383SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
5384 SelectionDAG &DAG) const {
5385 auto *Node = cast<AtomicSDNode>(Op.getNode());
5386 SDValue ChainIn = Node->getOperand(0);
5387 SDValue Addr = Node->getOperand(1);
5388 SDValue CmpVal = Node->getOperand(2);
5389 SDValue SwapVal = Node->getOperand(3);
5390 MachineMemOperand *MMO = Node->getMemOperand();
5391 SDLoc DL(Node);
5392
5393 if (Node->getMemoryVT() == MVT::i128) {
5394 // Use same code to handle both legal and non-legal i128 types.
5396 LowerOperationWrapper(Node, Results, DAG);
5397 return DAG.getMergeValues(Results, DL);
5398 }
5399
5400 // We have native support for 32-bit and 64-bit compare and swap, but we
5401 // still need to expand extracting the "success" result from the CC.
5402 EVT NarrowVT = Node->getMemoryVT();
5403 EVT WideVT = NarrowVT == MVT::i64 ? MVT::i64 : MVT::i32;
5404 if (NarrowVT == WideVT) {
5405 SDVTList Tys = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
5406 SDValue Ops[] = { ChainIn, Addr, CmpVal, SwapVal };
5407 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP,
5408 DL, Tys, Ops, NarrowVT, MMO);
5409 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
5411
5412 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), AtomicOp.getValue(0));
5413 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
5414 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
5415 return SDValue();
5416 }
5417
5418 // Convert 8-bit and 16-bit compare and swap to a loop, implemented
5419 // via a fullword ATOMIC_CMP_SWAPW operation.
5420 int64_t BitSize = NarrowVT.getSizeInBits();
5421
5422 SDValue AlignedAddr, BitShift, NegBitShift;
5423 getCSAddressAndShifts(Addr, DAG, DL, AlignedAddr, BitShift, NegBitShift);
5424
5425 // Construct the ATOMIC_CMP_SWAPW node.
5426 SDVTList VTList = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
5427 SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
5428 NegBitShift, DAG.getConstant(BitSize, DL, WideVT) };
5429 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
5430 VTList, Ops, NarrowVT, MMO);
5431 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
5433
5434 // emitAtomicCmpSwapW() will zero extend the result (original value).
5435 SDValue OrigVal = DAG.getNode(ISD::AssertZext, DL, WideVT, AtomicOp.getValue(0),
5436 DAG.getValueType(NarrowVT));
5437 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), OrigVal);
5438 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
5439 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
5440 return SDValue();
5441}
5442
5444SystemZTargetLowering::getTargetMMOFlags(const Instruction &I) const {
5445 // Because of how we convert atomic_load and atomic_store to normal loads and
5446 // stores in the DAG, we need to ensure that the MMOs are marked volatile
5447 // since DAGCombine hasn't been updated to account for atomic, but non
5448 // volatile loads. (See D57601)
5449 if (auto *SI = dyn_cast<StoreInst>(&I))
5450 if (SI->isAtomic())
5452 if (auto *LI = dyn_cast<LoadInst>(&I))
5453 if (LI->isAtomic())
5455 if (auto *AI = dyn_cast<AtomicRMWInst>(&I))
5456 if (AI->isAtomic())
5458 if (auto *AI = dyn_cast<AtomicCmpXchgInst>(&I))
5459 if (AI->isAtomic())
5462}
5463
5464SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
5465 SelectionDAG &DAG) const {
5467 auto *Regs = Subtarget.getSpecialRegisters();
5469 report_fatal_error("Variable-sized stack allocations are not supported "
5470 "in GHC calling convention");
5471 return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
5472 Regs->getStackPointerRegister(), Op.getValueType());
5473}
5474
5475SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
5476 SelectionDAG &DAG) const {
5478 auto *Regs = Subtarget.getSpecialRegisters();
5479 bool StoreBackchain = MF.getSubtarget<SystemZSubtarget>().hasBackChain();
5480
5482 report_fatal_error("Variable-sized stack allocations are not supported "
5483 "in GHC calling convention");
5484
5485 SDValue Chain = Op.getOperand(0);
5486 SDValue NewSP = Op.getOperand(1);
5487 SDValue Backchain;
5488 SDLoc DL(Op);
5489
5490 if (StoreBackchain) {
5491 SDValue OldSP = DAG.getCopyFromReg(
5492 Chain, DL, Regs->getStackPointerRegister(), MVT::i64);
5493 Backchain = DAG.getLoad(MVT::i64, DL, Chain, getBackchainAddress(OldSP, DAG),
5494 MachinePointerInfo());
5495 }
5496
5497 Chain = DAG.getCopyToReg(Chain, DL, Regs->getStackPointerRegister(), NewSP);
5498
5499 if (StoreBackchain)
5500 Chain = DAG.getStore(Chain, DL, Backchain, getBackchainAddress(NewSP, DAG),
5501 MachinePointerInfo());
5502
5503 return Chain;
5504}
5505
5506SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
5507 SelectionDAG &DAG) const {
5508 bool IsData = Op.getConstantOperandVal(4);
5509 if (!IsData)
5510 // Just preserve the chain.
5511 return Op.getOperand(0);
5512
5513 SDLoc DL(Op);
5514 bool IsWrite = Op.getConstantOperandVal(2);
5515 unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
5516 auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
5517 SDValue Ops[] = {Op.getOperand(0), DAG.getTargetConstant(Code, DL, MVT::i32),
5518 Op.getOperand(1)};
5519 return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, DL,
5520 Node->getVTList(), Ops,
5521 Node->getMemoryVT(), Node->getMemOperand());
5522}
5523
5524SDValue
5525SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
5526 SelectionDAG &DAG) const {
5527 unsigned Opcode, CCValid;
5528 if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) {
5529 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
5530 SDNode *Node = emitIntrinsicWithCCAndChain(DAG, Op, Opcode);
5531 SDValue CC = getCCResult(DAG, SDValue(Node, 0));
5532 DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC);
5533 return SDValue();
5534 }
5535
5536 return SDValue();
5537}
5538
5539SDValue
5540SystemZTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
5541 SelectionDAG &DAG) const {
5542 unsigned Opcode, CCValid;
5543 if (isIntrinsicWithCC(Op, Opcode, CCValid)) {
5544 SDNode *Node = emitIntrinsicWithCC(DAG, Op, Opcode);
5545 if (Op->getNumValues() == 1)
5546 return getCCResult(DAG, SDValue(Node, 0));
5547 assert(Op->getNumValues() == 2 && "Expected a CC and non-CC result");
5548 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), Op->getVTList(),
5549 SDValue(Node, 0), getCCResult(DAG, SDValue(Node, 1)));
5550 }
5551
5552 unsigned Id = Op.getConstantOperandVal(0);
5553 switch (Id) {
5554 case Intrinsic::thread_pointer:
5555 return lowerThreadPointer(SDLoc(Op), DAG);
5556
5557 case Intrinsic::s390_vpdi:
5558 return DAG.getNode(SystemZISD::PERMUTE_DWORDS, SDLoc(Op), Op.getValueType(),
5559 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5560
5561 case Intrinsic::s390_vperm:
5562 return DAG.getNode(SystemZISD::PERMUTE, SDLoc(Op), Op.getValueType(),
5563 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5564
5565 case Intrinsic::s390_vuphb:
5566 case Intrinsic::s390_vuphh:
5567 case Intrinsic::s390_vuphf:
5568 case Intrinsic::s390_vuphg:
5569 return DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(Op), Op.getValueType(),
5570 Op.getOperand(1));
5571
5572 case Intrinsic::s390_vuplhb:
5573 case Intrinsic::s390_vuplhh:
5574 case Intrinsic::s390_vuplhf:
5575 case Intrinsic::s390_vuplhg:
5576 return DAG.getNode(SystemZISD::UNPACKL_HIGH, SDLoc(Op), Op.getValueType(),
5577 Op.getOperand(1));
5578
5579 case Intrinsic::s390_vuplb:
5580 case Intrinsic::s390_vuplhw:
5581 case Intrinsic::s390_vuplf:
5582 case Intrinsic::s390_vuplg:
5583 return DAG.getNode(SystemZISD::UNPACK_LOW, SDLoc(Op), Op.getValueType(),
5584 Op.getOperand(1));
5585
5586 case Intrinsic::s390_vupllb:
5587 case Intrinsic::s390_vupllh:
5588 case Intrinsic::s390_vupllf:
5589 case Intrinsic::s390_vupllg:
5590 return DAG.getNode(SystemZISD::UNPACKL_LOW, SDLoc(Op), Op.getValueType(),
5591 Op.getOperand(1));
5592
5593 case Intrinsic::s390_vsumb:
5594 case Intrinsic::s390_vsumh:
5595 case Intrinsic::s390_vsumgh:
5596 case Intrinsic::s390_vsumgf:
5597 case Intrinsic::s390_vsumqf:
5598 case Intrinsic::s390_vsumqg:
5599 return DAG.getNode(SystemZISD::VSUM, SDLoc(Op), Op.getValueType(),
5600 Op.getOperand(1), Op.getOperand(2));
5601
5602 case Intrinsic::s390_vaq:
5603 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5604 Op.getOperand(1), Op.getOperand(2));
5605 case Intrinsic::s390_vaccb:
5606 case Intrinsic::s390_vacch:
5607 case Intrinsic::s390_vaccf:
5608 case Intrinsic::s390_vaccg:
5609 case Intrinsic::s390_vaccq:
5610 return DAG.getNode(SystemZISD::VACC, SDLoc(Op), Op.getValueType(),
5611 Op.getOperand(1), Op.getOperand(2));
5612 case Intrinsic::s390_vacq:
5613 return DAG.getNode(SystemZISD::VAC, SDLoc(Op), Op.getValueType(),
5614 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5615 case Intrinsic::s390_vacccq:
5616 return DAG.getNode(SystemZISD::VACCC, SDLoc(Op), Op.getValueType(),
5617 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5618
5619 case Intrinsic::s390_vsq:
5620 return DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(),
5621 Op.getOperand(1), Op.getOperand(2));
5622 case Intrinsic::s390_vscbib:
5623 case Intrinsic::s390_vscbih:
5624 case Intrinsic::s390_vscbif:
5625 case Intrinsic::s390_vscbig:
5626 case Intrinsic::s390_vscbiq:
5627 return DAG.getNode(SystemZISD::VSCBI, SDLoc(Op), Op.getValueType(),
5628 Op.getOperand(1), Op.getOperand(2));
5629 case Intrinsic::s390_vsbiq:
5630 return DAG.getNode(SystemZISD::VSBI, SDLoc(Op), Op.getValueType(),
5631 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5632 case Intrinsic::s390_vsbcbiq:
5633 return DAG.getNode(SystemZISD::VSBCBI, SDLoc(Op), Op.getValueType(),
5634 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5635
5636 case Intrinsic::s390_vmhb:
5637 case Intrinsic::s390_vmhh:
5638 case Intrinsic::s390_vmhf:
5639 case Intrinsic::s390_vmhg:
5640 case Intrinsic::s390_vmhq:
5641 return DAG.getNode(ISD::MULHS, SDLoc(Op), Op.getValueType(),
5642 Op.getOperand(1), Op.getOperand(2));
5643 case Intrinsic::s390_vmlhb:
5644 case Intrinsic::s390_vmlhh:
5645 case Intrinsic::s390_vmlhf:
5646 case Intrinsic::s390_vmlhg:
5647 case Intrinsic::s390_vmlhq:
5648 return DAG.getNode(ISD::MULHU, SDLoc(Op), Op.getValueType(),
5649 Op.getOperand(1), Op.getOperand(2));
5650
5651 case Intrinsic::s390_vmahb:
5652 case Intrinsic::s390_vmahh:
5653 case Intrinsic::s390_vmahf:
5654 case Intrinsic::s390_vmahg:
5655 case Intrinsic::s390_vmahq:
5656 return DAG.getNode(SystemZISD::VMAH, SDLoc(Op), Op.getValueType(),
5657 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5658 case Intrinsic::s390_vmalhb:
5659 case Intrinsic::s390_vmalhh:
5660 case Intrinsic::s390_vmalhf:
5661 case Intrinsic::s390_vmalhg:
5662 case Intrinsic::s390_vmalhq:
5663 return DAG.getNode(SystemZISD::VMALH, SDLoc(Op), Op.getValueType(),
5664 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5665
5666 case Intrinsic::s390_vmeb:
5667 case Intrinsic::s390_vmeh:
5668 case Intrinsic::s390_vmef:
5669 case Intrinsic::s390_vmeg:
5670 return DAG.getNode(SystemZISD::VME, SDLoc(Op), Op.getValueType(),
5671 Op.getOperand(1), Op.getOperand(2));
5672 case Intrinsic::s390_vmleb:
5673 case Intrinsic::s390_vmleh:
5674 case Intrinsic::s390_vmlef:
5675 case Intrinsic::s390_vmleg:
5676 return DAG.getNode(SystemZISD::VMLE, SDLoc(Op), Op.getValueType(),
5677 Op.getOperand(1), Op.getOperand(2));
5678 case Intrinsic::s390_vmob:
5679 case Intrinsic::s390_vmoh:
5680 case Intrinsic::s390_vmof:
5681 case Intrinsic::s390_vmog:
5682 return DAG.getNode(SystemZISD::VMO, SDLoc(Op), Op.getValueType(),
5683 Op.getOperand(1), Op.getOperand(2));
5684 case Intrinsic::s390_vmlob:
5685 case Intrinsic::s390_vmloh:
5686 case Intrinsic::s390_vmlof:
5687 case Intrinsic::s390_vmlog:
5688 return DAG.getNode(SystemZISD::VMLO, SDLoc(Op), Op.getValueType(),
5689 Op.getOperand(1), Op.getOperand(2));
5690
5691 case Intrinsic::s390_vmaeb:
5692 case Intrinsic::s390_vmaeh:
5693 case Intrinsic::s390_vmaef:
5694 case Intrinsic::s390_vmaeg:
5695 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5696 DAG.getNode(SystemZISD::VME, SDLoc(Op), Op.getValueType(),
5697 Op.getOperand(1), Op.getOperand(2)),
5698 Op.getOperand(3));
5699 case Intrinsic::s390_vmaleb:
5700 case Intrinsic::s390_vmaleh:
5701 case Intrinsic::s390_vmalef:
5702 case Intrinsic::s390_vmaleg:
5703 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5704 DAG.getNode(SystemZISD::VMLE, SDLoc(Op), Op.getValueType(),
5705 Op.getOperand(1), Op.getOperand(2)),
5706 Op.getOperand(3));
5707 case Intrinsic::s390_vmaob:
5708 case Intrinsic::s390_vmaoh:
5709 case Intrinsic::s390_vmaof:
5710 case Intrinsic::s390_vmaog:
5711 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5712 DAG.getNode(SystemZISD::VMO, SDLoc(Op), Op.getValueType(),
5713 Op.getOperand(1), Op.getOperand(2)),
5714 Op.getOperand(3));
5715 case Intrinsic::s390_vmalob:
5716 case Intrinsic::s390_vmaloh:
5717 case Intrinsic::s390_vmalof:
5718 case Intrinsic::s390_vmalog:
5719 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5720 DAG.getNode(SystemZISD::VMLO, SDLoc(Op), Op.getValueType(),
5721 Op.getOperand(1), Op.getOperand(2)),
5722 Op.getOperand(3));
5723 }
5724
5725 return SDValue();
5726}
5727
5728namespace {
5729// Says that SystemZISD operation Opcode can be used to perform the equivalent
5730// of a VPERM with permute vector Bytes. If Opcode takes three operands,
5731// Operand is the constant third operand, otherwise it is the number of
5732// bytes in each element of the result.
5733struct Permute {
5734 unsigned Opcode;
5735 unsigned Operand;
5736 unsigned char Bytes[SystemZ::VectorBytes];
5737};
5738}
5739
5740static const Permute PermuteForms[] = {
5741 // VMRHG
5742 { SystemZISD::MERGE_HIGH, 8,
5743 { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } },
5744 // VMRHF
5745 { SystemZISD::MERGE_HIGH, 4,
5746 { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } },
5747 // VMRHH
5748 { SystemZISD::MERGE_HIGH, 2,
5749 { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } },
5750 // VMRHB
5751 { SystemZISD::MERGE_HIGH, 1,
5752 { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } },
5753 // VMRLG
5754 { SystemZISD::MERGE_LOW, 8,
5755 { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } },
5756 // VMRLF
5757 { SystemZISD::MERGE_LOW, 4,
5758 { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
5759 // VMRLH
5760 { SystemZISD::MERGE_LOW, 2,
5761 { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
5762 // VMRLB
5763 { SystemZISD::MERGE_LOW, 1,
5764 { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
5765 // VPKG
5766 { SystemZISD::PACK, 4,
5767 { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } },
5768 // VPKF
5769 { SystemZISD::PACK, 2,
5770 { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
5771 // VPKH
5772 { SystemZISD::PACK, 1,
5773 { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
5774 // VPDI V1, V2, 4 (low half of V1, high half of V2)
5775 { SystemZISD::PERMUTE_DWORDS, 4,
5776 { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } },
5777 // VPDI V1, V2, 1 (high half of V1, low half of V2)
5778 { SystemZISD::PERMUTE_DWORDS, 1,
5779 { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } }
5780};
5781
5782// Called after matching a vector shuffle against a particular pattern.
5783// Both the original shuffle and the pattern have two vector operands.
5784// OpNos[0] is the operand of the original shuffle that should be used for
5785// operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything.
5786// OpNos[1] is the same for operand 1 of the pattern. Resolve these -1s and
5787// set OpNo0 and OpNo1 to the shuffle operands that should actually be used
5788// for operands 0 and 1 of the pattern.
5789static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) {
5790 if (OpNos[0] < 0) {
5791 if (OpNos[1] < 0)
5792 return false;
5793 OpNo0 = OpNo1 = OpNos[1];
5794 } else if (OpNos[1] < 0) {
5795 OpNo0 = OpNo1 = OpNos[0];
5796 } else {
5797 OpNo0 = OpNos[0];
5798 OpNo1 = OpNos[1];
5799 }
5800 return true;
5801}
5802
5803// Bytes is a VPERM-like permute vector, except that -1 is used for
5804// undefined bytes. Return true if the VPERM can be implemented using P.
5805// When returning true set OpNo0 to the VPERM operand that should be
5806// used for operand 0 of P and likewise OpNo1 for operand 1 of P.
5807//
5808// For example, if swapping the VPERM operands allows P to match, OpNo0
5809// will be 1 and OpNo1 will be 0. If instead Bytes only refers to one
5810// operand, but rewriting it to use two duplicated operands allows it to
5811// match P, then OpNo0 and OpNo1 will be the same.
5812static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P,
5813 unsigned &OpNo0, unsigned &OpNo1) {
5814 int OpNos[] = { -1, -1 };
5815 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
5816 int Elt = Bytes[I];
5817 if (Elt >= 0) {
5818 // Make sure that the two permute vectors use the same suboperand
5819 // byte number. Only the operand numbers (the high bits) are
5820 // allowed to differ.
5821 if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1))
5822 return false;
5823 int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes;
5824 int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes;
5825 // Make sure that the operand mappings are consistent with previous
5826 // elements.
5827 if (OpNos[ModelOpNo] == 1 - RealOpNo)
5828 return false;
5829 OpNos[ModelOpNo] = RealOpNo;
5830 }
5831 }
5832 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
5833}
5834
5835// As above, but search for a matching permute.
5836static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes,
5837 unsigned &OpNo0, unsigned &OpNo1) {
5838 for (auto &P : PermuteForms)
5839 if (matchPermute(Bytes, P, OpNo0, OpNo1))
5840 return &P;
5841 return nullptr;
5842}
5843
5844// Bytes is a VPERM-like permute vector, except that -1 is used for
5845// undefined bytes. This permute is an operand of an outer permute.
5846// See whether redistributing the -1 bytes gives a shuffle that can be
5847// implemented using P. If so, set Transform to a VPERM-like permute vector
5848// that, when applied to the result of P, gives the original permute in Bytes.
5850 const Permute &P,
5851 SmallVectorImpl<int> &Transform) {
5852 unsigned To = 0;
5853 for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) {
5854 int Elt = Bytes[From];
5855 if (Elt < 0)
5856 // Byte number From of the result is undefined.
5857 Transform[From] = -1;
5858 else {
5859 while (P.Bytes[To] != Elt) {
5860 To += 1;
5861 if (To == SystemZ::VectorBytes)
5862 return false;
5863 }
5864 Transform[From] = To;
5865 }
5866 }
5867 return true;
5868}
5869
5870// As above, but search for a matching permute.
5871static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes,
5872 SmallVectorImpl<int> &Transform) {
5873 for (auto &P : PermuteForms)
5874 if (matchDoublePermute(Bytes, P, Transform))
5875 return &P;
5876 return nullptr;
5877}
5878
5879// Convert the mask of the given shuffle op into a byte-level mask,
5880// as if it had type vNi8.
5881static bool getVPermMask(SDValue ShuffleOp,
5882 SmallVectorImpl<int> &Bytes) {
5883 EVT VT = ShuffleOp.getValueType();
5884 unsigned NumElements = VT.getVectorNumElements();
5885 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
5886
5887 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(ShuffleOp)) {
5888 Bytes.resize(NumElements * BytesPerElement, -1);
5889 for (unsigned I = 0; I < NumElements; ++I) {
5890 int Index = VSN->getMaskElt(I);
5891 if (Index >= 0)
5892 for (unsigned J = 0; J < BytesPerElement; ++J)
5893 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
5894 }
5895 return true;
5896 }
5897 if (SystemZISD::SPLAT == ShuffleOp.getOpcode() &&
5898 isa<ConstantSDNode>(ShuffleOp.getOperand(1))) {
5899 unsigned Index = ShuffleOp.getConstantOperandVal(1);
5900 Bytes.resize(NumElements * BytesPerElement, -1);
5901 for (unsigned I = 0; I < NumElements; ++I)
5902 for (unsigned J = 0; J < BytesPerElement; ++J)
5903 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
5904 return true;
5905 }
5906 return false;
5907}
5908
5909// Bytes is a VPERM-like permute vector, except that -1 is used for
5910// undefined bytes. See whether bytes [Start, Start + BytesPerElement) of
5911// the result come from a contiguous sequence of bytes from one input.
5912// Set Base to the selector for the first byte if so.
5913static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start,
5914 unsigned BytesPerElement, int &Base) {
5915 Base = -1;
5916 for (unsigned I = 0; I < BytesPerElement; ++I) {
5917 if (Bytes[Start + I] >= 0) {
5918 unsigned Elem = Bytes[Start + I];
5919 if (Base < 0) {
5920 Base = Elem - I;
5921 // Make sure the bytes would come from one input operand.
5922 if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size())
5923 return false;
5924 } else if (unsigned(Base) != Elem - I)
5925 return false;
5926 }
5927 }
5928 return true;
5929}
5930
5931// Bytes is a VPERM-like permute vector, except that -1 is used for
5932// undefined bytes. Return true if it can be performed using VSLDB.
5933// When returning true, set StartIndex to the shift amount and OpNo0
5934// and OpNo1 to the VPERM operands that should be used as the first
5935// and second shift operand respectively.
5937 unsigned &StartIndex, unsigned &OpNo0,
5938 unsigned &OpNo1) {
5939 int OpNos[] = { -1, -1 };
5940 int Shift = -1;
5941 for (unsigned I = 0; I < 16; ++I) {
5942 int Index = Bytes[I];
5943 if (Index >= 0) {
5944 int ExpectedShift = (Index - I) % SystemZ::VectorBytes;
5945 int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes;
5946 int RealOpNo = unsigned(Index) / SystemZ::VectorBytes;
5947 if (Shift < 0)
5948 Shift = ExpectedShift;
5949 else if (Shift != ExpectedShift)
5950 return false;
5951 // Make sure that the operand mappings are consistent with previous
5952 // elements.
5953 if (OpNos[ModelOpNo] == 1 - RealOpNo)
5954 return false;
5955 OpNos[ModelOpNo] = RealOpNo;
5956 }
5957 }
5958 StartIndex = Shift;
5959 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
5960}
5961
5962// Create a node that performs P on operands Op0 and Op1, casting the
5963// operands to the appropriate type. The type of the result is determined by P.
5965 const Permute &P, SDValue Op0, SDValue Op1) {
5966 // VPDI (PERMUTE_DWORDS) always operates on v2i64s. The input
5967 // elements of a PACK are twice as wide as the outputs.
5968 unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 :
5969 P.Opcode == SystemZISD::PACK ? P.Operand * 2 :
5970 P.Operand);
5971 // Cast both operands to the appropriate type.
5972 MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8),
5973 SystemZ::VectorBytes / InBytes);
5974 Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0);
5975 Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1);
5976 SDValue Op;
5977 if (P.Opcode == SystemZISD::PERMUTE_DWORDS) {
5978 SDValue Op2 = DAG.getTargetConstant(P.Operand, DL, MVT::i32);
5979 Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2);
5980 } else if (P.Opcode == SystemZISD::PACK) {
5981 MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8),
5982 SystemZ::VectorBytes / P.Operand);
5983 Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1);
5984 } else {
5985 Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1);
5986 }
5987 return Op;
5988}
5989
5990static bool isZeroVector(SDValue N) {
5991 if (N->getOpcode() == ISD::BITCAST)
5992 N = N->getOperand(0);
5993 if (N->getOpcode() == ISD::SPLAT_VECTOR)
5994 if (auto *Op = dyn_cast<ConstantSDNode>(N->getOperand(0)))
5995 return Op->getZExtValue() == 0;
5996 return ISD::isBuildVectorAllZeros(N.getNode());
5997}
5998
5999// Return the index of the zero/undef vector, or UINT32_MAX if not found.
6000static uint32_t findZeroVectorIdx(SDValue *Ops, unsigned Num) {
6001 for (unsigned I = 0; I < Num ; I++)
6002 if (isZeroVector(Ops[I]))
6003 return I;
6004 return UINT32_MAX;
6005}
6006
6007// Bytes is a VPERM-like permute vector, except that -1 is used for
6008// undefined bytes. Implement it on operands Ops[0] and Ops[1] using
6009// VSLDB or VPERM.
6011 SDValue *Ops,
6012 const SmallVectorImpl<int> &Bytes) {
6013 for (unsigned I = 0; I < 2; ++I)
6014 Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]);
6015
6016 // First see whether VSLDB can be used.
6017 unsigned StartIndex, OpNo0, OpNo1;
6018 if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1))
6019 return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0],
6020 Ops[OpNo1],
6021 DAG.getTargetConstant(StartIndex, DL, MVT::i32));
6022
6023 // Fall back on VPERM. Construct an SDNode for the permute vector. Try to
6024 // eliminate a zero vector by reusing any zero index in the permute vector.
6025 unsigned ZeroVecIdx = findZeroVectorIdx(&Ops[0], 2);
6026 if (ZeroVecIdx != UINT32_MAX) {
6027 bool MaskFirst = true;
6028 int ZeroIdx = -1;
6029 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
6030 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
6031 unsigned Byte = unsigned(Bytes[I]) % SystemZ::VectorBytes;
6032 if (OpNo == ZeroVecIdx && I == 0) {
6033 // If the first byte is zero, use mask as first operand.
6034 ZeroIdx = 0;
6035 break;
6036 }
6037 if (OpNo != ZeroVecIdx && Byte == 0) {
6038 // If mask contains a zero, use it by placing that vector first.
6039 ZeroIdx = I + SystemZ::VectorBytes;
6040 MaskFirst = false;
6041 break;
6042 }
6043 }
6044 if (ZeroIdx != -1) {
6045 SDValue IndexNodes[SystemZ::VectorBytes];
6046 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
6047 if (Bytes[I] >= 0) {
6048 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
6049 unsigned Byte = unsigned(Bytes[I]) % SystemZ::VectorBytes;
6050 if (OpNo == ZeroVecIdx)
6051 IndexNodes[I] = DAG.getConstant(ZeroIdx, DL, MVT::i32);
6052 else {
6053 unsigned BIdx = MaskFirst ? Byte + SystemZ::VectorBytes : Byte;
6054 IndexNodes[I] = DAG.getConstant(BIdx, DL, MVT::i32);
6055 }
6056 } else
6057 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
6058 }
6059 SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
6060 SDValue Src = ZeroVecIdx == 0 ? Ops[1] : Ops[0];
6061 if (MaskFirst)
6062 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Mask, Src,
6063 Mask);
6064 else
6065 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Src, Mask,
6066 Mask);
6067 }
6068 }
6069
6070 SDValue IndexNodes[SystemZ::VectorBytes];
6071 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
6072 if (Bytes[I] >= 0)
6073 IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32);
6074 else
6075 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
6076 SDValue Op2 = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
6077 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0],
6078 (!Ops[1].isUndef() ? Ops[1] : Ops[0]), Op2);
6079}
6080
6081namespace {
6082// Describes a general N-operand vector shuffle.
6083struct GeneralShuffle {
6084 GeneralShuffle(EVT vt)
6085 : VT(vt), UnpackFromEltSize(UINT_MAX), UnpackLow(false) {}
6086 void addUndef();
6087 bool add(SDValue, unsigned);
6088 SDValue getNode(SelectionDAG &, const SDLoc &);
6089 void tryPrepareForUnpack();
6090 bool unpackWasPrepared() { return UnpackFromEltSize <= 4; }
6091 SDValue insertUnpackIfPrepared(SelectionDAG &DAG, const SDLoc &DL, SDValue Op);
6092
6093 // The operands of the shuffle.
6095
6096 // Index I is -1 if byte I of the result is undefined. Otherwise the
6097 // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand
6098 // Bytes[I] / SystemZ::VectorBytes.
6100
6101 // The type of the shuffle result.
6102 EVT VT;
6103
6104 // Holds a value of 1, 2 or 4 if a final unpack has been prepared for.
6105 unsigned UnpackFromEltSize;
6106 // True if the final unpack uses the low half.
6107 bool UnpackLow;
6108};
6109} // namespace
6110
6111// Add an extra undefined element to the shuffle.
6112void GeneralShuffle::addUndef() {
6113 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
6114 for (unsigned I = 0; I < BytesPerElement; ++I)
6115 Bytes.push_back(-1);
6116}
6117
6118// Add an extra element to the shuffle, taking it from element Elem of Op.
6119// A null Op indicates a vector input whose value will be calculated later;
6120// there is at most one such input per shuffle and it always has the same
6121// type as the result. Aborts and returns false if the source vector elements
6122// of an EXTRACT_VECTOR_ELT are smaller than the destination elements. Per
6123// LLVM they become implicitly extended, but this is rare and not optimized.
6124bool GeneralShuffle::add(SDValue Op, unsigned Elem) {
6125 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
6126
6127 // The source vector can have wider elements than the result,
6128 // either through an explicit TRUNCATE or because of type legalization.
6129 // We want the least significant part.
6130 EVT FromVT = Op.getNode() ? Op.getValueType() : VT;
6131 unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize();
6132
6133 // Return false if the source elements are smaller than their destination
6134 // elements.
6135 if (FromBytesPerElement < BytesPerElement)
6136 return false;
6137
6138 unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes +
6139 (FromBytesPerElement - BytesPerElement));
6140
6141 // Look through things like shuffles and bitcasts.
6142 while (Op.getNode()) {
6143 if (Op.getOpcode() == ISD::BITCAST)
6144 Op = Op.getOperand(0);
6145 else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) {
6146 // See whether the bytes we need come from a contiguous part of one
6147 // operand.
6149 if (!getVPermMask(Op, OpBytes))
6150 break;
6151 int NewByte;
6152 if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte))
6153 break;
6154 if (NewByte < 0) {
6155 addUndef();
6156 return true;
6157 }
6158 Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes);
6159 Byte = unsigned(NewByte) % SystemZ::VectorBytes;
6160 } else if (Op.isUndef()) {
6161 addUndef();
6162 return true;
6163 } else
6164 break;
6165 }
6166
6167 // Make sure that the source of the extraction is in Ops.
6168 unsigned OpNo = 0;
6169 for (; OpNo < Ops.size(); ++OpNo)
6170 if (Ops[OpNo] == Op)
6171 break;
6172 if (OpNo == Ops.size())
6173 Ops.push_back(Op);
6174
6175 // Add the element to Bytes.
6176 unsigned Base = OpNo * SystemZ::VectorBytes + Byte;
6177 for (unsigned I = 0; I < BytesPerElement; ++I)
6178 Bytes.push_back(Base + I);
6179
6180 return true;
6181}
6182
6183// Return SDNodes for the completed shuffle.
6184SDValue GeneralShuffle::getNode(SelectionDAG &DAG, const SDLoc &DL) {
6185 assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector");
6186
6187 if (Ops.size() == 0)
6188 return DAG.getUNDEF(VT);
6189
6190 // Use a single unpack if possible as the last operation.
6191 tryPrepareForUnpack();
6192
6193 // Make sure that there are at least two shuffle operands.
6194 if (Ops.size() == 1)
6195 Ops.push_back(DAG.getUNDEF(MVT::v16i8));
6196
6197 // Create a tree of shuffles, deferring root node until after the loop.
6198 // Try to redistribute the undefined elements of non-root nodes so that
6199 // the non-root shuffles match something like a pack or merge, then adjust
6200 // the parent node's permute vector to compensate for the new order.
6201 // Among other things, this copes with vectors like <2 x i16> that were
6202 // padded with undefined elements during type legalization.
6203 //
6204 // In the best case this redistribution will lead to the whole tree
6205 // using packs and merges. It should rarely be a loss in other cases.
6206 unsigned Stride = 1;
6207 for (; Stride * 2 < Ops.size(); Stride *= 2) {
6208 for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) {
6209 SDValue SubOps[] = { Ops[I], Ops[I + Stride] };
6210
6211 // Create a mask for just these two operands.
6213 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
6214 unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes;
6215 unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes;
6216 if (OpNo == I)
6217 NewBytes[J] = Byte;
6218 else if (OpNo == I + Stride)
6219 NewBytes[J] = SystemZ::VectorBytes + Byte;
6220 else
6221 NewBytes[J] = -1;
6222 }
6223 // See if it would be better to reorganize NewMask to avoid using VPERM.
6225 if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) {
6226 Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]);
6227 // Applying NewBytesMap to Ops[I] gets back to NewBytes.
6228 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
6229 if (NewBytes[J] >= 0) {
6230 assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
6231 "Invalid double permute");
6232 Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J];
6233 } else
6234 assert(NewBytesMap[J] < 0 && "Invalid double permute");
6235 }
6236 } else {
6237 // Just use NewBytes on the operands.
6238 Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes);
6239 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J)
6240 if (NewBytes[J] >= 0)
6241 Bytes[J] = I * SystemZ::VectorBytes + J;
6242 }
6243 }
6244 }
6245
6246 // Now we just have 2 inputs. Put the second operand in Ops[1].
6247 if (Stride > 1) {
6248 Ops[1] = Ops[Stride];
6249 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
6250 if (Bytes[I] >= int(SystemZ::VectorBytes))
6251 Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes;
6252 }
6253
6254 // Look for an instruction that can do the permute without resorting
6255 // to VPERM.
6256 unsigned OpNo0, OpNo1;
6257 SDValue Op;
6258 if (unpackWasPrepared() && Ops[1].isUndef())
6259 Op = Ops[0];
6260 else if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1))
6261 Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]);
6262 else
6263 Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes);
6264
6265 Op = insertUnpackIfPrepared(DAG, DL, Op);
6266
6267 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
6268}
6269
6270#ifndef NDEBUG
6271static void dumpBytes(const SmallVectorImpl<int> &Bytes, std::string Msg) {
6272 dbgs() << Msg.c_str() << " { ";
6273 for (unsigned I = 0; I < Bytes.size(); I++)
6274 dbgs() << Bytes[I] << " ";
6275 dbgs() << "}\n";
6276}
6277#endif
6278
6279// If the Bytes vector matches an unpack operation, prepare to do the unpack
6280// after all else by removing the zero vector and the effect of the unpack on
6281// Bytes.
6282void GeneralShuffle::tryPrepareForUnpack() {
6283 uint32_t ZeroVecOpNo = findZeroVectorIdx(&Ops[0], Ops.size());
6284 if (ZeroVecOpNo == UINT32_MAX || Ops.size() == 1)
6285 return;
6286
6287 // Only do this if removing the zero vector reduces the depth, otherwise
6288 // the critical path will increase with the final unpack.
6289 if (Ops.size() > 2 &&
6290 Log2_32_Ceil(Ops.size()) == Log2_32_Ceil(Ops.size() - 1))
6291 return;
6292
6293 // Find an unpack that would allow removing the zero vector from Ops.
6294 UnpackFromEltSize = 1;
6295 for (; UnpackFromEltSize <= 4; UnpackFromEltSize *= 2) {
6296 bool MatchUnpack = true;
6298 for (unsigned Elt = 0; Elt < SystemZ::VectorBytes; Elt++) {
6299 unsigned ToEltSize = UnpackFromEltSize * 2;
6300 bool IsZextByte = (Elt % ToEltSize) < UnpackFromEltSize;
6301 if (!IsZextByte)
6302 SrcBytes.push_back(Bytes[Elt]);
6303 if (Bytes[Elt] != -1) {
6304 unsigned OpNo = unsigned(Bytes[Elt]) / SystemZ::VectorBytes;
6305 if (IsZextByte != (OpNo == ZeroVecOpNo)) {
6306 MatchUnpack = false;
6307 break;
6308 }
6309 }
6310 }
6311 if (MatchUnpack) {
6312 if (Ops.size() == 2) {
6313 // Don't use unpack if a single source operand needs rearrangement.
6314 bool CanUseUnpackLow = true, CanUseUnpackHigh = true;
6315 for (unsigned i = 0; i < SystemZ::VectorBytes / 2; i++) {
6316 if (SrcBytes[i] == -1)
6317 continue;
6318 if (SrcBytes[i] % 16 != int(i))
6319 CanUseUnpackHigh = false;
6320 if (SrcBytes[i] % 16 != int(i + SystemZ::VectorBytes / 2))
6321 CanUseUnpackLow = false;
6322 if (!CanUseUnpackLow && !CanUseUnpackHigh) {
6323 UnpackFromEltSize = UINT_MAX;
6324 return;
6325 }
6326 }
6327 if (!CanUseUnpackHigh)
6328 UnpackLow = true;
6329 }
6330 break;
6331 }
6332 }
6333 if (UnpackFromEltSize > 4)
6334 return;
6335
6336 LLVM_DEBUG(dbgs() << "Preparing for final unpack of element size "
6337 << UnpackFromEltSize << ". Zero vector is Op#" << ZeroVecOpNo
6338 << ".\n";
6339 dumpBytes(Bytes, "Original Bytes vector:"););
6340
6341 // Apply the unpack in reverse to the Bytes array.
6342 unsigned B = 0;
6343 if (UnpackLow) {
6344 while (B < SystemZ::VectorBytes / 2)
6345 Bytes[B++] = -1;
6346 }
6347 for (unsigned Elt = 0; Elt < SystemZ::VectorBytes;) {
6348 Elt += UnpackFromEltSize;
6349 for (unsigned i = 0; i < UnpackFromEltSize; i++, Elt++, B++)
6350 Bytes[B] = Bytes[Elt];
6351 }
6352 if (!UnpackLow) {
6353 while (B < SystemZ::VectorBytes)
6354 Bytes[B++] = -1;
6355 }
6356
6357 // Remove the zero vector from Ops
6358 Ops.erase(&Ops[ZeroVecOpNo]);
6359 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
6360 if (Bytes[I] >= 0) {
6361 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
6362 if (OpNo > ZeroVecOpNo)
6363 Bytes[I] -= SystemZ::VectorBytes;
6364 }
6365
6366 LLVM_DEBUG(dumpBytes(Bytes, "Resulting Bytes vector, zero vector removed:");
6367 dbgs() << "\n";);
6368}
6369
6370SDValue GeneralShuffle::insertUnpackIfPrepared(SelectionDAG &DAG,
6371 const SDLoc &DL,
6372 SDValue Op) {
6373 if (!unpackWasPrepared())
6374 return Op;
6375 unsigned InBits = UnpackFromEltSize * 8;
6376 EVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBits),
6377 SystemZ::VectorBits / InBits);
6378 SDValue PackedOp = DAG.getNode(ISD::BITCAST, DL, InVT, Op);
6379 unsigned OutBits = InBits * 2;
6380 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(OutBits),
6381 SystemZ::VectorBits / OutBits);
6382 return DAG.getNode(UnpackLow ? SystemZISD::UNPACKL_LOW
6383 : SystemZISD::UNPACKL_HIGH,
6384 DL, OutVT, PackedOp);
6385}
6386
6387// Return true if the given BUILD_VECTOR is a scalar-to-vector conversion.
6389 for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I)
6390 if (!Op.getOperand(I).isUndef())
6391 return false;
6392 return true;
6393}
6394
6395// Return a vector of type VT that contains Value in the first element.
6396// The other elements don't matter.
6398 SDValue Value) {
6399 // If we have a constant, replicate it to all elements and let the
6400 // BUILD_VECTOR lowering take care of it.
6401 if (Value.getOpcode() == ISD::Constant ||
6402 Value.getOpcode() == ISD::ConstantFP) {
6404 return DAG.getBuildVector(VT, DL, Ops);
6405 }
6406 if (Value.isUndef())
6407 return DAG.getUNDEF(VT);
6408 return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
6409}
6410
6411// Return a vector of type VT in which Op0 is in element 0 and Op1 is in
6412// element 1. Used for cases in which replication is cheap.
6414 SDValue Op0, SDValue Op1) {
6415 if (Op0.isUndef()) {
6416 if (Op1.isUndef())
6417 return DAG.getUNDEF(VT);
6418 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1);
6419 }
6420 if (Op1.isUndef())
6421 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0);
6422 return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT,
6423 buildScalarToVector(DAG, DL, VT, Op0),
6424 buildScalarToVector(DAG, DL, VT, Op1));
6425}
6426
6427// Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64
6428// vector for them.
6430 SDValue Op1) {
6431 if (Op0.isUndef() && Op1.isUndef())
6432 return DAG.getUNDEF(MVT::v2i64);
6433 // If one of the two inputs is undefined then replicate the other one,
6434 // in order to avoid using another register unnecessarily.
6435 if (Op0.isUndef())
6436 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
6437 else if (Op1.isUndef())
6438 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
6439 else {
6440 Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
6441 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
6442 }
6443 return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1);
6444}
6445
6446// If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually
6447// better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for
6448// the non-EXTRACT_VECTOR_ELT elements. See if the given BUILD_VECTOR
6449// would benefit from this representation and return it if so.
6451 BuildVectorSDNode *BVN) {
6452 EVT VT = BVN->getValueType(0);
6453 unsigned NumElements = VT.getVectorNumElements();
6454
6455 // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation
6456 // on byte vectors. If there are non-EXTRACT_VECTOR_ELT elements that still
6457 // need a BUILD_VECTOR, add an additional placeholder operand for that
6458 // BUILD_VECTOR and store its operands in ResidueOps.
6459 GeneralShuffle GS(VT);
6461 bool FoundOne = false;
6462 for (unsigned I = 0; I < NumElements; ++I) {
6463 SDValue Op = BVN->getOperand(I);
6464 if (Op.getOpcode() == ISD::TRUNCATE)
6465 Op = Op.getOperand(0);
6466 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6467 Op.getOperand(1).getOpcode() == ISD::Constant) {
6468 unsigned Elem = Op.getConstantOperandVal(1);
6469 if (!GS.add(Op.getOperand(0), Elem))
6470 return SDValue();
6471 FoundOne = true;
6472 } else if (Op.isUndef()) {
6473 GS.addUndef();
6474 } else {
6475 if (!GS.add(SDValue(), ResidueOps.size()))
6476 return SDValue();
6477 ResidueOps.push_back(BVN->getOperand(I));
6478 }
6479 }
6480
6481 // Nothing to do if there are no EXTRACT_VECTOR_ELTs.
6482 if (!FoundOne)
6483 return SDValue();
6484
6485 // Create the BUILD_VECTOR for the remaining elements, if any.
6486 if (!ResidueOps.empty()) {
6487 while (ResidueOps.size() < NumElements)
6488 ResidueOps.push_back(DAG.getUNDEF(ResidueOps[0].getValueType()));
6489 for (auto &Op : GS.Ops) {
6490 if (!Op.getNode()) {
6491 Op = DAG.getBuildVector(VT, SDLoc(BVN), ResidueOps);
6492 break;
6493 }
6494 }
6495 }
6496 return GS.getNode(DAG, SDLoc(BVN));
6497}
6498
6499bool SystemZTargetLowering::isVectorElementLoad(SDValue Op) const {
6500 if (Op.getOpcode() == ISD::LOAD && cast<LoadSDNode>(Op)->isUnindexed())
6501 return true;
6502 if (auto *AL = dyn_cast<AtomicSDNode>(Op))
6503 if (AL->getOpcode() == ISD::ATOMIC_LOAD)
6504 return true;
6505 if (Subtarget.hasVectorEnhancements2() && Op.getOpcode() == SystemZISD::LRV)
6506 return true;
6507 return false;
6508}
6509
6511 unsigned MergedBits, EVT VT, SDValue Op0,
6512 SDValue Op1) {
6513 MVT IntVecVT = MVT::getVectorVT(MVT::getIntegerVT(MergedBits),
6514 SystemZ::VectorBits / MergedBits);
6515 assert(VT.getSizeInBits() == 128 && IntVecVT.getSizeInBits() == 128 &&
6516 "Handling full vectors only.");
6517 Op0 = DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0);
6518 Op1 = DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op1);
6519 SDValue Op = DAG.getNode(SystemZISD::MERGE_HIGH, DL, IntVecVT, Op0, Op1);
6520 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
6521}
6522
6524 EVT VT, SmallVectorImpl<SDValue> &Elems,
6525 unsigned Pos) {
6526 SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[Pos + 0], Elems[Pos + 1]);
6527 SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[Pos + 2], Elems[Pos + 3]);
6528 // Avoid unnecessary undefs by reusing the other operand.
6529 if (Op01.isUndef()) {
6530 if (Op23.isUndef())
6531 return Op01;
6532 Op01 = Op23;
6533 } else if (Op23.isUndef())
6534 Op23 = Op01;
6535 // Merging identical replications is a no-op.
6536 if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23)
6537 return Op01;
6538 unsigned MergedBits = VT.getSimpleVT().getScalarSizeInBits() * 2;
6539 return mergeHighParts(DAG, DL, MergedBits, VT, Op01, Op23);
6540}
6541
6542// Combine GPR scalar values Elems into a vector of type VT.
6543SDValue
6544SystemZTargetLowering::buildVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
6545 SmallVectorImpl<SDValue> &Elems) const {
6546 // See whether there is a single replicated value.
6547 SDValue Single;
6548 unsigned int NumElements = Elems.size();
6549 unsigned int Count = 0;
6550 for (auto Elem : Elems) {
6551 if (!Elem.isUndef()) {
6552 if (!Single.getNode())
6553 Single = Elem;
6554 else if (Elem != Single) {
6555 Single = SDValue();
6556 break;
6557 }
6558 Count += 1;
6559 }
6560 }
6561 // There are three cases here:
6562 //
6563 // - if the only defined element is a loaded one, the best sequence
6564 // is a replicating load.
6565 //
6566 // - otherwise, if the only defined element is an i64 value, we will
6567 // end up with the same VLVGP sequence regardless of whether we short-cut
6568 // for replication or fall through to the later code.
6569 //
6570 // - otherwise, if the only defined element is an i32 or smaller value,
6571 // we would need 2 instructions to replicate it: VLVGP followed by VREPx.
6572 // This is only a win if the single defined element is used more than once.
6573 // In other cases we're better off using a single VLVGx.
6574 if (Single.getNode() && (Count > 1 || isVectorElementLoad(Single)))
6575 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single);
6576
6577 // If all elements are loads, use VLREP/VLEs (below).
6578 bool AllLoads = true;
6579 for (auto Elem : Elems)
6580 if (!isVectorElementLoad(Elem)) {
6581 AllLoads = false;
6582 break;
6583 }
6584
6585 // The best way of building a v2i64 from two i64s is to use VLVGP.
6586 if (VT == MVT::v2i64 && !AllLoads)
6587 return joinDwords(DAG, DL, Elems[0], Elems[1]);
6588
6589 // Use a 64-bit merge high to combine two doubles.
6590 if (VT == MVT::v2f64 && !AllLoads)
6591 return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
6592
6593 // Build v4f32 values directly from the FPRs:
6594 //
6595 // <Axxx> <Bxxx> <Cxxxx> <Dxxx>
6596 // V V VMRHF
6597 // <ABxx> <CDxx>
6598 // V VMRHG
6599 // <ABCD>
6600 if (VT == MVT::v4f32 && !AllLoads)
6601 return buildFPVecFromScalars4(DAG, DL, VT, Elems, 0);
6602
6603 // Same for v8f16.
6604 if (VT == MVT::v8f16 && !AllLoads) {
6605 SDValue Op0123 = buildFPVecFromScalars4(DAG, DL, VT, Elems, 0);
6606 SDValue Op4567 = buildFPVecFromScalars4(DAG, DL, VT, Elems, 4);
6607 // Avoid unnecessary undefs by reusing the other operand.
6608 if (Op0123.isUndef())
6609 Op0123 = Op4567;
6610 else if (Op4567.isUndef())
6611 Op4567 = Op0123;
6612 // Merging identical replications is a no-op.
6613 if (Op0123.getOpcode() == SystemZISD::REPLICATE && Op0123 == Op4567)
6614 return Op0123;
6615 return mergeHighParts(DAG, DL, 64, VT, Op0123, Op4567);
6616 }
6617
6618 // Collect the constant terms.
6621
6622 unsigned NumConstants = 0;
6623 for (unsigned I = 0; I < NumElements; ++I) {
6624 SDValue Elem = Elems[I];
6625 if (Elem.getOpcode() == ISD::Constant ||
6626 Elem.getOpcode() == ISD::ConstantFP) {
6627 NumConstants += 1;
6628 Constants[I] = Elem;
6629 Done[I] = true;
6630 }
6631 }
6632 // If there was at least one constant, fill in the other elements of
6633 // Constants with undefs to get a full vector constant and use that
6634 // as the starting point.
6635 SDValue Result;
6636 SDValue ReplicatedVal;
6637 if (NumConstants > 0) {
6638 for (unsigned I = 0; I < NumElements; ++I)
6639 if (!Constants[I].getNode())
6640 Constants[I] = DAG.getUNDEF(Elems[I].getValueType());
6641 Result = DAG.getBuildVector(VT, DL, Constants);
6642 } else {
6643 // Otherwise try to use VLREP or VLVGP to start the sequence in order to
6644 // avoid a false dependency on any previous contents of the vector
6645 // register.
6646
6647 // Use a VLREP if at least one element is a load. Make sure to replicate
6648 // the load with the most elements having its value.
6649 std::map<const SDNode*, unsigned> UseCounts;
6650 SDNode *LoadMaxUses = nullptr;
6651 for (unsigned I = 0; I < NumElements; ++I)
6652 if (isVectorElementLoad(Elems[I])) {
6653 SDNode *Ld = Elems[I].getNode();
6654 unsigned Count = ++UseCounts[Ld];
6655 if (LoadMaxUses == nullptr || UseCounts[LoadMaxUses] < Count)
6656 LoadMaxUses = Ld;
6657 }
6658 if (LoadMaxUses != nullptr) {
6659 ReplicatedVal = SDValue(LoadMaxUses, 0);
6660 Result = DAG.getNode(SystemZISD::REPLICATE, DL, VT, ReplicatedVal);
6661 } else {
6662 // Try to use VLVGP.
6663 unsigned I1 = NumElements / 2 - 1;
6664 unsigned I2 = NumElements - 1;
6665 bool Def1 = !Elems[I1].isUndef();
6666 bool Def2 = !Elems[I2].isUndef();
6667 if (Def1 || Def2) {
6668 SDValue Elem1 = Elems[Def1 ? I1 : I2];
6669 SDValue Elem2 = Elems[Def2 ? I2 : I1];
6670 Result = DAG.getNode(ISD::BITCAST, DL, VT,
6671 joinDwords(DAG, DL, Elem1, Elem2));
6672 Done[I1] = true;
6673 Done[I2] = true;
6674 } else
6675 Result = DAG.getUNDEF(VT);
6676 }
6677 }
6678
6679 // Use VLVGx to insert the other elements.
6680 for (unsigned I = 0; I < NumElements; ++I)
6681 if (!Done[I] && !Elems[I].isUndef() && Elems[I] != ReplicatedVal)
6682 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I],
6683 DAG.getConstant(I, DL, MVT::i32));
6684 return Result;
6685}
6686
6687SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op,
6688 SelectionDAG &DAG) const {
6689 auto *BVN = cast<BuildVectorSDNode>(Op.getNode());
6690 SDLoc DL(Op);
6691 EVT VT = Op.getValueType();
6692
6693 if (BVN->isConstant()) {
6694 if (SystemZVectorConstantInfo(BVN).isVectorConstantLegal(Subtarget))
6695 return Op;
6696
6697 // Fall back to loading it from memory.
6698 return SDValue();
6699 }
6700
6701 // See if we should use shuffles to construct the vector from other vectors.
6702 if (SDValue Res = tryBuildVectorShuffle(DAG, BVN))
6703 return Res;
6704
6705 // Detect SCALAR_TO_VECTOR conversions.
6707 return buildScalarToVector(DAG, DL, VT, Op.getOperand(0));
6708
6709 // Otherwise use buildVector to build the vector up from GPRs.
6710 unsigned NumElements = Op.getNumOperands();
6712 for (unsigned I = 0; I < NumElements; ++I)
6713 Ops[I] = Op.getOperand(I);
6714 return buildVector(DAG, DL, VT, Ops);
6715}
6716
6717SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
6718 SelectionDAG &DAG) const {
6719 auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode());
6720 SDLoc DL(Op);
6721 EVT VT = Op.getValueType();
6722 unsigned NumElements = VT.getVectorNumElements();
6723
6724 if (VSN->isSplat()) {
6725 SDValue Op0 = Op.getOperand(0);
6726 unsigned Index = VSN->getSplatIndex();
6727 assert(Index < VT.getVectorNumElements() &&
6728 "Splat index should be defined and in first operand");
6729 // See whether the value we're splatting is directly available as a scalar.
6730 if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
6732 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index));
6733 // Otherwise keep it as a vector-to-vector operation.
6734 return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0),
6735 DAG.getTargetConstant(Index, DL, MVT::i32));
6736 }
6737
6738 GeneralShuffle GS(VT);
6739 for (unsigned I = 0; I < NumElements; ++I) {
6740 int Elt = VSN->getMaskElt(I);
6741 if (Elt < 0)
6742 GS.addUndef();
6743 else if (!GS.add(Op.getOperand(unsigned(Elt) / NumElements),
6744 unsigned(Elt) % NumElements))
6745 return SDValue();
6746 }
6747 return GS.getNode(DAG, SDLoc(VSN));
6748}
6749
6750SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
6751 SelectionDAG &DAG) const {
6752 SDLoc DL(Op);
6753 // Just insert the scalar into element 0 of an undefined vector.
6754 return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL,
6755 Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
6756 Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32));
6757}
6758
6759// Shift the lower 2 bytes of Op to the left in order to insert into the
6760// upper 2 bytes of the FP register.
6762 assert(Op.getSimpleValueType() == MVT::i64 &&
6763 "Expexted to convert i64 to f16.");
6764 SDLoc DL(Op);
6765 SDValue Shft = DAG.getNode(ISD::SHL, DL, MVT::i64, Op,
6766 DAG.getConstant(48, DL, MVT::i64));
6767 SDValue BCast = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Shft);
6768 SDValue F16Val =
6769 DAG.getTargetExtractSubreg(SystemZ::subreg_h16, DL, MVT::f16, BCast);
6770 return F16Val;
6771}
6772
6773// Extract Op into GPR and shift the 2 f16 bytes to the right.
6775 assert(Op.getSimpleValueType() == MVT::f16 &&
6776 "Expected to convert f16 to i64.");
6777 SDNode *U32 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
6778 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h16, DL, MVT::f64,
6779 SDValue(U32, 0), Op);
6780 SDValue BCast = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
6781 SDValue Shft = DAG.getNode(ISD::SRL, DL, MVT::i64, BCast,
6782 DAG.getConstant(48, DL, MVT::i32));
6783 return Shft;
6784}
6785
6787 auto *CIdx = dyn_cast<ConstantSDNode>(Idx);
6788 return CIdx && CIdx->getZExtValue() < VecVT.getVectorNumElements();
6789}
6790
6791SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
6792 SelectionDAG &DAG) const {
6793 // Handle insertions of floating-point values.
6794 SDLoc DL(Op);
6795 SDValue Op0 = Op.getOperand(0);
6796 SDValue Op1 = Op.getOperand(1);
6797 SDValue Op2 = Op.getOperand(2);
6798 EVT VT = Op.getValueType();
6799
6800 // A constant index selects a GR128 subregister.
6801 if (!Subtarget.hasVector())
6802 return isInBoundsConstantVectorIndex(VT, Op2) ? Op : SDValue();
6803
6804 // Insertions into constant indices of a v2f64 can be done using VPDI.
6805 // However, if the inserted value is a bitcast or a constant then it's
6806 // better to use GPRs, as below.
6807 if (VT == MVT::v2f64 && Op1.getOpcode() != ISD::BITCAST &&
6808 Op1.getOpcode() != ISD::ConstantFP &&
6810 return Op;
6811
6812 // Otherwise bitcast to the equivalent integer form and insert via a GPR.
6813 MVT IntVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
6814 MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements());
6815 SDValue IntOp1 =
6816 VT == MVT::v8f16
6817 ? DAG.getZExtOrTrunc(convertFromF16(Op1, DL, DAG), DL, MVT::i32)
6818 : DAG.getNode(ISD::BITCAST, DL, IntVT, Op1);
6819 SDValue Res =
6820 DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT,
6821 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), IntOp1, Op2);
6822 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
6823}
6824
6825SDValue
6826SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
6827 SelectionDAG &DAG) const {
6828 // Handle extractions of floating-point values.
6829 SDLoc DL(Op);
6830 SDValue Op0 = Op.getOperand(0);
6831 SDValue Op1 = Op.getOperand(1);
6832 EVT VT = Op.getValueType();
6833 EVT VecVT = Op0.getValueType();
6834
6835 // Extractions of constant indices can be done directly.
6836 if (isInBoundsConstantVectorIndex(VecVT, Op1))
6837 return Op;
6838
6839 if (!Subtarget.hasVector())
6840 return SDValue();
6841
6842 // Otherwise bitcast to the equivalent integer form and extract via a GPR.
6843 MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
6844 MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements());
6845 MVT ExtrVT = IntVT == MVT::i16 ? MVT::i32 : IntVT;
6846 SDValue Extr = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrVT,
6847 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1);
6848 if (VT == MVT::f16)
6849 return convertToF16(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Extr), DAG);
6850 return DAG.getNode(ISD::BITCAST, DL, VT, Extr);
6851}
6852
6853SDValue SystemZTargetLowering::
6854lowerSIGN_EXTEND_VECTOR_INREG(SDValue Op, SelectionDAG &DAG) const {
6855 SDValue PackedOp = Op.getOperand(0);
6856 EVT OutVT = Op.getValueType();
6857 EVT InVT = PackedOp.getValueType();
6858 unsigned ToBits = OutVT.getScalarSizeInBits();
6859 unsigned FromBits = InVT.getScalarSizeInBits();
6860 unsigned StartOffset = 0;
6861
6862 // If the input is a VECTOR_SHUFFLE, there are a number of important
6863 // cases where we can directly implement the sign-extension of the
6864 // original input lanes of the shuffle.
6865 if (PackedOp.getOpcode() == ISD::VECTOR_SHUFFLE) {
6866 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(PackedOp.getNode());
6867 ArrayRef<int> ShuffleMask = SVN->getMask();
6868 int OutNumElts = OutVT.getVectorNumElements();
6869
6870 // Recognize the special case where the sign-extension can be done
6871 // by the VSEG instruction. Handled via the default expander.
6872 if (ToBits == 64 && OutNumElts == 2) {
6873 int NumElem = ToBits / FromBits;
6874 if (ShuffleMask[0] == NumElem - 1 && ShuffleMask[1] == 2 * NumElem - 1)
6875 return SDValue();
6876 }
6877
6878 // Recognize the special case where we can fold the shuffle by
6879 // replacing some of the UNPACK_HIGH with UNPACK_LOW.
6880 int StartOffsetCandidate = -1;
6881 for (int Elt = 0; Elt < OutNumElts; Elt++) {
6882 if (ShuffleMask[Elt] == -1)
6883 continue;
6884 if (ShuffleMask[Elt] % OutNumElts == Elt) {
6885 if (StartOffsetCandidate == -1)
6886 StartOffsetCandidate = ShuffleMask[Elt] - Elt;
6887 if (StartOffsetCandidate == ShuffleMask[Elt] - Elt)
6888 continue;
6889 }
6890 StartOffsetCandidate = -1;
6891 break;
6892 }
6893 if (StartOffsetCandidate != -1) {
6894 StartOffset = StartOffsetCandidate;
6895 PackedOp = PackedOp.getOperand(0);
6896 }
6897 }
6898
6899 do {
6900 FromBits *= 2;
6901 unsigned OutNumElts = SystemZ::VectorBits / FromBits;
6902 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(FromBits), OutNumElts);
6903 unsigned Opcode = SystemZISD::UNPACK_HIGH;
6904 if (StartOffset >= OutNumElts) {
6905 Opcode = SystemZISD::UNPACK_LOW;
6906 StartOffset -= OutNumElts;
6907 }
6908 PackedOp = DAG.getNode(Opcode, SDLoc(PackedOp), OutVT, PackedOp);
6909 } while (FromBits != ToBits);
6910 return PackedOp;
6911}
6912
6913// Lower a ZERO_EXTEND_VECTOR_INREG to a vector shuffle with a zero vector.
6914SDValue SystemZTargetLowering::
6915lowerZERO_EXTEND_VECTOR_INREG(SDValue Op, SelectionDAG &DAG) const {
6916 SDValue PackedOp = Op.getOperand(0);
6917 SDLoc DL(Op);
6918 EVT OutVT = Op.getValueType();
6919 EVT InVT = PackedOp.getValueType();
6920 unsigned InNumElts = InVT.getVectorNumElements();
6921 unsigned OutNumElts = OutVT.getVectorNumElements();
6922 unsigned NumInPerOut = InNumElts / OutNumElts;
6923
6924 SDValue ZeroVec =
6925 DAG.getSplatVector(InVT, DL, DAG.getConstant(0, DL, InVT.getScalarType()));
6926
6927 SmallVector<int, 16> Mask(InNumElts);
6928 unsigned ZeroVecElt = InNumElts;
6929 for (unsigned PackedElt = 0; PackedElt < OutNumElts; PackedElt++) {
6930 unsigned MaskElt = PackedElt * NumInPerOut;
6931 unsigned End = MaskElt + NumInPerOut - 1;
6932 for (; MaskElt < End; MaskElt++)
6933 Mask[MaskElt] = ZeroVecElt++;
6934 Mask[MaskElt] = PackedElt;
6935 }
6936 SDValue Shuf = DAG.getVectorShuffle(InVT, DL, PackedOp, ZeroVec, Mask);
6937 return DAG.getNode(ISD::BITCAST, DL, OutVT, Shuf);
6938}
6939
6940SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG,
6941 unsigned ByScalar) const {
6942 // Look for cases where a vector shift can use the *_BY_SCALAR form.
6943 SDValue Op0 = Op.getOperand(0);
6944 SDValue Op1 = Op.getOperand(1);
6945 SDLoc DL(Op);
6946 EVT VT = Op.getValueType();
6947 unsigned ElemBitSize = VT.getScalarSizeInBits();
6948
6949 // See whether the shift vector is a splat represented as BUILD_VECTOR.
6950 if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) {
6951 APInt SplatBits, SplatUndef;
6952 unsigned SplatBitSize;
6953 bool HasAnyUndefs;
6954 // Check for constant splats. Use ElemBitSize as the minimum element
6955 // width and reject splats that need wider elements.
6956 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6957 ElemBitSize, true) &&
6958 SplatBitSize == ElemBitSize) {
6959 SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff,
6960 DL, MVT::i32);
6961 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
6962 }
6963 // Check for variable splats.
6964 BitVector UndefElements;
6965 SDValue Splat = BVN->getSplatValue(&UndefElements);
6966 if (Splat) {
6967 // Since i32 is the smallest legal type, we either need a no-op
6968 // or a truncation.
6969 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat);
6970 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
6971 }
6972 }
6973
6974 // See whether the shift vector is a splat represented as SHUFFLE_VECTOR,
6975 // and the shift amount is directly available in a GPR.
6976 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) {
6977 if (VSN->isSplat()) {
6978 SDValue VSNOp0 = VSN->getOperand(0);
6979 unsigned Index = VSN->getSplatIndex();
6980 assert(Index < VT.getVectorNumElements() &&
6981 "Splat index should be defined and in first operand");
6982 if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
6983 VSNOp0.getOpcode() == ISD::BUILD_VECTOR) {
6984 // Since i32 is the smallest legal type, we either need a no-op
6985 // or a truncation.
6986 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
6987 VSNOp0.getOperand(Index));
6988 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
6989 }
6990 }
6991 }
6992
6993 // Otherwise just treat the current form as legal.
6994 return Op;
6995}
6996
6997SDValue SystemZTargetLowering::lowerFSHL(SDValue Op, SelectionDAG &DAG) const {
6998 SDLoc DL(Op);
6999
7000 // i128 FSHL with a constant amount that is a multiple of 8 can be
7001 // implemented via VECTOR_SHUFFLE. If we have the vector-enhancements-2
7002 // facility, FSHL with a constant amount less than 8 can be implemented
7003 // via SHL_DOUBLE_BIT, and FSHL with other constant amounts by a
7004 // combination of the two.
7005 if (auto *ShiftAmtNode = dyn_cast<ConstantSDNode>(Op.getOperand(2))) {
7006 uint64_t ShiftAmt = ShiftAmtNode->getZExtValue() & 127;
7007 if ((ShiftAmt & 7) == 0 || Subtarget.hasVectorEnhancements2()) {
7008 SDValue Op0 = DAG.getBitcast(MVT::v16i8, Op.getOperand(0));
7009 SDValue Op1 = DAG.getBitcast(MVT::v16i8, Op.getOperand(1));
7010 if (ShiftAmt > 120) {
7011 // For N in 121..128, fshl N == fshr (128 - N), and for 1 <= N < 8
7012 // SHR_DOUBLE_BIT emits fewer instructions.
7013 SDValue Val =
7014 DAG.getNode(SystemZISD::SHR_DOUBLE_BIT, DL, MVT::v16i8, Op0, Op1,
7015 DAG.getTargetConstant(128 - ShiftAmt, DL, MVT::i32));
7016 return DAG.getBitcast(MVT::i128, Val);
7017 }
7018 SmallVector<int, 16> Mask(16);
7019 for (unsigned Elt = 0; Elt < 16; Elt++)
7020 Mask[Elt] = (ShiftAmt >> 3) + Elt;
7021 SDValue Shuf1 = DAG.getVectorShuffle(MVT::v16i8, DL, Op0, Op1, Mask);
7022 if ((ShiftAmt & 7) == 0)
7023 return DAG.getBitcast(MVT::i128, Shuf1);
7024 SDValue Shuf2 = DAG.getVectorShuffle(MVT::v16i8, DL, Op1, Op1, Mask);
7025 SDValue Val =
7026 DAG.getNode(SystemZISD::SHL_DOUBLE_BIT, DL, MVT::v16i8, Shuf1, Shuf2,
7027 DAG.getTargetConstant(ShiftAmt & 7, DL, MVT::i32));
7028 return DAG.getBitcast(MVT::i128, Val);
7029 }
7030 }
7031
7032 return SDValue();
7033}
7034
7035SDValue SystemZTargetLowering::lowerFSHR(SDValue Op, SelectionDAG &DAG) const {
7036 SDLoc DL(Op);
7037
7038 // i128 FSHR with a constant amount that is a multiple of 8 can be
7039 // implemented via VECTOR_SHUFFLE. If we have the vector-enhancements-2
7040 // facility, FSHR with a constant amount less than 8 can be implemented
7041 // via SHR_DOUBLE_BIT, and FSHR with other constant amounts by a
7042 // combination of the two.
7043 if (auto *ShiftAmtNode = dyn_cast<ConstantSDNode>(Op.getOperand(2))) {
7044 uint64_t ShiftAmt = ShiftAmtNode->getZExtValue() & 127;
7045 if ((ShiftAmt & 7) == 0 || Subtarget.hasVectorEnhancements2()) {
7046 SDValue Op0 = DAG.getBitcast(MVT::v16i8, Op.getOperand(0));
7047 SDValue Op1 = DAG.getBitcast(MVT::v16i8, Op.getOperand(1));
7048 if (ShiftAmt > 120) {
7049 // For N in 121..128, fshr N == fshl (128 - N), and for 1 <= N < 8
7050 // SHL_DOUBLE_BIT emits fewer instructions.
7051 SDValue Val =
7052 DAG.getNode(SystemZISD::SHL_DOUBLE_BIT, DL, MVT::v16i8, Op0, Op1,
7053 DAG.getTargetConstant(128 - ShiftAmt, DL, MVT::i32));
7054 return DAG.getBitcast(MVT::i128, Val);
7055 }
7056 SmallVector<int, 16> Mask(16);
7057 for (unsigned Elt = 0; Elt < 16; Elt++)
7058 Mask[Elt] = 16 - (ShiftAmt >> 3) + Elt;
7059 SDValue Shuf1 = DAG.getVectorShuffle(MVT::v16i8, DL, Op0, Op1, Mask);
7060 if ((ShiftAmt & 7) == 0)
7061 return DAG.getBitcast(MVT::i128, Shuf1);
7062 SDValue Shuf2 = DAG.getVectorShuffle(MVT::v16i8, DL, Op0, Op0, Mask);
7063 SDValue Val =
7064 DAG.getNode(SystemZISD::SHR_DOUBLE_BIT, DL, MVT::v16i8, Shuf2, Shuf1,
7065 DAG.getTargetConstant(ShiftAmt & 7, DL, MVT::i32));
7066 return DAG.getBitcast(MVT::i128, Val);
7067 }
7068 }
7069
7070 return SDValue();
7071}
7072
7074 SDLoc DL(Op);
7075 SDValue Src = Op.getOperand(0);
7076 MVT DstVT = Op.getSimpleValueType();
7077
7079 unsigned SrcAS = N->getSrcAddressSpace();
7080
7081 assert(SrcAS != N->getDestAddressSpace() &&
7082 "addrspacecast must be between different address spaces");
7083
7084 // addrspacecast [0 <- 1] : Assinging a ptr32 value to a 64-bit pointer.
7085 // addrspacecast [1 <- 0] : Assigining a 64-bit pointer to a ptr32 value.
7086 if (SrcAS == SYSTEMZAS::PTR32 && DstVT == MVT::i64) {
7087 Op = DAG.getNode(ISD::AND, DL, MVT::i32, Src,
7088 DAG.getConstant(0x7fffffff, DL, MVT::i32));
7089 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, DstVT, Op);
7090 } else if (DstVT == MVT::i32) {
7091 Op = DAG.getNode(ISD::TRUNCATE, DL, DstVT, Src);
7092 Op = DAG.getNode(ISD::AND, DL, MVT::i32, Op,
7093 DAG.getConstant(0x7fffffff, DL, MVT::i32));
7094 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, DstVT, Op);
7095 } else {
7096 report_fatal_error("Bad address space in addrspacecast");
7097 }
7098 return Op;
7099}
7100
7101SDValue SystemZTargetLowering::lowerFP_EXTEND(SDValue Op,
7102 SelectionDAG &DAG) const {
7103 SDValue In = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
7104 if (In.getSimpleValueType() != MVT::f16)
7105 return Op; // Legal
7106 return SDValue(); // Let legalizer emit the libcall.
7107}
7108
7110 MVT VT, SDValue Arg, SDLoc DL,
7111 SDValue Chain, bool IsStrict) const {
7112 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected request for libcall!");
7113 MakeLibCallOptions CallOptions;
7114 SDValue Result;
7115 std::tie(Result, Chain) =
7116 makeLibCall(DAG, LC, VT, Arg, CallOptions, DL, Chain);
7117 return IsStrict ? DAG.getMergeValues({Result, Chain}, DL) : Result;
7118}
7119
7120SDValue SystemZTargetLowering::lower_FP_TO_INT(SDValue Op,
7121 SelectionDAG &DAG) const {
7122 bool IsSigned = (Op->getOpcode() == ISD::FP_TO_SINT ||
7123 Op->getOpcode() == ISD::STRICT_FP_TO_SINT);
7124 bool IsStrict = Op->isStrictFPOpcode();
7125 SDLoc DL(Op);
7126 MVT VT = Op.getSimpleValueType();
7127 SDValue InOp = Op.getOperand(IsStrict ? 1 : 0);
7128 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
7129 EVT InVT = InOp.getValueType();
7130
7131 // FP to unsigned is not directly supported on z10. Promoting an i32
7132 // result to (signed) i64 doesn't generate an inexact condition (fp
7133 // exception) for values that are outside the i32 range but in the i64
7134 // range, so use the default expansion.
7135 if (!Subtarget.hasFPExtension() && !IsSigned)
7136 // Expand i32/i64. F16 values will be recognized to fit and extended.
7137 return SDValue();
7138
7139 // Conversion from f16 is done via f32.
7140 if (InOp.getSimpleValueType() == MVT::f16) {
7142 LowerOperationWrapper(Op.getNode(), Results, DAG);
7143 return DAG.getMergeValues(Results, DL);
7144 }
7145
7146 if (VT == MVT::i128) {
7147 RTLIB::Libcall LC =
7148 IsSigned ? RTLIB::getFPTOSINT(InVT, VT) : RTLIB::getFPTOUINT(InVT, VT);
7149 return useLibCall(DAG, LC, VT, InOp, DL, Chain, IsStrict);
7150 }
7151
7152 return Op; // Legal
7153}
7154
7155SDValue SystemZTargetLowering::lower_INT_TO_FP(SDValue Op,
7156 SelectionDAG &DAG) const {
7157 bool IsSigned = (Op->getOpcode() == ISD::SINT_TO_FP ||
7158 Op->getOpcode() == ISD::STRICT_SINT_TO_FP);
7159 bool IsStrict = Op->isStrictFPOpcode();
7160 SDLoc DL(Op);
7161 MVT VT = Op.getSimpleValueType();
7162 SDValue InOp = Op.getOperand(IsStrict ? 1 : 0);
7163 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
7164 EVT InVT = InOp.getValueType();
7165
7166 // Conversion to f16 is done via f32.
7167 if (VT == MVT::f16) {
7169 LowerOperationWrapper(Op.getNode(), Results, DAG);
7170 return DAG.getMergeValues(Results, DL);
7171 }
7172
7173 // Unsigned to fp is not directly supported on z10.
7174 if (!Subtarget.hasFPExtension() && !IsSigned)
7175 return SDValue(); // Expand i64.
7176
7177 if (InVT == MVT::i128) {
7178 RTLIB::Libcall LC =
7179 IsSigned ? RTLIB::getSINTTOFP(InVT, VT) : RTLIB::getUINTTOFP(InVT, VT);
7180 return useLibCall(DAG, LC, VT, InOp, DL, Chain, IsStrict);
7181 }
7182
7183 return Op; // Legal
7184}
7185
7186// Lower an f16 LOAD in case of no vector support.
7187SDValue SystemZTargetLowering::lowerLoadF16(SDValue Op,
7188 SelectionDAG &DAG) const {
7189 EVT RegVT = Op.getValueType();
7190 assert(RegVT == MVT::f16 && "Expected to lower an f16 load.");
7191 (void)RegVT;
7192
7193 // Load as integer.
7194 SDLoc DL(Op);
7195 SDValue NewLd;
7196 if (auto *AtomicLd = dyn_cast<AtomicSDNode>(Op.getNode())) {
7197 assert(EVT(RegVT) == AtomicLd->getMemoryVT() && "Unhandled f16 load");
7198 NewLd = DAG.getAtomicLoad(ISD::EXTLOAD, DL, MVT::i16, MVT::i64,
7199 AtomicLd->getChain(), AtomicLd->getBasePtr(),
7200 AtomicLd->getMemOperand());
7201 } else {
7202 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
7203 assert(EVT(RegVT) == Ld->getMemoryVT() && "Unhandled f16 load");
7204 NewLd = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i64, Ld->getChain(),
7205 Ld->getBasePtr(), Ld->getPointerInfo(), MVT::i16,
7206 Ld->getBaseAlign(), Ld->getMemOperand()->getFlags());
7207 }
7208 SDValue F16Val = convertToF16(NewLd, DAG);
7209 return DAG.getMergeValues({F16Val, NewLd.getValue(1)}, DL);
7210}
7211
7212// Lower an f16 STORE in case of no vector support.
7213SDValue SystemZTargetLowering::lowerStoreF16(SDValue Op,
7214 SelectionDAG &DAG) const {
7215 SDLoc DL(Op);
7216 SDValue Shft = convertFromF16(Op->getOperand(1), DL, DAG);
7217
7218 if (auto *AtomicSt = dyn_cast<AtomicSDNode>(Op.getNode()))
7219 return DAG.getAtomic(ISD::ATOMIC_STORE, DL, MVT::i16, AtomicSt->getChain(),
7220 Shft, AtomicSt->getBasePtr(),
7221 AtomicSt->getMemOperand());
7222
7223 StoreSDNode *St = cast<StoreSDNode>(Op.getNode());
7224 return DAG.getTruncStore(St->getChain(), DL, Shft, St->getBasePtr(), MVT::i16,
7225 St->getMemOperand());
7226}
7227
7228SDValue SystemZTargetLowering::lowerIS_FPCLASS(SDValue Op,
7229 SelectionDAG &DAG) const {
7230 SDLoc DL(Op);
7231 MVT ResultVT = Op.getSimpleValueType();
7232 SDValue Arg = Op.getOperand(0);
7233 unsigned Check = Op.getConstantOperandVal(1);
7234
7235 unsigned TDCMask = 0;
7236 if (Check & fcSNan)
7238 if (Check & fcQNan)
7240 if (Check & fcPosInf)
7242 if (Check & fcNegInf)
7244 if (Check & fcPosNormal)
7246 if (Check & fcNegNormal)
7248 if (Check & fcPosSubnormal)
7250 if (Check & fcNegSubnormal)
7252 if (Check & fcPosZero)
7253 TDCMask |= SystemZ::TDCMASK_ZERO_PLUS;
7254 if (Check & fcNegZero)
7255 TDCMask |= SystemZ::TDCMASK_ZERO_MINUS;
7256 SDValue TDCMaskV = DAG.getConstant(TDCMask, DL, MVT::i64);
7257
7258 SDValue Intr = DAG.getNode(SystemZISD::TDC, DL, ResultVT, Arg, TDCMaskV);
7259 return getCCResult(DAG, Intr);
7260}
7261
7262SDValue SystemZTargetLowering::lowerREADCYCLECOUNTER(SDValue Op,
7263 SelectionDAG &DAG) const {
7264 SDLoc DL(Op);
7265 SDValue Chain = Op.getOperand(0);
7266
7267 // STCKF only supports a memory operand, so we have to use a temporary.
7268 SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
7269 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
7270 MachinePointerInfo MPI =
7272
7273 // Use STCFK to store the TOD clock into the temporary.
7274 SDValue StoreOps[] = {Chain, StackPtr};
7275 Chain = DAG.getMemIntrinsicNode(
7276 SystemZISD::STCKF, DL, DAG.getVTList(MVT::Other), StoreOps, MVT::i64,
7277 MPI, MaybeAlign(), MachineMemOperand::MOStore);
7278
7279 // And read it back from there.
7280 return DAG.getLoad(MVT::i64, DL, Chain, StackPtr, MPI);
7281}
7282
7284 SelectionDAG &DAG) const {
7285 switch (Op.getOpcode()) {
7286 case ISD::FRAMEADDR:
7287 return lowerFRAMEADDR(Op, DAG);
7288 case ISD::RETURNADDR:
7289 return lowerRETURNADDR(Op, DAG);
7290 case ISD::BR_CC:
7291 return lowerBR_CC(Op, DAG);
7292 case ISD::SELECT_CC:
7293 return lowerSELECT_CC(Op, DAG);
7294 case ISD::SETCC:
7295 return lowerSETCC(Op, DAG);
7296 case ISD::STRICT_FSETCC:
7297 return lowerSTRICT_FSETCC(Op, DAG, false);
7299 return lowerSTRICT_FSETCC(Op, DAG, true);
7300 case ISD::GlobalAddress:
7301 return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
7303 return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
7304 case ISD::BlockAddress:
7305 return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
7306 case ISD::JumpTable:
7307 return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
7308 case ISD::ConstantPool:
7309 return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
7310 case ISD::BITCAST:
7311 return lowerBITCAST(Op, DAG);
7312 case ISD::VASTART:
7313 return lowerVASTART(Op, DAG);
7314 case ISD::VACOPY:
7315 return lowerVACOPY(Op, DAG);
7317 return lowerDYNAMIC_STACKALLOC(Op, DAG);
7319 return lowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
7320 case ISD::MULHS:
7321 return lowerMULH(Op, DAG, SystemZISD::SMUL_LOHI);
7322 case ISD::MULHU:
7323 return lowerMULH(Op, DAG, SystemZISD::UMUL_LOHI);
7324 case ISD::SMUL_LOHI:
7325 return lowerSMUL_LOHI(Op, DAG);
7326 case ISD::UMUL_LOHI:
7327 return lowerUMUL_LOHI(Op, DAG);
7328 case ISD::SDIVREM:
7329 return lowerSDIVREM(Op, DAG);
7330 case ISD::UDIVREM:
7331 return lowerUDIVREM(Op, DAG);
7332 case ISD::SADDO:
7333 case ISD::SSUBO:
7334 case ISD::UADDO:
7335 case ISD::USUBO:
7336 return lowerXALUO(Op, DAG);
7337 case ISD::UADDO_CARRY:
7338 case ISD::USUBO_CARRY:
7339 return lowerUADDSUBO_CARRY(Op, DAG);
7340 case ISD::OR:
7341 return lowerOR(Op, DAG);
7342 case ISD::CTPOP:
7343 return lowerCTPOP(Op, DAG);
7344 case ISD::VECREDUCE_ADD:
7345 return lowerVECREDUCE_ADD(Op, DAG);
7346 case ISD::ATOMIC_FENCE:
7347 return lowerATOMIC_FENCE(Op, DAG);
7348 case ISD::ATOMIC_SWAP:
7349 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_SWAPW);
7350 case ISD::ATOMIC_STORE:
7351 return lowerATOMIC_STORE(Op, DAG);
7352 case ISD::ATOMIC_LOAD:
7353 return lowerATOMIC_LOAD(Op, DAG);
7355 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
7357 return lowerATOMIC_LOAD_SUB(Op, DAG);
7359 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
7361 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
7363 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
7365 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
7367 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
7369 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
7371 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
7373 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
7375 return lowerATOMIC_CMP_SWAP(Op, DAG);
7376 case ISD::STACKSAVE:
7377 return lowerSTACKSAVE(Op, DAG);
7378 case ISD::STACKRESTORE:
7379 return lowerSTACKRESTORE(Op, DAG);
7380 case ISD::PREFETCH:
7381 return lowerPREFETCH(Op, DAG);
7383 return lowerINTRINSIC_W_CHAIN(Op, DAG);
7385 return lowerINTRINSIC_WO_CHAIN(Op, DAG);
7386 case ISD::BUILD_VECTOR:
7387 return lowerBUILD_VECTOR(Op, DAG);
7389 return lowerVECTOR_SHUFFLE(Op, DAG);
7391 return lowerSCALAR_TO_VECTOR(Op, DAG);
7393 return lowerINSERT_VECTOR_ELT(Op, DAG);
7395 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
7397 return lowerSIGN_EXTEND_VECTOR_INREG(Op, DAG);
7399 return lowerZERO_EXTEND_VECTOR_INREG(Op, DAG);
7400 case ISD::SHL:
7401 return lowerShift(Op, DAG, SystemZISD::VSHL_BY_SCALAR);
7402 case ISD::SRL:
7403 return lowerShift(Op, DAG, SystemZISD::VSRL_BY_SCALAR);
7404 case ISD::SRA:
7405 return lowerShift(Op, DAG, SystemZISD::VSRA_BY_SCALAR);
7406 case ISD::ADDRSPACECAST:
7407 return lowerAddrSpaceCast(Op, DAG);
7408 case ISD::ROTL:
7409 return lowerShift(Op, DAG, SystemZISD::VROTL_BY_SCALAR);
7410 case ISD::FSHL:
7411 return lowerFSHL(Op, DAG);
7412 case ISD::FSHR:
7413 return lowerFSHR(Op, DAG);
7414 case ISD::FP_EXTEND:
7416 return lowerFP_EXTEND(Op, DAG);
7417 case ISD::FP_TO_UINT:
7418 case ISD::FP_TO_SINT:
7421 return lower_FP_TO_INT(Op, DAG);
7422 case ISD::UINT_TO_FP:
7423 case ISD::SINT_TO_FP:
7426 return lower_INT_TO_FP(Op, DAG);
7427 case ISD::LOAD:
7428 return lowerLoadF16(Op, DAG);
7429 case ISD::STORE:
7430 return lowerStoreF16(Op, DAG);
7431 case ISD::IS_FPCLASS:
7432 return lowerIS_FPCLASS(Op, DAG);
7433 case ISD::GET_ROUNDING:
7434 return lowerGET_ROUNDING(Op, DAG);
7436 return lowerREADCYCLECOUNTER(Op, DAG);
7439 // These operations are legal on our platform, but we cannot actually
7440 // set the operation action to Legal as common code would treat this
7441 // as equivalent to Expand. Instead, we keep the operation action to
7442 // Custom and just leave them unchanged here.
7443 return Op;
7444
7445 default:
7446 llvm_unreachable("Unexpected node to lower");
7447 }
7448}
7449
7451 const SDLoc &SL) {
7452 // If i128 is legal, just use a normal bitcast.
7453 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128))
7454 return DAG.getBitcast(MVT::f128, Src);
7455
7456 // Otherwise, f128 must live in FP128, so do a partwise move.
7458 &SystemZ::FP128BitRegClass);
7459
7460 SDValue Hi, Lo;
7461 std::tie(Lo, Hi) = DAG.SplitScalar(Src, SL, MVT::i64, MVT::i64);
7462
7463 Hi = DAG.getBitcast(MVT::f64, Hi);
7464 Lo = DAG.getBitcast(MVT::f64, Lo);
7465
7466 SDNode *Pair = DAG.getMachineNode(
7467 SystemZ::REG_SEQUENCE, SL, MVT::f128,
7468 {DAG.getTargetConstant(SystemZ::FP128BitRegClassID, SL, MVT::i32), Lo,
7469 DAG.getTargetConstant(SystemZ::subreg_l64, SL, MVT::i32), Hi,
7470 DAG.getTargetConstant(SystemZ::subreg_h64, SL, MVT::i32)});
7471 return SDValue(Pair, 0);
7472}
7473
7475 const SDLoc &SL) {
7476 // If i128 is legal, just use a normal bitcast.
7477 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128))
7478 return DAG.getBitcast(MVT::i128, Src);
7479
7480 // Otherwise, f128 must live in FP128, so do a partwise move.
7482 &SystemZ::FP128BitRegClass);
7483
7484 SDValue LoFP =
7485 DAG.getTargetExtractSubreg(SystemZ::subreg_l64, SL, MVT::f64, Src);
7486 SDValue HiFP =
7487 DAG.getTargetExtractSubreg(SystemZ::subreg_h64, SL, MVT::f64, Src);
7488 SDValue Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i64, LoFP);
7489 SDValue Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i64, HiFP);
7490
7491 return DAG.getNode(ISD::BUILD_PAIR, SL, MVT::i128, Lo, Hi);
7492}
7493
7494// Lower operations with invalid operand or result types.
7495void
7498 SelectionDAG &DAG) const {
7499 switch (N->getOpcode()) {
7500 case ISD::ATOMIC_LOAD: {
7501 SDLoc DL(N);
7502 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
7503 SDValue Ops[] = { N->getOperand(0), N->getOperand(1) };
7504 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
7505 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_LOAD_128,
7506 DL, Tys, Ops, MVT::i128, MMO);
7507
7508 SDValue Lowered = lowerGR128ToI128(DAG, Res);
7509 if (N->getValueType(0) == MVT::f128)
7510 Lowered = expandBitCastI128ToF128(DAG, Lowered, DL);
7511 Results.push_back(Lowered);
7512 Results.push_back(Res.getValue(1));
7513 break;
7514 }
7515 case ISD::ATOMIC_STORE: {
7516 SDLoc DL(N);
7517 SDVTList Tys = DAG.getVTList(MVT::Other);
7518 SDValue Val = N->getOperand(1);
7519 if (Val.getValueType() == MVT::f128)
7520 Val = expandBitCastF128ToI128(DAG, Val, DL);
7521 Val = lowerI128ToGR128(DAG, Val);
7522
7523 SDValue Ops[] = {N->getOperand(0), Val, N->getOperand(2)};
7524 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
7525 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_STORE_128,
7526 DL, Tys, Ops, MVT::i128, MMO);
7527 // We have to enforce sequential consistency by performing a
7528 // serialization operation after the store.
7529 if (cast<AtomicSDNode>(N)->getSuccessOrdering() ==
7531 Res = SDValue(DAG.getMachineNode(SystemZ::Serialize, DL,
7532 MVT::Other, Res), 0);
7533 Results.push_back(Res);
7534 break;
7535 }
7537 SDLoc DL(N);
7538 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::i32, MVT::Other);
7539 SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
7540 lowerI128ToGR128(DAG, N->getOperand(2)),
7541 lowerI128ToGR128(DAG, N->getOperand(3)) };
7542 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
7543 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP_128,
7544 DL, Tys, Ops, MVT::i128, MMO);
7545 SDValue Success = emitSETCC(DAG, DL, Res.getValue(1),
7547 Success = DAG.getZExtOrTrunc(Success, DL, N->getValueType(1));
7548 Results.push_back(lowerGR128ToI128(DAG, Res));
7549 Results.push_back(Success);
7550 Results.push_back(Res.getValue(2));
7551 break;
7552 }
7553 case ISD::BITCAST: {
7554 if (useSoftFloat())
7555 return;
7556 SDLoc DL(N);
7557 SDValue Src = N->getOperand(0);
7558 EVT SrcVT = Src.getValueType();
7559 EVT ResVT = N->getValueType(0);
7560 if (ResVT == MVT::i128 && SrcVT == MVT::f128)
7561 Results.push_back(expandBitCastF128ToI128(DAG, Src, DL));
7562 else if (SrcVT == MVT::i16 && ResVT == MVT::f16) {
7563 if (Subtarget.hasVector()) {
7564 SDValue In32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Src);
7565 Results.push_back(SDValue(
7566 DAG.getMachineNode(SystemZ::LEFR_16, DL, MVT::f16, In32), 0));
7567 } else {
7568 SDValue In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Src);
7569 Results.push_back(convertToF16(In64, DAG));
7570 }
7571 } else if (SrcVT == MVT::f16 && ResVT == MVT::i16) {
7572 SDValue ExtractedVal =
7573 Subtarget.hasVector()
7574 ? SDValue(DAG.getMachineNode(SystemZ::LFER_16, DL, MVT::i32, Src),
7575 0)
7576 : convertFromF16(Src, DL, DAG);
7577 Results.push_back(DAG.getZExtOrTrunc(ExtractedVal, DL, ResVT));
7578 }
7579 break;
7580 }
7581 case ISD::UINT_TO_FP:
7582 case ISD::SINT_TO_FP:
7585 if (useSoftFloat())
7586 return;
7587 bool IsStrict = N->isStrictFPOpcode();
7588 SDLoc DL(N);
7589 SDValue InOp = N->getOperand(IsStrict ? 1 : 0);
7590 EVT ResVT = N->getValueType(0);
7591 SDValue Chain = IsStrict ? N->getOperand(0) : DAG.getEntryNode();
7592 if (ResVT == MVT::f16) {
7593 if (!IsStrict) {
7594 SDValue OpF32 = DAG.getNode(N->getOpcode(), DL, MVT::f32, InOp);
7595 Results.push_back(DAG.getFPExtendOrRound(OpF32, DL, MVT::f16));
7596 } else {
7597 SDValue OpF32 =
7598 DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::f32, MVT::Other),
7599 {Chain, InOp});
7600 SDValue F16Res;
7601 std::tie(F16Res, Chain) = DAG.getStrictFPExtendOrRound(
7602 OpF32, OpF32.getValue(1), DL, MVT::f16);
7603 Results.push_back(F16Res);
7604 Results.push_back(Chain);
7605 }
7606 }
7607 break;
7608 }
7609 case ISD::FP_TO_UINT:
7610 case ISD::FP_TO_SINT:
7613 if (useSoftFloat())
7614 return;
7615 bool IsStrict = N->isStrictFPOpcode();
7616 SDLoc DL(N);
7617 EVT ResVT = N->getValueType(0);
7618 SDValue InOp = N->getOperand(IsStrict ? 1 : 0);
7619 EVT InVT = InOp->getValueType(0);
7620 SDValue Chain = IsStrict ? N->getOperand(0) : DAG.getEntryNode();
7621 if (InVT == MVT::f16) {
7622 if (!IsStrict) {
7623 SDValue InF32 = DAG.getFPExtendOrRound(InOp, DL, MVT::f32);
7624 Results.push_back(DAG.getNode(N->getOpcode(), DL, ResVT, InF32));
7625 } else {
7626 SDValue InF32;
7627 std::tie(InF32, Chain) =
7628 DAG.getStrictFPExtendOrRound(InOp, Chain, DL, MVT::f32);
7629 SDValue OpF32 =
7630 DAG.getNode(N->getOpcode(), DL, DAG.getVTList(ResVT, MVT::Other),
7631 {Chain, InF32});
7632 Results.push_back(OpF32);
7633 Results.push_back(OpF32.getValue(1));
7634 }
7635 }
7636 break;
7637 }
7638 default:
7639 llvm_unreachable("Unexpected node to lower");
7640 }
7641}
7642
7643void
7649
7650// Return true if VT is a vector whose elements are a whole number of bytes
7651// in width. Also check for presence of vector support.
7652bool SystemZTargetLowering::canTreatAsByteVector(EVT VT) const {
7653 if (!Subtarget.hasVector())
7654 return false;
7655
7656 return VT.isVector() && VT.getScalarSizeInBits() % 8 == 0 && VT.isSimple();
7657}
7658
7659// Try to simplify an EXTRACT_VECTOR_ELT from a vector of type VecVT
7660// producing a result of type ResVT. Op is a possibly bitcast version
7661// of the input vector and Index is the index (based on type VecVT) that
7662// should be extracted. Return the new extraction if a simplification
7663// was possible or if Force is true.
7664SDValue SystemZTargetLowering::combineExtract(const SDLoc &DL, EVT ResVT,
7665 EVT VecVT, SDValue Op,
7666 unsigned Index,
7667 DAGCombinerInfo &DCI,
7668 bool Force) const {
7669 SelectionDAG &DAG = DCI.DAG;
7670
7671 // The number of bytes being extracted.
7672 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
7673
7674 for (;;) {
7675 unsigned Opcode = Op.getOpcode();
7676 if (Opcode == ISD::BITCAST)
7677 // Look through bitcasts.
7678 Op = Op.getOperand(0);
7679 else if ((Opcode == ISD::VECTOR_SHUFFLE || Opcode == SystemZISD::SPLAT) &&
7680 canTreatAsByteVector(Op.getValueType())) {
7681 // Get a VPERM-like permute mask and see whether the bytes covered
7682 // by the extracted element are a contiguous sequence from one
7683 // source operand.
7685 if (!getVPermMask(Op, Bytes))
7686 break;
7687 int First;
7688 if (!getShuffleInput(Bytes, Index * BytesPerElement,
7689 BytesPerElement, First))
7690 break;
7691 if (First < 0)
7692 return DAG.getUNDEF(ResVT);
7693 // Make sure the contiguous sequence starts at a multiple of the
7694 // original element size.
7695 unsigned Byte = unsigned(First) % Bytes.size();
7696 if (Byte % BytesPerElement != 0)
7697 break;
7698 // We can get the extracted value directly from an input.
7699 Index = Byte / BytesPerElement;
7700 Op = Op.getOperand(unsigned(First) / Bytes.size());
7701 Force = true;
7702 } else if (Opcode == ISD::BUILD_VECTOR &&
7703 canTreatAsByteVector(Op.getValueType())) {
7704 // We can only optimize this case if the BUILD_VECTOR elements are
7705 // at least as wide as the extracted value.
7706 EVT OpVT = Op.getValueType();
7707 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
7708 if (OpBytesPerElement < BytesPerElement)
7709 break;
7710 // Make sure that the least-significant bit of the extracted value
7711 // is the least significant bit of an input.
7712 unsigned End = (Index + 1) * BytesPerElement;
7713 if (End % OpBytesPerElement != 0)
7714 break;
7715 // We're extracting the low part of one operand of the BUILD_VECTOR.
7716 Op = Op.getOperand(End / OpBytesPerElement - 1);
7717 EVT ResIntVT = MVT::getIntegerVT(ResVT.getSizeInBits());
7718 if (!isTypeLegal(ResIntVT))
7719 break;
7720 if (!Op.getValueType().isInteger()) {
7721 EVT OpIntVT = MVT::getIntegerVT(Op.getValueSizeInBits());
7722 if (!isTypeLegal(OpIntVT))
7723 break;
7724 Op = DAG.getNode(ISD::BITCAST, DL, OpIntVT, Op);
7725 DCI.AddToWorklist(Op.getNode());
7726 }
7727 Op = DAG.getNode(ISD::TRUNCATE, DL, ResIntVT, Op);
7728 if (ResIntVT != ResVT) {
7729 DCI.AddToWorklist(Op.getNode());
7730 Op = DAG.getNode(ISD::BITCAST, DL, ResVT, Op);
7731 }
7732 return Op;
7733 } else if ((Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
7735 Opcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
7736 canTreatAsByteVector(Op.getValueType()) &&
7737 canTreatAsByteVector(Op.getOperand(0).getValueType())) {
7738 // Make sure that only the unextended bits are significant.
7739 EVT ExtVT = Op.getValueType();
7740 EVT OpVT = Op.getOperand(0).getValueType();
7741 unsigned ExtBytesPerElement = ExtVT.getVectorElementType().getStoreSize();
7742 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
7743 unsigned Byte = Index * BytesPerElement;
7744 unsigned SubByte = Byte % ExtBytesPerElement;
7745 unsigned MinSubByte = ExtBytesPerElement - OpBytesPerElement;
7746 if (SubByte < MinSubByte ||
7747 SubByte + BytesPerElement > ExtBytesPerElement)
7748 break;
7749 // Get the byte offset of the unextended element
7750 Byte = Byte / ExtBytesPerElement * OpBytesPerElement;
7751 // ...then add the byte offset relative to that element.
7752 Byte += SubByte - MinSubByte;
7753 if (Byte % BytesPerElement != 0)
7754 break;
7755 Op = Op.getOperand(0);
7756 Index = Byte / BytesPerElement;
7757 Force = true;
7758 } else
7759 break;
7760 }
7761 if (Force) {
7762 if (Op.getValueType() != VecVT) {
7763 Op = DAG.getNode(ISD::BITCAST, DL, VecVT, Op);
7764 DCI.AddToWorklist(Op.getNode());
7765 }
7766 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Op,
7767 DAG.getConstant(Index, DL, MVT::i32));
7768 }
7769 return SDValue();
7770}
7771
7772// Optimize vector operations in scalar value Op on the basis that Op
7773// is truncated to TruncVT.
7774SDValue SystemZTargetLowering::combineTruncateExtract(
7775 const SDLoc &DL, EVT TruncVT, SDValue Op, DAGCombinerInfo &DCI) const {
7776 // If we have (trunc (extract_vector_elt X, Y)), try to turn it into
7777 // (extract_vector_elt (bitcast X), Y'), where (bitcast X) has elements
7778 // of type TruncVT.
7779 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7780 TruncVT.getSizeInBits() % 8 == 0) {
7781 SDValue Vec = Op.getOperand(0);
7782 EVT VecVT = Vec.getValueType();
7783 if (canTreatAsByteVector(VecVT)) {
7784 if (auto *IndexN = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7785 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
7786 unsigned TruncBytes = TruncVT.getStoreSize();
7787 if (BytesPerElement % TruncBytes == 0) {
7788 // Calculate the value of Y' in the above description. We are
7789 // splitting the original elements into Scale equal-sized pieces
7790 // and for truncation purposes want the last (least-significant)
7791 // of these pieces for IndexN. This is easiest to do by calculating
7792 // the start index of the following element and then subtracting 1.
7793 unsigned Scale = BytesPerElement / TruncBytes;
7794 unsigned NewIndex = (IndexN->getZExtValue() + 1) * Scale - 1;
7795
7796 // Defer the creation of the bitcast from X to combineExtract,
7797 // which might be able to optimize the extraction.
7798 VecVT = EVT::getVectorVT(*DCI.DAG.getContext(),
7799 MVT::getIntegerVT(TruncBytes * 8),
7800 VecVT.getStoreSize() / TruncBytes);
7801 EVT ResVT = (TruncBytes < 4 ? MVT::i32 : TruncVT);
7802 return combineExtract(DL, ResVT, VecVT, Vec, NewIndex, DCI, true);
7803 }
7804 }
7805 }
7806 }
7807 return SDValue();
7808}
7809
7810SDValue SystemZTargetLowering::combineZERO_EXTEND(
7811 SDNode *N, DAGCombinerInfo &DCI) const {
7812 // Convert (zext (select_ccmask C1, C2)) into (select_ccmask C1', C2')
7813 SelectionDAG &DAG = DCI.DAG;
7814 SDValue N0 = N->getOperand(0);
7815 EVT VT = N->getValueType(0);
7816 if (N0.getOpcode() == SystemZISD::SELECT_CCMASK) {
7817 auto *TrueOp = dyn_cast<ConstantSDNode>(N0.getOperand(0));
7818 auto *FalseOp = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7819 if (TrueOp && FalseOp) {
7820 SDLoc DL(N0);
7821 SDValue Ops[] = { DAG.getConstant(TrueOp->getZExtValue(), DL, VT),
7822 DAG.getConstant(FalseOp->getZExtValue(), DL, VT),
7823 N0.getOperand(2), N0.getOperand(3), N0.getOperand(4) };
7824 SDValue NewSelect = DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VT, Ops);
7825 // If N0 has multiple uses, change other uses as well.
7826 if (!N0.hasOneUse()) {
7827 SDValue TruncSelect =
7828 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), NewSelect);
7829 DCI.CombineTo(N0.getNode(), TruncSelect);
7830 }
7831 return NewSelect;
7832 }
7833 }
7834 // Convert (zext (xor (trunc X), C)) into (xor (trunc X), C') if the size
7835 // of the result is smaller than the size of X and all the truncated bits
7836 // of X are already zero.
7837 if (N0.getOpcode() == ISD::XOR &&
7838 N0.hasOneUse() && N0.getOperand(0).hasOneUse() &&
7839 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7840 N0.getOperand(1).getOpcode() == ISD::Constant) {
7841 SDValue X = N0.getOperand(0).getOperand(0);
7842 if (VT.isScalarInteger() && VT.getSizeInBits() < X.getValueSizeInBits()) {
7843 KnownBits Known = DAG.computeKnownBits(X);
7844 APInt TruncatedBits = APInt::getBitsSet(X.getValueSizeInBits(),
7845 N0.getValueSizeInBits(),
7846 VT.getSizeInBits());
7847 if (TruncatedBits.isSubsetOf(Known.Zero)) {
7848 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7849 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
7850 return DAG.getNode(ISD::XOR, SDLoc(N0), VT,
7851 X, DAG.getConstant(Mask, SDLoc(N0), VT));
7852 }
7853 }
7854 }
7855 // Recognize patterns for VECTOR SUBTRACT COMPUTE BORROW INDICATION
7856 // and VECTOR ADD COMPUTE CARRY for i128:
7857 // (zext (setcc_uge X Y)) --> (VSCBI X Y)
7858 // (zext (setcc_ule Y X)) --> (VSCBI X Y)
7859 // (zext (setcc_ult (add X Y) X/Y) -> (VACC X Y)
7860 // (zext (setcc_ugt X/Y (add X Y)) -> (VACC X Y)
7861 // For vector types, these patterns are recognized in the .td file.
7862 if (N0.getOpcode() == ISD::SETCC && isTypeLegal(VT) && VT == MVT::i128 &&
7863 N0.getOperand(0).getValueType() == VT) {
7864 SDValue Op0 = N0.getOperand(0);
7865 SDValue Op1 = N0.getOperand(1);
7866 const ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
7867 switch (CC) {
7868 case ISD::SETULE:
7869 std::swap(Op0, Op1);
7870 [[fallthrough]];
7871 case ISD::SETUGE:
7872 return DAG.getNode(SystemZISD::VSCBI, SDLoc(N0), VT, Op0, Op1);
7873 case ISD::SETUGT:
7874 std::swap(Op0, Op1);
7875 [[fallthrough]];
7876 case ISD::SETULT:
7877 if (Op0->hasOneUse() && Op0->getOpcode() == ISD::ADD &&
7878 (Op0->getOperand(0) == Op1 || Op0->getOperand(1) == Op1))
7879 return DAG.getNode(SystemZISD::VACC, SDLoc(N0), VT, Op0->getOperand(0),
7880 Op0->getOperand(1));
7881 break;
7882 default:
7883 break;
7884 }
7885 }
7886
7887 return SDValue();
7888}
7889
7890SDValue SystemZTargetLowering::combineSIGN_EXTEND_INREG(
7891 SDNode *N, DAGCombinerInfo &DCI) const {
7892 // Convert (sext_in_reg (setcc LHS, RHS, COND), i1)
7893 // and (sext_in_reg (any_extend (setcc LHS, RHS, COND)), i1)
7894 // into (select_cc LHS, RHS, -1, 0, COND)
7895 SelectionDAG &DAG = DCI.DAG;
7896 SDValue N0 = N->getOperand(0);
7897 EVT VT = N->getValueType(0);
7898 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7899 if (N0.hasOneUse() && N0.getOpcode() == ISD::ANY_EXTEND)
7900 N0 = N0.getOperand(0);
7901 if (EVT == MVT::i1 && N0.hasOneUse() && N0.getOpcode() == ISD::SETCC) {
7902 SDLoc DL(N0);
7903 SDValue Ops[] = { N0.getOperand(0), N0.getOperand(1),
7904 DAG.getAllOnesConstant(DL, VT),
7905 DAG.getConstant(0, DL, VT), N0.getOperand(2) };
7906 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
7907 }
7908 return SDValue();
7909}
7910
7911SDValue SystemZTargetLowering::combineSIGN_EXTEND(
7912 SDNode *N, DAGCombinerInfo &DCI) const {
7913 // Convert (sext (ashr (shl X, C1), C2)) to
7914 // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
7915 // cheap as narrower ones.
7916 SelectionDAG &DAG = DCI.DAG;
7917 SDValue N0 = N->getOperand(0);
7918 EVT VT = N->getValueType(0);
7919 if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
7920 auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7921 SDValue Inner = N0.getOperand(0);
7922 if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
7923 if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
7924 unsigned Extra = (VT.getSizeInBits() - N0.getValueSizeInBits());
7925 unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
7926 unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
7927 EVT ShiftVT = N0.getOperand(1).getValueType();
7928 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
7929 Inner.getOperand(0));
7930 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
7931 DAG.getConstant(NewShlAmt, SDLoc(Inner),
7932 ShiftVT));
7933 return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
7934 DAG.getConstant(NewSraAmt, SDLoc(N0), ShiftVT));
7935 }
7936 }
7937 }
7938
7939 return SDValue();
7940}
7941
7942SDValue SystemZTargetLowering::combineMERGE(
7943 SDNode *N, DAGCombinerInfo &DCI) const {
7944 SelectionDAG &DAG = DCI.DAG;
7945 unsigned Opcode = N->getOpcode();
7946 SDValue Op0 = N->getOperand(0);
7947 SDValue Op1 = N->getOperand(1);
7948 if (Op0.getOpcode() == ISD::BITCAST)
7949 Op0 = Op0.getOperand(0);
7951 // (z_merge_* 0, 0) -> 0. This is mostly useful for using VLLEZF
7952 // for v4f32.
7953 if (Op1 == N->getOperand(0))
7954 return Op1;
7955 // (z_merge_? 0, X) -> (z_unpackl_? 0, X).
7956 EVT VT = Op1.getValueType();
7957 unsigned ElemBytes = VT.getVectorElementType().getStoreSize();
7958 if (ElemBytes <= 4) {
7959 Opcode = (Opcode == SystemZISD::MERGE_HIGH ?
7960 SystemZISD::UNPACKL_HIGH : SystemZISD::UNPACKL_LOW);
7961 EVT InVT = VT.changeVectorElementTypeToInteger();
7962 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(ElemBytes * 16),
7963 SystemZ::VectorBytes / ElemBytes / 2);
7964 if (VT != InVT) {
7965 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), InVT, Op1);
7966 DCI.AddToWorklist(Op1.getNode());
7967 }
7968 SDValue Op = DAG.getNode(Opcode, SDLoc(N), OutVT, Op1);
7969 DCI.AddToWorklist(Op.getNode());
7970 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7971 }
7972 }
7973 return SDValue();
7974}
7975
7976static bool isI128MovedToParts(LoadSDNode *LD, SDNode *&LoPart,
7977 SDNode *&HiPart) {
7978 LoPart = HiPart = nullptr;
7979
7980 // Scan through all users.
7981 for (SDUse &Use : LD->uses()) {
7982 // Skip the uses of the chain.
7983 if (Use.getResNo() != 0)
7984 continue;
7985
7986 // Verify every user is a TRUNCATE to i64 of the low or high half.
7987 SDNode *User = Use.getUser();
7988 bool IsLoPart = true;
7989 if (User->getOpcode() == ISD::SRL &&
7990 User->getOperand(1).getOpcode() == ISD::Constant &&
7991 User->getConstantOperandVal(1) == 64 && User->hasOneUse()) {
7992 User = *User->user_begin();
7993 IsLoPart = false;
7994 }
7995 if (User->getOpcode() != ISD::TRUNCATE || User->getValueType(0) != MVT::i64)
7996 return false;
7997
7998 if (IsLoPart) {
7999 if (LoPart)
8000 return false;
8001 LoPart = User;
8002 } else {
8003 if (HiPart)
8004 return false;
8005 HiPart = User;
8006 }
8007 }
8008 return true;
8009}
8010
8011static bool isF128MovedToParts(LoadSDNode *LD, SDNode *&LoPart,
8012 SDNode *&HiPart) {
8013 LoPart = HiPart = nullptr;
8014
8015 // Scan through all users.
8016 for (SDUse &Use : LD->uses()) {
8017 // Skip the uses of the chain.
8018 if (Use.getResNo() != 0)
8019 continue;
8020
8021 // Verify every user is an EXTRACT_SUBREG of the low or high half.
8022 SDNode *User = Use.getUser();
8023 if (!User->hasOneUse() || !User->isMachineOpcode() ||
8024 User->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
8025 return false;
8026
8027 switch (User->getConstantOperandVal(1)) {
8028 case SystemZ::subreg_l64:
8029 if (LoPart)
8030 return false;
8031 LoPart = User;
8032 break;
8033 case SystemZ::subreg_h64:
8034 if (HiPart)
8035 return false;
8036 HiPart = User;
8037 break;
8038 default:
8039 return false;
8040 }
8041 }
8042 return true;
8043}
8044
8045SDValue SystemZTargetLowering::combineLOAD(
8046 SDNode *N, DAGCombinerInfo &DCI) const {
8047 SelectionDAG &DAG = DCI.DAG;
8048 EVT LdVT = N->getValueType(0);
8049 if (auto *LN = dyn_cast<LoadSDNode>(N)) {
8050 if (LN->getAddressSpace() == SYSTEMZAS::PTR32) {
8051 MVT PtrVT = getPointerTy(DAG.getDataLayout());
8052 MVT LoadNodeVT = LN->getBasePtr().getSimpleValueType();
8053 if (PtrVT != LoadNodeVT) {
8054 SDLoc DL(LN);
8055 SDValue AddrSpaceCast = DAG.getAddrSpaceCast(
8056 DL, PtrVT, LN->getBasePtr(), SYSTEMZAS::PTR32, 0);
8057 return DAG.getExtLoad(LN->getExtensionType(), DL, LN->getValueType(0),
8058 LN->getChain(), AddrSpaceCast, LN->getMemoryVT(),
8059 LN->getMemOperand());
8060 }
8061 }
8062 }
8063 SDLoc DL(N);
8064
8065 // Replace a 128-bit load that is used solely to move its value into GPRs
8066 // by separate loads of both halves.
8067 LoadSDNode *LD = cast<LoadSDNode>(N);
8068 if (LD->isSimple() && ISD::isNormalLoad(LD)) {
8069 SDNode *LoPart, *HiPart;
8070 if ((LdVT == MVT::i128 && isI128MovedToParts(LD, LoPart, HiPart)) ||
8071 (LdVT == MVT::f128 && isF128MovedToParts(LD, LoPart, HiPart))) {
8072 // Rewrite each extraction as an independent load.
8073 SmallVector<SDValue, 2> ArgChains;
8074 if (HiPart) {
8075 SDValue EltLoad = DAG.getLoad(
8076 HiPart->getValueType(0), DL, LD->getChain(), LD->getBasePtr(),
8077 LD->getPointerInfo(), LD->getBaseAlign(),
8078 LD->getMemOperand()->getFlags(), LD->getAAInfo());
8079
8080 DCI.CombineTo(HiPart, EltLoad, true);
8081 ArgChains.push_back(EltLoad.getValue(1));
8082 }
8083 if (LoPart) {
8084 SDValue EltLoad = DAG.getLoad(
8085 LoPart->getValueType(0), DL, LD->getChain(),
8086 DAG.getObjectPtrOffset(DL, LD->getBasePtr(), TypeSize::getFixed(8)),
8087 LD->getPointerInfo().getWithOffset(8), LD->getBaseAlign(),
8088 LD->getMemOperand()->getFlags(), LD->getAAInfo());
8089
8090 DCI.CombineTo(LoPart, EltLoad, true);
8091 ArgChains.push_back(EltLoad.getValue(1));
8092 }
8093
8094 // Collect all chains via TokenFactor.
8095 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, ArgChains);
8096 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8097 DCI.AddToWorklist(Chain.getNode());
8098 return SDValue(N, 0);
8099 }
8100 }
8101
8102 if (LdVT.isVector() || LdVT.isInteger())
8103 return SDValue();
8104 // Transform a scalar load that is REPLICATEd as well as having other
8105 // use(s) to the form where the other use(s) use the first element of the
8106 // REPLICATE instead of the load. Otherwise instruction selection will not
8107 // produce a VLREP. Avoid extracting to a GPR, so only do this for floating
8108 // point loads.
8109
8110 SDValue Replicate;
8111 SmallVector<SDNode*, 8> OtherUses;
8112 for (SDUse &Use : N->uses()) {
8113 if (Use.getUser()->getOpcode() == SystemZISD::REPLICATE) {
8114 if (Replicate)
8115 return SDValue(); // Should never happen
8116 Replicate = SDValue(Use.getUser(), 0);
8117 } else if (Use.getResNo() == 0)
8118 OtherUses.push_back(Use.getUser());
8119 }
8120 if (!Replicate || OtherUses.empty())
8121 return SDValue();
8122
8123 SDValue Extract0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, LdVT,
8124 Replicate, DAG.getConstant(0, DL, MVT::i32));
8125 // Update uses of the loaded Value while preserving old chains.
8126 for (SDNode *U : OtherUses) {
8128 for (SDValue Op : U->ops())
8129 Ops.push_back((Op.getNode() == N && Op.getResNo() == 0) ? Extract0 : Op);
8130 DAG.UpdateNodeOperands(U, Ops);
8131 }
8132 return SDValue(N, 0);
8133}
8134
8135bool SystemZTargetLowering::canLoadStoreByteSwapped(EVT VT) const {
8136 if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)
8137 return true;
8138 if (Subtarget.hasVectorEnhancements2())
8139 if (VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v2i64 || VT == MVT::i128)
8140 return true;
8141 return false;
8142}
8143
8145 if (!VT.isVector() || !VT.isSimple() ||
8146 VT.getSizeInBits() != 128 ||
8147 VT.getScalarSizeInBits() % 8 != 0)
8148 return false;
8149
8150 unsigned NumElts = VT.getVectorNumElements();
8151 for (unsigned i = 0; i < NumElts; ++i) {
8152 if (M[i] < 0) continue; // ignore UNDEF indices
8153 if ((unsigned) M[i] != NumElts - 1 - i)
8154 return false;
8155 }
8156
8157 return true;
8158}
8159
8160static bool isOnlyUsedByStores(SDValue StoredVal, SelectionDAG &DAG) {
8161 for (auto *U : StoredVal->users()) {
8162 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(U)) {
8163 EVT CurrMemVT = ST->getMemoryVT().getScalarType();
8164 if (CurrMemVT.isRound() && CurrMemVT.getStoreSize() <= 16)
8165 continue;
8166 } else if (isa<BuildVectorSDNode>(U)) {
8167 SDValue BuildVector = SDValue(U, 0);
8168 if (DAG.isSplatValue(BuildVector, true/*AllowUndefs*/) &&
8169 isOnlyUsedByStores(BuildVector, DAG))
8170 continue;
8171 }
8172 return false;
8173 }
8174 return true;
8175}
8176
8177static bool isI128MovedFromParts(SDValue Val, SDValue &LoPart,
8178 SDValue &HiPart) {
8179 if (Val.getOpcode() != ISD::OR || !Val.getNode()->hasOneUse())
8180 return false;
8181
8182 SDValue Op0 = Val.getOperand(0);
8183 SDValue Op1 = Val.getOperand(1);
8184
8185 if (Op0.getOpcode() == ISD::SHL)
8186 std::swap(Op0, Op1);
8187 if (Op1.getOpcode() != ISD::SHL || !Op1.getNode()->hasOneUse() ||
8188 Op1.getOperand(1).getOpcode() != ISD::Constant ||
8189 Op1.getConstantOperandVal(1) != 64)
8190 return false;
8191 Op1 = Op1.getOperand(0);
8192
8193 if (Op0.getOpcode() != ISD::ZERO_EXTEND || !Op0.getNode()->hasOneUse() ||
8194 Op0.getOperand(0).getValueType() != MVT::i64)
8195 return false;
8196 if (Op1.getOpcode() != ISD::ANY_EXTEND || !Op1.getNode()->hasOneUse() ||
8197 Op1.getOperand(0).getValueType() != MVT::i64)
8198 return false;
8199
8200 LoPart = Op0.getOperand(0);
8201 HiPart = Op1.getOperand(0);
8202 return true;
8203}
8204
8205static bool isF128MovedFromParts(SDValue Val, SDValue &LoPart,
8206 SDValue &HiPart) {
8207 if (!Val.getNode()->hasOneUse() || !Val.isMachineOpcode() ||
8208 Val.getMachineOpcode() != TargetOpcode::REG_SEQUENCE)
8209 return false;
8210
8211 if (Val->getNumOperands() != 5 ||
8212 Val->getOperand(0)->getAsZExtVal() != SystemZ::FP128BitRegClassID ||
8213 Val->getOperand(2)->getAsZExtVal() != SystemZ::subreg_l64 ||
8214 Val->getOperand(4)->getAsZExtVal() != SystemZ::subreg_h64)
8215 return false;
8216
8217 LoPart = Val->getOperand(1);
8218 HiPart = Val->getOperand(3);
8219 return true;
8220}
8221
8222SDValue SystemZTargetLowering::combineSTORE(
8223 SDNode *N, DAGCombinerInfo &DCI) const {
8224 SelectionDAG &DAG = DCI.DAG;
8225 auto *SN = cast<StoreSDNode>(N);
8226 auto &Op1 = N->getOperand(1);
8227 EVT MemVT = SN->getMemoryVT();
8228
8229 if (SN->getAddressSpace() == SYSTEMZAS::PTR32) {
8230 MVT PtrVT = getPointerTy(DAG.getDataLayout());
8231 MVT StoreNodeVT = SN->getBasePtr().getSimpleValueType();
8232 if (PtrVT != StoreNodeVT) {
8233 SDLoc DL(SN);
8234 SDValue AddrSpaceCast = DAG.getAddrSpaceCast(DL, PtrVT, SN->getBasePtr(),
8235 SYSTEMZAS::PTR32, 0);
8236 return DAG.getStore(SN->getChain(), DL, SN->getValue(), AddrSpaceCast,
8237 SN->getPointerInfo(), SN->getBaseAlign(),
8238 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8239 }
8240 }
8241
8242 // If we have (truncstoreiN (extract_vector_elt X, Y), Z) then it is better
8243 // for the extraction to be done on a vMiN value, so that we can use VSTE.
8244 // If X has wider elements then convert it to:
8245 // (truncstoreiN (extract_vector_elt (bitcast X), Y2), Z).
8246 if (MemVT.isInteger() && SN->isTruncatingStore()) {
8247 if (SDValue Value =
8248 combineTruncateExtract(SDLoc(N), MemVT, SN->getValue(), DCI)) {
8249 DCI.AddToWorklist(Value.getNode());
8250
8251 // Rewrite the store with the new form of stored value.
8252 return DAG.getTruncStore(SN->getChain(), SDLoc(SN), Value,
8253 SN->getBasePtr(), SN->getMemoryVT(),
8254 SN->getMemOperand());
8255 }
8256 }
8257
8258 // combine STORE (LOAD_STACK_GUARD) into MOV_STACKGUARD_DAG
8259 if (Op1->isMachineOpcode() &&
8260 (Op1->getMachineOpcode() == SystemZ::LOAD_STACK_GUARD)) {
8261 // Obtain the frame index the store was targeting.
8262 int FI = cast<FrameIndexSDNode>(SN->getOperand(2))->getIndex();
8263 // Prepare operands of the MOV_STACKGUARD ISD Node - Chain and FrameIndex.
8264 SDValue Ops[] = {SN->getChain(), DAG.getTargetFrameIndex(FI, MVT::i64)};
8265 return DAG.getNode(SystemZISD::MOV_STACKGUARD, SDLoc(SN), MVT::Other, Ops);
8266 }
8267
8268 // Combine STORE (BSWAP) into STRVH/STRV/STRVG/VSTBR
8269 if (!SN->isTruncatingStore() &&
8270 Op1.getOpcode() == ISD::BSWAP &&
8271 Op1.getNode()->hasOneUse() &&
8272 canLoadStoreByteSwapped(Op1.getValueType())) {
8273
8274 SDValue BSwapOp = Op1.getOperand(0);
8275
8276 if (BSwapOp.getValueType() == MVT::i16)
8277 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), MVT::i32, BSwapOp);
8278
8279 SDValue Ops[] = {
8280 N->getOperand(0), BSwapOp, N->getOperand(2)
8281 };
8282
8283 return
8284 DAG.getMemIntrinsicNode(SystemZISD::STRV, SDLoc(N), DAG.getVTList(MVT::Other),
8285 Ops, MemVT, SN->getMemOperand());
8286 }
8287 // Combine STORE (element-swap) into VSTER
8288 if (!SN->isTruncatingStore() &&
8289 Op1.getOpcode() == ISD::VECTOR_SHUFFLE &&
8290 Op1.getNode()->hasOneUse() &&
8291 Subtarget.hasVectorEnhancements2()) {
8292 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op1.getNode());
8293 ArrayRef<int> ShuffleMask = SVN->getMask();
8294 if (isVectorElementSwap(ShuffleMask, Op1.getValueType())) {
8295 SDValue Ops[] = {
8296 N->getOperand(0), Op1.getOperand(0), N->getOperand(2)
8297 };
8298
8299 return DAG.getMemIntrinsicNode(SystemZISD::VSTER, SDLoc(N),
8300 DAG.getVTList(MVT::Other),
8301 Ops, MemVT, SN->getMemOperand());
8302 }
8303 }
8304
8305 // Combine STORE (READCYCLECOUNTER) into STCKF.
8306 if (!SN->isTruncatingStore() &&
8308 Op1.hasOneUse() &&
8309 N->getOperand(0).reachesChainWithoutSideEffects(SDValue(Op1.getNode(), 1))) {
8310 SDValue Ops[] = { Op1.getOperand(0), N->getOperand(2) };
8311 return DAG.getMemIntrinsicNode(SystemZISD::STCKF, SDLoc(N),
8312 DAG.getVTList(MVT::Other),
8313 Ops, MemVT, SN->getMemOperand());
8314 }
8315
8316 // Transform a store of a 128-bit value moved from parts into two stores.
8317 if (SN->isSimple() && ISD::isNormalStore(SN)) {
8318 SDValue LoPart, HiPart;
8319 if ((MemVT == MVT::i128 && isI128MovedFromParts(Op1, LoPart, HiPart)) ||
8320 (MemVT == MVT::f128 && isF128MovedFromParts(Op1, LoPart, HiPart))) {
8321 SDLoc DL(SN);
8322 SDValue Chain0 = DAG.getStore(
8323 SN->getChain(), DL, HiPart, SN->getBasePtr(), SN->getPointerInfo(),
8324 SN->getBaseAlign(), SN->getMemOperand()->getFlags(), SN->getAAInfo());
8325 SDValue Chain1 = DAG.getStore(
8326 SN->getChain(), DL, LoPart,
8327 DAG.getObjectPtrOffset(DL, SN->getBasePtr(), TypeSize::getFixed(8)),
8328 SN->getPointerInfo().getWithOffset(8), SN->getBaseAlign(),
8329 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8330
8331 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chain0, Chain1);
8332 }
8333 }
8334
8335 // Replicate a reg or immediate with VREP instead of scalar multiply or
8336 // immediate load. It seems best to do this during the first DAGCombine as
8337 // it is straight-forward to handle the zero-extend node in the initial
8338 // DAG, and also not worry about the keeping the new MemVT legal (e.g. when
8339 // extracting an i16 element from a v16i8 vector).
8340 if (Subtarget.hasVector() && DCI.Level == BeforeLegalizeTypes &&
8341 isOnlyUsedByStores(Op1, DAG)) {
8342 SDValue Word = SDValue();
8343 EVT WordVT;
8344
8345 // Find a replicated immediate and return it if found in Word and its
8346 // type in WordVT.
8347 auto FindReplicatedImm = [&](ConstantSDNode *C, unsigned TotBytes) {
8348 // Some constants are better handled with a scalar store.
8349 if (C->getAPIntValue().getBitWidth() > 64 || C->isAllOnes() ||
8350 isInt<16>(C->getSExtValue()) || MemVT.getStoreSize() <= 2)
8351 return;
8352
8353 APInt Val = C->getAPIntValue();
8354 // Truncate Val in case of a truncating store.
8355 if (!llvm::isUIntN(TotBytes * 8, Val.getZExtValue())) {
8356 assert(SN->isTruncatingStore() &&
8357 "Non-truncating store and immediate value does not fit?");
8358 Val = Val.trunc(TotBytes * 8);
8359 }
8360
8361 SystemZVectorConstantInfo VCI(APInt(TotBytes * 8, Val.getZExtValue()));
8362 if (VCI.isVectorConstantLegal(Subtarget) &&
8363 VCI.Opcode == SystemZISD::REPLICATE) {
8364 Word = DAG.getConstant(VCI.OpVals[0], SDLoc(SN), MVT::i32);
8365 WordVT = VCI.VecVT.getScalarType();
8366 }
8367 };
8368
8369 // Find a replicated register and return it if found in Word and its type
8370 // in WordVT.
8371 auto FindReplicatedReg = [&](SDValue MulOp) {
8372 EVT MulVT = MulOp.getValueType();
8373 if (MulOp->getOpcode() == ISD::MUL &&
8374 (MulVT == MVT::i16 || MulVT == MVT::i32 || MulVT == MVT::i64)) {
8375 // Find a zero extended value and its type.
8376 SDValue LHS = MulOp->getOperand(0);
8377 if (LHS->getOpcode() == ISD::ZERO_EXTEND)
8378 WordVT = LHS->getOperand(0).getValueType();
8379 else if (LHS->getOpcode() == ISD::AssertZext)
8380 WordVT = cast<VTSDNode>(LHS->getOperand(1))->getVT();
8381 else
8382 return;
8383 // Find a replicating constant, e.g. 0x00010001.
8384 if (auto *C = dyn_cast<ConstantSDNode>(MulOp->getOperand(1))) {
8385 SystemZVectorConstantInfo VCI(
8386 APInt(MulVT.getSizeInBits(), C->getZExtValue()));
8387 if (VCI.isVectorConstantLegal(Subtarget) &&
8388 VCI.Opcode == SystemZISD::REPLICATE && VCI.OpVals[0] == 1 &&
8389 WordVT == VCI.VecVT.getScalarType())
8390 Word = DAG.getZExtOrTrunc(LHS->getOperand(0), SDLoc(SN), WordVT);
8391 }
8392 }
8393 };
8394
8395 if (isa<BuildVectorSDNode>(Op1) &&
8396 DAG.isSplatValue(Op1, true/*AllowUndefs*/)) {
8397 SDValue SplatVal = Op1->getOperand(0);
8398 if (auto *C = dyn_cast<ConstantSDNode>(SplatVal))
8399 FindReplicatedImm(C, SplatVal.getValueType().getStoreSize());
8400 else
8401 FindReplicatedReg(SplatVal);
8402 } else {
8403 if (auto *C = dyn_cast<ConstantSDNode>(Op1))
8404 FindReplicatedImm(C, MemVT.getStoreSize());
8405 else
8406 FindReplicatedReg(Op1);
8407 }
8408
8409 if (Word != SDValue()) {
8410 assert(MemVT.getSizeInBits() % WordVT.getSizeInBits() == 0 &&
8411 "Bad type handling");
8412 unsigned NumElts = MemVT.getSizeInBits() / WordVT.getSizeInBits();
8413 EVT SplatVT = EVT::getVectorVT(*DAG.getContext(), WordVT, NumElts);
8414 SDValue SplatVal = DAG.getSplatVector(SplatVT, SDLoc(SN), Word);
8415 return DAG.getStore(SN->getChain(), SDLoc(SN), SplatVal,
8416 SN->getBasePtr(), SN->getMemOperand());
8417 }
8418 }
8419
8420 return SDValue();
8421}
8422
8423SDValue SystemZTargetLowering::combineVECTOR_SHUFFLE(
8424 SDNode *N, DAGCombinerInfo &DCI) const {
8425 SelectionDAG &DAG = DCI.DAG;
8426 // Combine element-swap (LOAD) into VLER
8427 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8428 N->getOperand(0).hasOneUse() &&
8429 Subtarget.hasVectorEnhancements2()) {
8430 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8431 ArrayRef<int> ShuffleMask = SVN->getMask();
8432 if (isVectorElementSwap(ShuffleMask, N->getValueType(0))) {
8433 SDValue Load = N->getOperand(0);
8434 LoadSDNode *LD = cast<LoadSDNode>(Load);
8435
8436 // Create the element-swapping load.
8437 SDValue Ops[] = {
8438 LD->getChain(), // Chain
8439 LD->getBasePtr() // Ptr
8440 };
8441 SDValue ESLoad =
8442 DAG.getMemIntrinsicNode(SystemZISD::VLER, SDLoc(N),
8443 DAG.getVTList(LD->getValueType(0), MVT::Other),
8444 Ops, LD->getMemoryVT(), LD->getMemOperand());
8445
8446 // First, combine the VECTOR_SHUFFLE away. This makes the value produced
8447 // by the load dead.
8448 DCI.CombineTo(N, ESLoad);
8449
8450 // Next, combine the load away, we give it a bogus result value but a real
8451 // chain result. The result value is dead because the shuffle is dead.
8452 DCI.CombineTo(Load.getNode(), ESLoad, ESLoad.getValue(1));
8453
8454 // Return N so it doesn't get rechecked!
8455 return SDValue(N, 0);
8456 }
8457 }
8458
8459 return SDValue();
8460}
8461
8462SDValue SystemZTargetLowering::combineEXTRACT_VECTOR_ELT(
8463 SDNode *N, DAGCombinerInfo &DCI) const {
8464 SelectionDAG &DAG = DCI.DAG;
8465
8466 if (!Subtarget.hasVector())
8467 return SDValue();
8468
8469 // Look through bitcasts that retain the number of vector elements.
8470 SDValue Op = N->getOperand(0);
8471 if (Op.getOpcode() == ISD::BITCAST &&
8472 Op.getValueType().isVector() &&
8473 Op.getOperand(0).getValueType().isVector() &&
8474 Op.getValueType().getVectorNumElements() ==
8475 Op.getOperand(0).getValueType().getVectorNumElements())
8476 Op = Op.getOperand(0);
8477
8478 // Pull BSWAP out of a vector extraction.
8479 if (Op.getOpcode() == ISD::BSWAP && Op.hasOneUse()) {
8480 EVT VecVT = Op.getValueType();
8481 EVT EltVT = VecVT.getVectorElementType();
8482 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), EltVT,
8483 Op.getOperand(0), N->getOperand(1));
8484 DCI.AddToWorklist(Op.getNode());
8485 Op = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Op);
8486 if (EltVT != N->getValueType(0)) {
8487 DCI.AddToWorklist(Op.getNode());
8488 Op = DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Op);
8489 }
8490 return Op;
8491 }
8492
8493 // Try to simplify a vector extraction.
8494 if (auto *IndexN = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8495 SDValue Op0 = N->getOperand(0);
8496 EVT VecVT = Op0.getValueType();
8497 if (canTreatAsByteVector(VecVT))
8498 return combineExtract(SDLoc(N), N->getValueType(0), VecVT, Op0,
8499 IndexN->getZExtValue(), DCI, false);
8500 }
8501 return SDValue();
8502}
8503
8504SDValue SystemZTargetLowering::combineJOIN_DWORDS(
8505 SDNode *N, DAGCombinerInfo &DCI) const {
8506 SelectionDAG &DAG = DCI.DAG;
8507 // (join_dwords X, X) == (replicate X)
8508 if (N->getOperand(0) == N->getOperand(1))
8509 return DAG.getNode(SystemZISD::REPLICATE, SDLoc(N), N->getValueType(0),
8510 N->getOperand(0));
8511 return SDValue();
8512}
8513
8515 SDValue Chain1 = N1->getOperand(0);
8516 SDValue Chain2 = N2->getOperand(0);
8517
8518 // Trivial case: both nodes take the same chain.
8519 if (Chain1 == Chain2)
8520 return Chain1;
8521
8522 // FIXME - we could handle more complex cases via TokenFactor,
8523 // assuming we can verify that this would not create a cycle.
8524 return SDValue();
8525}
8526
8527SDValue SystemZTargetLowering::combineFP_ROUND(
8528 SDNode *N, DAGCombinerInfo &DCI) const {
8529
8530 if (!Subtarget.hasVector())
8531 return SDValue();
8532
8533 // (fpround (extract_vector_elt X 0))
8534 // (fpround (extract_vector_elt X 1)) ->
8535 // (extract_vector_elt (VROUND X) 0)
8536 // (extract_vector_elt (VROUND X) 2)
8537 //
8538 // This is a special case since the target doesn't really support v2f32s.
8539 unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0;
8540 SelectionDAG &DAG = DCI.DAG;
8541 SDValue Op0 = N->getOperand(OpNo);
8542 if (N->getValueType(0) == MVT::f32 && Op0.hasOneUse() &&
8544 Op0.getOperand(0).getValueType() == MVT::v2f64 &&
8545 Op0.getOperand(1).getOpcode() == ISD::Constant &&
8546 Op0.getConstantOperandVal(1) == 0) {
8547 SDValue Vec = Op0.getOperand(0);
8548 for (auto *U : Vec->users()) {
8549 if (U != Op0.getNode() && U->hasOneUse() &&
8550 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8551 U->getOperand(0) == Vec &&
8552 U->getOperand(1).getOpcode() == ISD::Constant &&
8553 U->getConstantOperandVal(1) == 1) {
8554 SDValue OtherRound = SDValue(*U->user_begin(), 0);
8555 if (OtherRound.getOpcode() == N->getOpcode() &&
8556 OtherRound.getOperand(OpNo) == SDValue(U, 0) &&
8557 OtherRound.getValueType() == MVT::f32) {
8558 SDValue VRound, Chain;
8559 if (N->isStrictFPOpcode()) {
8560 Chain = MergeInputChains(N, OtherRound.getNode());
8561 if (!Chain)
8562 continue;
8563 VRound = DAG.getNode(SystemZISD::STRICT_VROUND, SDLoc(N),
8564 {MVT::v4f32, MVT::Other}, {Chain, Vec});
8565 Chain = VRound.getValue(1);
8566 } else
8567 VRound = DAG.getNode(SystemZISD::VROUND, SDLoc(N),
8568 MVT::v4f32, Vec);
8569 DCI.AddToWorklist(VRound.getNode());
8570 SDValue Extract1 =
8571 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f32,
8572 VRound, DAG.getConstant(2, SDLoc(U), MVT::i32));
8573 DCI.AddToWorklist(Extract1.getNode());
8574 DAG.ReplaceAllUsesOfValueWith(OtherRound, Extract1);
8575 if (Chain)
8576 DAG.ReplaceAllUsesOfValueWith(OtherRound.getValue(1), Chain);
8577 SDValue Extract0 =
8578 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f32,
8579 VRound, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
8580 if (Chain)
8581 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0),
8582 N->getVTList(), Extract0, Chain);
8583 return Extract0;
8584 }
8585 }
8586 }
8587 }
8588 return SDValue();
8589}
8590
8591SDValue SystemZTargetLowering::combineFP_EXTEND(
8592 SDNode *N, DAGCombinerInfo &DCI) const {
8593
8594 if (!Subtarget.hasVector())
8595 return SDValue();
8596
8597 // (fpextend (extract_vector_elt X 0))
8598 // (fpextend (extract_vector_elt X 2)) ->
8599 // (extract_vector_elt (VEXTEND X) 0)
8600 // (extract_vector_elt (VEXTEND X) 1)
8601 //
8602 // This is a special case since the target doesn't really support v2f32s.
8603 unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0;
8604 SelectionDAG &DAG = DCI.DAG;
8605 SDValue Op0 = N->getOperand(OpNo);
8606 if (N->getValueType(0) == MVT::f64 && Op0.hasOneUse() &&
8608 Op0.getOperand(0).getValueType() == MVT::v4f32 &&
8609 Op0.getOperand(1).getOpcode() == ISD::Constant &&
8610 Op0.getConstantOperandVal(1) == 0) {
8611 SDValue Vec = Op0.getOperand(0);
8612 for (auto *U : Vec->users()) {
8613 if (U != Op0.getNode() && U->hasOneUse() &&
8614 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8615 U->getOperand(0) == Vec &&
8616 U->getOperand(1).getOpcode() == ISD::Constant &&
8617 U->getConstantOperandVal(1) == 2) {
8618 SDValue OtherExtend = SDValue(*U->user_begin(), 0);
8619 if (OtherExtend.getOpcode() == N->getOpcode() &&
8620 OtherExtend.getOperand(OpNo) == SDValue(U, 0) &&
8621 OtherExtend.getValueType() == MVT::f64) {
8622 SDValue VExtend, Chain;
8623 if (N->isStrictFPOpcode()) {
8624 Chain = MergeInputChains(N, OtherExtend.getNode());
8625 if (!Chain)
8626 continue;
8627 VExtend = DAG.getNode(SystemZISD::STRICT_VEXTEND, SDLoc(N),
8628 {MVT::v2f64, MVT::Other}, {Chain, Vec});
8629 Chain = VExtend.getValue(1);
8630 } else
8631 VExtend = DAG.getNode(SystemZISD::VEXTEND, SDLoc(N),
8632 MVT::v2f64, Vec);
8633 DCI.AddToWorklist(VExtend.getNode());
8634 SDValue Extract1 =
8635 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f64,
8636 VExtend, DAG.getConstant(1, SDLoc(U), MVT::i32));
8637 DCI.AddToWorklist(Extract1.getNode());
8638 DAG.ReplaceAllUsesOfValueWith(OtherExtend, Extract1);
8639 if (Chain)
8640 DAG.ReplaceAllUsesOfValueWith(OtherExtend.getValue(1), Chain);
8641 SDValue Extract0 =
8642 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f64,
8643 VExtend, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
8644 if (Chain)
8645 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0),
8646 N->getVTList(), Extract0, Chain);
8647 return Extract0;
8648 }
8649 }
8650 }
8651 }
8652 return SDValue();
8653}
8654
8655SDValue SystemZTargetLowering::combineINT_TO_FP(
8656 SDNode *N, DAGCombinerInfo &DCI) const {
8657 if (DCI.Level != BeforeLegalizeTypes)
8658 return SDValue();
8659 SelectionDAG &DAG = DCI.DAG;
8660 LLVMContext &Ctx = *DAG.getContext();
8661 unsigned Opcode = N->getOpcode();
8662 EVT OutVT = N->getValueType(0);
8663 Type *OutLLVMTy = OutVT.getTypeForEVT(Ctx);
8664 SDValue Op = N->getOperand(0);
8665 unsigned OutScalarBits = OutLLVMTy->getScalarSizeInBits();
8666 unsigned InScalarBits = Op->getValueType(0).getScalarSizeInBits();
8667
8668 // Insert an extension before type-legalization to avoid scalarization, e.g.:
8669 // v2f64 = uint_to_fp v2i16
8670 // =>
8671 // v2f64 = uint_to_fp (v2i64 zero_extend v2i16)
8672 if (OutLLVMTy->isVectorTy() && OutScalarBits > InScalarBits &&
8673 OutScalarBits <= 64) {
8674 unsigned NumElts = cast<FixedVectorType>(OutLLVMTy)->getNumElements();
8675 EVT ExtVT = EVT::getVectorVT(
8676 Ctx, EVT::getIntegerVT(Ctx, OutLLVMTy->getScalarSizeInBits()), NumElts);
8677 unsigned ExtOpcode =
8679 SDValue ExtOp = DAG.getNode(ExtOpcode, SDLoc(N), ExtVT, Op);
8680 return DAG.getNode(Opcode, SDLoc(N), OutVT, ExtOp);
8681 }
8682 return SDValue();
8683}
8684
8685SDValue SystemZTargetLowering::combineFCOPYSIGN(
8686 SDNode *N, DAGCombinerInfo &DCI) const {
8687 SelectionDAG &DAG = DCI.DAG;
8688 EVT VT = N->getValueType(0);
8689 SDValue ValOp = N->getOperand(0);
8690 SDValue SignOp = N->getOperand(1);
8691
8692 // Remove the rounding which is not needed.
8693 if (SignOp.getOpcode() == ISD::FP_ROUND) {
8694 SDValue WideOp = SignOp.getOperand(0);
8695 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, ValOp, WideOp);
8696 }
8697
8698 return SDValue();
8699}
8700
8701SDValue SystemZTargetLowering::combineBSWAP(
8702 SDNode *N, DAGCombinerInfo &DCI) const {
8703 SelectionDAG &DAG = DCI.DAG;
8704 // Combine BSWAP (LOAD) into LRVH/LRV/LRVG/VLBR
8705 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8706 N->getOperand(0).hasOneUse() &&
8707 canLoadStoreByteSwapped(N->getValueType(0))) {
8708 SDValue Load = N->getOperand(0);
8709 LoadSDNode *LD = cast<LoadSDNode>(Load);
8710
8711 // Create the byte-swapping load.
8712 SDValue Ops[] = {
8713 LD->getChain(), // Chain
8714 LD->getBasePtr() // Ptr
8715 };
8716 EVT LoadVT = N->getValueType(0);
8717 if (LoadVT == MVT::i16)
8718 LoadVT = MVT::i32;
8719 SDValue BSLoad =
8720 DAG.getMemIntrinsicNode(SystemZISD::LRV, SDLoc(N),
8721 DAG.getVTList(LoadVT, MVT::Other),
8722 Ops, LD->getMemoryVT(), LD->getMemOperand());
8723
8724 // If this is an i16 load, insert the truncate.
8725 SDValue ResVal = BSLoad;
8726 if (N->getValueType(0) == MVT::i16)
8727 ResVal = DAG.getNode(ISD::TRUNCATE, SDLoc(N), MVT::i16, BSLoad);
8728
8729 // First, combine the bswap away. This makes the value produced by the
8730 // load dead.
8731 DCI.CombineTo(N, ResVal);
8732
8733 // Next, combine the load away, we give it a bogus result value but a real
8734 // chain result. The result value is dead because the bswap is dead.
8735 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8736
8737 // Return N so it doesn't get rechecked!
8738 return SDValue(N, 0);
8739 }
8740
8741 // Look through bitcasts that retain the number of vector elements.
8742 SDValue Op = N->getOperand(0);
8743 if (Op.getOpcode() == ISD::BITCAST &&
8744 Op.getValueType().isVector() &&
8745 Op.getOperand(0).getValueType().isVector() &&
8746 Op.getValueType().getVectorNumElements() ==
8747 Op.getOperand(0).getValueType().getVectorNumElements())
8748 Op = Op.getOperand(0);
8749
8750 // Push BSWAP into a vector insertion if at least one side then simplifies.
8751 if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT && Op.hasOneUse()) {
8752 SDValue Vec = Op.getOperand(0);
8753 SDValue Elt = Op.getOperand(1);
8754 SDValue Idx = Op.getOperand(2);
8755
8757 Vec.getOpcode() == ISD::BSWAP || Vec.isUndef() ||
8759 Elt.getOpcode() == ISD::BSWAP || Elt.isUndef() ||
8760 (canLoadStoreByteSwapped(N->getValueType(0)) &&
8761 ISD::isNON_EXTLoad(Elt.getNode()) && Elt.hasOneUse())) {
8762 EVT VecVT = N->getValueType(0);
8763 EVT EltVT = N->getValueType(0).getVectorElementType();
8764 if (VecVT != Vec.getValueType()) {
8765 Vec = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Vec);
8766 DCI.AddToWorklist(Vec.getNode());
8767 }
8768 if (EltVT != Elt.getValueType()) {
8769 Elt = DAG.getNode(ISD::BITCAST, SDLoc(N), EltVT, Elt);
8770 DCI.AddToWorklist(Elt.getNode());
8771 }
8772 Vec = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Vec);
8773 DCI.AddToWorklist(Vec.getNode());
8774 Elt = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Elt);
8775 DCI.AddToWorklist(Elt.getNode());
8776 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VecVT,
8777 Vec, Elt, Idx);
8778 }
8779 }
8780
8781 // Push BSWAP into a vector shuffle if at least one side then simplifies.
8782 ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(Op);
8783 if (SV && Op.hasOneUse()) {
8784 SDValue Op0 = Op.getOperand(0);
8785 SDValue Op1 = Op.getOperand(1);
8786
8788 Op0.getOpcode() == ISD::BSWAP || Op0.isUndef() ||
8790 Op1.getOpcode() == ISD::BSWAP || Op1.isUndef()) {
8791 EVT VecVT = N->getValueType(0);
8792 if (VecVT != Op0.getValueType()) {
8793 Op0 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op0);
8794 DCI.AddToWorklist(Op0.getNode());
8795 }
8796 if (VecVT != Op1.getValueType()) {
8797 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op1);
8798 DCI.AddToWorklist(Op1.getNode());
8799 }
8800 Op0 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op0);
8801 DCI.AddToWorklist(Op0.getNode());
8802 Op1 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op1);
8803 DCI.AddToWorklist(Op1.getNode());
8804 return DAG.getVectorShuffle(VecVT, SDLoc(N), Op0, Op1, SV->getMask());
8805 }
8806 }
8807
8808 return SDValue();
8809}
8810
8811SDValue SystemZTargetLowering::combineSETCC(
8812 SDNode *N, DAGCombinerInfo &DCI) const {
8813 SelectionDAG &DAG = DCI.DAG;
8814 const ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
8815 const SDValue LHS = N->getOperand(0);
8816 const SDValue RHS = N->getOperand(1);
8817 bool CmpNull = isNullConstant(RHS);
8818 bool CmpAllOnes = isAllOnesConstant(RHS);
8819 EVT VT = N->getValueType(0);
8820 SDLoc DL(N);
8821
8822 // Match icmp_eq/ne(bitcast(icmp(X,Y)),0/-1) reduction patterns, and
8823 // change the outer compare to a i128 compare. This will normally
8824 // allow the reduction to be recognized in adjustICmp128, and even if
8825 // not, the i128 compare will still generate better code.
8826 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && (CmpNull || CmpAllOnes)) {
8827 SDValue Src = peekThroughBitcasts(LHS);
8828 if (Src.getOpcode() == ISD::SETCC &&
8829 Src.getValueType().isFixedLengthVector() &&
8830 Src.getValueType().getScalarType() == MVT::i1) {
8831 EVT CmpVT = Src.getOperand(0).getValueType();
8832 if (CmpVT.getSizeInBits() == 128) {
8833 EVT IntVT = CmpVT.changeVectorElementTypeToInteger();
8834 SDValue LHS =
8835 DAG.getBitcast(MVT::i128, DAG.getSExtOrTrunc(Src, DL, IntVT));
8836 SDValue RHS = CmpNull ? DAG.getConstant(0, DL, MVT::i128)
8837 : DAG.getAllOnesConstant(DL, MVT::i128);
8838 return DAG.getNode(ISD::SETCC, DL, VT, LHS, RHS, N->getOperand(2),
8839 N->getFlags());
8840 }
8841 }
8842 }
8843
8844 return SDValue();
8845}
8846
8847static std::pair<SDValue, int> findCCUse(const SDValue &Val,
8848 unsigned Depth = 0) {
8849 // Limit depth of potentially exponential walk.
8850 if (Depth > 5)
8851 return std::make_pair(SDValue(), SystemZ::CCMASK_NONE);
8852
8853 switch (Val.getOpcode()) {
8854 default:
8855 return std::make_pair(SDValue(), SystemZ::CCMASK_NONE);
8856 case SystemZISD::IPM:
8857 if (Val.getOperand(0).getOpcode() == SystemZISD::CLC ||
8858 Val.getOperand(0).getOpcode() == SystemZISD::STRCMP)
8859 return std::make_pair(Val.getOperand(0), SystemZ::CCMASK_ICMP);
8860 return std::make_pair(Val.getOperand(0), SystemZ::CCMASK_ANY);
8861 case SystemZISD::SELECT_CCMASK: {
8862 SDValue Op4CCReg = Val.getOperand(4);
8863 if (Op4CCReg.getOpcode() == SystemZISD::ICMP ||
8864 Op4CCReg.getOpcode() == SystemZISD::TM) {
8865 auto [OpCC, OpCCValid] = findCCUse(Op4CCReg.getOperand(0), Depth + 1);
8866 if (OpCC != SDValue())
8867 return std::make_pair(OpCC, OpCCValid);
8868 }
8869 auto *CCValid = dyn_cast<ConstantSDNode>(Val.getOperand(2));
8870 if (!CCValid)
8871 return std::make_pair(SDValue(), SystemZ::CCMASK_NONE);
8872 int CCValidVal = CCValid->getZExtValue();
8873 return std::make_pair(Op4CCReg, CCValidVal);
8874 }
8875 case ISD::ADD:
8876 case ISD::AND:
8877 case ISD::OR:
8878 case ISD::XOR:
8879 case ISD::SHL:
8880 case ISD::SRA:
8881 case ISD::SRL:
8882 auto [Op0CC, Op0CCValid] = findCCUse(Val.getOperand(0), Depth + 1);
8883 if (Op0CC != SDValue())
8884 return std::make_pair(Op0CC, Op0CCValid);
8885 return findCCUse(Val.getOperand(1), Depth + 1);
8886 }
8887}
8888
8889static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask,
8890 SelectionDAG &DAG);
8891
8893 SelectionDAG &DAG) {
8894 SDLoc DL(Val);
8895 auto Opcode = Val.getOpcode();
8896 switch (Opcode) {
8897 default:
8898 return {};
8899 case ISD::Constant:
8900 return {Val, Val, Val, Val};
8901 case SystemZISD::IPM: {
8902 SDValue IPMOp0 = Val.getOperand(0);
8903 if (IPMOp0 != CC)
8904 return {};
8905 SmallVector<SDValue, 4> ShiftedCCVals;
8906 for (auto CC : {0, 1, 2, 3})
8907 ShiftedCCVals.emplace_back(
8908 DAG.getConstant((CC << SystemZ::IPM_CC), DL, MVT::i32));
8909 return ShiftedCCVals;
8910 }
8911 case SystemZISD::SELECT_CCMASK: {
8912 SDValue TrueVal = Val.getOperand(0), FalseVal = Val.getOperand(1);
8913 auto *CCValid = dyn_cast<ConstantSDNode>(Val.getOperand(2));
8914 auto *CCMask = dyn_cast<ConstantSDNode>(Val.getOperand(3));
8915 if (!CCValid || !CCMask)
8916 return {};
8917
8918 int CCValidVal = CCValid->getZExtValue();
8919 int CCMaskVal = CCMask->getZExtValue();
8920 // Pruning search tree early - Moving CC test and combineCCMask ahead of
8921 // recursive call to simplifyAssumingCCVal.
8922 SDValue Op4CCReg = Val.getOperand(4);
8923 if (Op4CCReg != CC)
8924 combineCCMask(Op4CCReg, CCValidVal, CCMaskVal, DAG);
8925 if (Op4CCReg != CC)
8926 return {};
8927 const auto &&TrueSDVals = simplifyAssumingCCVal(TrueVal, CC, DAG);
8928 const auto &&FalseSDVals = simplifyAssumingCCVal(FalseVal, CC, DAG);
8929 if (TrueSDVals.empty() || FalseSDVals.empty())
8930 return {};
8931 SmallVector<SDValue, 4> MergedSDVals;
8932 for (auto &CCVal : {0, 1, 2, 3})
8933 MergedSDVals.emplace_back(((CCMaskVal & (1 << (3 - CCVal))) != 0)
8934 ? TrueSDVals[CCVal]
8935 : FalseSDVals[CCVal]);
8936 return MergedSDVals;
8937 }
8938 case ISD::ADD:
8939 case ISD::AND:
8940 case ISD::OR:
8941 case ISD::XOR:
8942 case ISD::SRA:
8943 // Avoid introducing CC spills (because ADD/AND/OR/XOR/SRA
8944 // would clobber CC).
8945 if (!Val.hasOneUse())
8946 return {};
8947 [[fallthrough]];
8948 case ISD::SHL:
8949 case ISD::SRL:
8950 SDValue Op0 = Val.getOperand(0), Op1 = Val.getOperand(1);
8951 const auto &&Op0SDVals = simplifyAssumingCCVal(Op0, CC, DAG);
8952 const auto &&Op1SDVals = simplifyAssumingCCVal(Op1, CC, DAG);
8953 if (Op0SDVals.empty() || Op1SDVals.empty())
8954 return {};
8955 SmallVector<SDValue, 4> BinaryOpSDVals;
8956 for (auto CCVal : {0, 1, 2, 3})
8957 BinaryOpSDVals.emplace_back(DAG.getNode(
8958 Opcode, DL, Val.getValueType(), Op0SDVals[CCVal], Op1SDVals[CCVal]));
8959 return BinaryOpSDVals;
8960 }
8961}
8962
8963static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask,
8964 SelectionDAG &DAG) {
8965 // We have a SELECT_CCMASK or BR_CCMASK comparing the condition code
8966 // set by the CCReg instruction using the CCValid / CCMask masks,
8967 // If the CCReg instruction is itself a ICMP / TM testing the condition
8968 // code set by some other instruction, see whether we can directly
8969 // use that condition code.
8970 auto *CCNode = CCReg.getNode();
8971 if (!CCNode)
8972 return false;
8973
8974 if (CCNode->getOpcode() == SystemZISD::TM) {
8975 if (CCValid != SystemZ::CCMASK_TM)
8976 return false;
8977 auto emulateTMCCMask = [](const SDValue &Op0Val, const SDValue &Op1Val) {
8978 auto *Op0Node = dyn_cast<ConstantSDNode>(Op0Val.getNode());
8979 auto *Op1Node = dyn_cast<ConstantSDNode>(Op1Val.getNode());
8980 if (!Op0Node || !Op1Node)
8981 return -1;
8982 auto Op0APVal = Op0Node->getAPIntValue();
8983 auto Op1APVal = Op1Node->getAPIntValue();
8984 auto Result = Op0APVal & Op1APVal;
8985 bool AllOnes = Result == Op1APVal;
8986 bool AllZeros = Result == 0;
8987 bool IsLeftMostBitSet = Result[Op1APVal.getActiveBits() - 1] != 0;
8988 return AllZeros ? 0 : AllOnes ? 3 : IsLeftMostBitSet ? 2 : 1;
8989 };
8990 SDValue Op0 = CCNode->getOperand(0);
8991 SDValue Op1 = CCNode->getOperand(1);
8992 auto [Op0CC, Op0CCValid] = findCCUse(Op0);
8993 if (Op0CC == SDValue())
8994 return false;
8995 const auto &&Op0SDVals = simplifyAssumingCCVal(Op0, Op0CC, DAG);
8996 const auto &&Op1SDVals = simplifyAssumingCCVal(Op1, Op0CC, DAG);
8997 if (Op0SDVals.empty() || Op1SDVals.empty())
8998 return false;
8999 int NewCCMask = 0;
9000 for (auto CC : {0, 1, 2, 3}) {
9001 auto CCVal = emulateTMCCMask(Op0SDVals[CC], Op1SDVals[CC]);
9002 if (CCVal < 0)
9003 return false;
9004 NewCCMask <<= 1;
9005 NewCCMask |= (CCMask & (1 << (3 - CCVal))) != 0;
9006 }
9007 NewCCMask &= Op0CCValid;
9008 CCReg = Op0CC;
9009 CCMask = NewCCMask;
9010 CCValid = Op0CCValid;
9011 return true;
9012 }
9013 if (CCNode->getOpcode() != SystemZISD::ICMP ||
9014 CCValid != SystemZ::CCMASK_ICMP)
9015 return false;
9016
9017 SDValue CmpOp0 = CCNode->getOperand(0);
9018 SDValue CmpOp1 = CCNode->getOperand(1);
9019 SDValue CmpOp2 = CCNode->getOperand(2);
9020 auto [Op0CC, Op0CCValid] = findCCUse(CmpOp0);
9021 if (Op0CC != SDValue()) {
9022 const auto &&Op0SDVals = simplifyAssumingCCVal(CmpOp0, Op0CC, DAG);
9023 const auto &&Op1SDVals = simplifyAssumingCCVal(CmpOp1, Op0CC, DAG);
9024 if (Op0SDVals.empty() || Op1SDVals.empty())
9025 return false;
9026
9027 auto *CmpType = dyn_cast<ConstantSDNode>(CmpOp2);
9028 auto CmpTypeVal = CmpType->getZExtValue();
9029 const auto compareCCSigned = [&CmpTypeVal](const SDValue &Op0Val,
9030 const SDValue &Op1Val) {
9031 auto *Op0Node = dyn_cast<ConstantSDNode>(Op0Val.getNode());
9032 auto *Op1Node = dyn_cast<ConstantSDNode>(Op1Val.getNode());
9033 if (!Op0Node || !Op1Node)
9034 return -1;
9035 auto Op0APVal = Op0Node->getAPIntValue();
9036 auto Op1APVal = Op1Node->getAPIntValue();
9037 if (CmpTypeVal == SystemZICMP::SignedOnly)
9038 return Op0APVal == Op1APVal ? 0 : Op0APVal.slt(Op1APVal) ? 1 : 2;
9039 return Op0APVal == Op1APVal ? 0 : Op0APVal.ult(Op1APVal) ? 1 : 2;
9040 };
9041 int NewCCMask = 0;
9042 for (auto CC : {0, 1, 2, 3}) {
9043 auto CCVal = compareCCSigned(Op0SDVals[CC], Op1SDVals[CC]);
9044 if (CCVal < 0)
9045 return false;
9046 NewCCMask <<= 1;
9047 NewCCMask |= (CCMask & (1 << (3 - CCVal))) != 0;
9048 }
9049 NewCCMask &= Op0CCValid;
9050 CCMask = NewCCMask;
9051 CCReg = Op0CC;
9052 CCValid = Op0CCValid;
9053 return true;
9054 }
9055
9056 return false;
9057}
9058
9059// Merging versus split in multiple branches cost.
9062 const Value *Lhs,
9063 const Value *Rhs,
9064 const Function *) const {
9065 const auto isFlagOutOpCC = [](const Value *V) {
9066 using namespace llvm::PatternMatch;
9067 const Value *RHSVal;
9068 const APInt *RHSC;
9069 if (const auto *I = dyn_cast<Instruction>(V)) {
9070 // PatternMatch.h provides concise tree-based pattern match of llvm IR.
9071 if (match(I->getOperand(0), m_And(m_Value(RHSVal), m_APInt(RHSC))) ||
9072 match(I, m_Cmp(m_Value(RHSVal), m_APInt(RHSC)))) {
9073 if (const auto *CB = dyn_cast<CallBase>(RHSVal)) {
9074 if (CB->isInlineAsm()) {
9075 const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
9076 return IA && IA->getConstraintString().contains("{@cc}");
9077 }
9078 }
9079 }
9080 }
9081 return false;
9082 };
9083 // Pattern (ICmp %asm) or (ICmp (And %asm)).
9084 // Cost of longest dependency chain (ICmp, And) is 2. CostThreshold or
9085 // BaseCost can be set >=2. If cost of instruction <= CostThreshold
9086 // conditionals will be merged or else conditionals will be split.
9087 if (isFlagOutOpCC(Lhs) && isFlagOutOpCC(Rhs))
9088 return {3, 0, -1};
9089 // Default.
9090 return {-1, -1, -1};
9091}
9092
9093SDValue SystemZTargetLowering::combineBR_CCMASK(SDNode *N,
9094 DAGCombinerInfo &DCI) const {
9095 SelectionDAG &DAG = DCI.DAG;
9096
9097 // Combine BR_CCMASK (ICMP (SELECT_CCMASK)) into a single BR_CCMASK.
9098 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1));
9099 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2));
9100 if (!CCValid || !CCMask)
9101 return SDValue();
9102
9103 int CCValidVal = CCValid->getZExtValue();
9104 int CCMaskVal = CCMask->getZExtValue();
9105 SDValue Chain = N->getOperand(0);
9106 SDValue CCReg = N->getOperand(4);
9107 // If combineCMask was able to merge or simplify ccvalid or ccmask, re-emit
9108 // the modified BR_CCMASK with the new values.
9109 // In order to avoid conditional branches with full or empty cc masks, do not
9110 // do this if ccmask is 0 or equal to ccvalid.
9111 if (combineCCMask(CCReg, CCValidVal, CCMaskVal, DAG) && CCMaskVal != 0 &&
9112 CCMaskVal != CCValidVal)
9113 return DAG.getNode(SystemZISD::BR_CCMASK, SDLoc(N), N->getValueType(0),
9114 Chain,
9115 DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32),
9116 DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32),
9117 N->getOperand(3), CCReg);
9118 return SDValue();
9119}
9120
9121SDValue SystemZTargetLowering::combineSELECT_CCMASK(
9122 SDNode *N, DAGCombinerInfo &DCI) const {
9123 SelectionDAG &DAG = DCI.DAG;
9124
9125 // Combine SELECT_CCMASK (ICMP (SELECT_CCMASK)) into a single SELECT_CCMASK.
9126 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(2));
9127 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(3));
9128 if (!CCValid || !CCMask)
9129 return SDValue();
9130
9131 int CCValidVal = CCValid->getZExtValue();
9132 int CCMaskVal = CCMask->getZExtValue();
9133 SDValue CCReg = N->getOperand(4);
9134
9135 bool IsCombinedCCReg = combineCCMask(CCReg, CCValidVal, CCMaskVal, DAG);
9136
9137 // Populate SDVals vector for each condition code ccval for given Val, which
9138 // can again be another nested select_ccmask with the same CC.
9139 const auto constructCCSDValsFromSELECT = [&CCReg](SDValue &Val) {
9140 if (Val.getOpcode() == SystemZISD::SELECT_CCMASK) {
9142 if (Val.getOperand(4) != CCReg)
9143 return SmallVector<SDValue, 4>{};
9144 SDValue TrueVal = Val.getOperand(0), FalseVal = Val.getOperand(1);
9145 auto *CCMask = dyn_cast<ConstantSDNode>(Val.getOperand(3));
9146 if (!CCMask)
9147 return SmallVector<SDValue, 4>{};
9148
9149 int CCMaskVal = CCMask->getZExtValue();
9150 for (auto &CC : {0, 1, 2, 3})
9151 Res.emplace_back(((CCMaskVal & (1 << (3 - CC))) != 0) ? TrueVal
9152 : FalseVal);
9153 return Res;
9154 }
9155 return SmallVector<SDValue, 4>{Val, Val, Val, Val};
9156 };
9157 // Attempting to optimize TrueVal/FalseVal in outermost select_ccmask either
9158 // with CCReg found by combineCCMask or original CCReg.
9159 SDValue TrueVal = N->getOperand(0);
9160 SDValue FalseVal = N->getOperand(1);
9161 auto &&TrueSDVals = simplifyAssumingCCVal(TrueVal, CCReg, DAG);
9162 auto &&FalseSDVals = simplifyAssumingCCVal(FalseVal, CCReg, DAG);
9163 // TrueSDVals/FalseSDVals might be empty in case of non-constant
9164 // TrueVal/FalseVal for select_ccmask, which can not be optimized further.
9165 if (TrueSDVals.empty())
9166 TrueSDVals = constructCCSDValsFromSELECT(TrueVal);
9167 if (FalseSDVals.empty())
9168 FalseSDVals = constructCCSDValsFromSELECT(FalseVal);
9169 if (!TrueSDVals.empty() && !FalseSDVals.empty()) {
9170 SmallSet<SDValue, 4> MergedSDValsSet;
9171 // Ignoring CC values outside CCValiid.
9172 for (auto CC : {0, 1, 2, 3}) {
9173 if ((CCValidVal & ((1 << (3 - CC)))) != 0)
9174 MergedSDValsSet.insert(((CCMaskVal & (1 << (3 - CC))) != 0)
9175 ? TrueSDVals[CC]
9176 : FalseSDVals[CC]);
9177 }
9178 if (MergedSDValsSet.size() == 1)
9179 return *MergedSDValsSet.begin();
9180 if (MergedSDValsSet.size() == 2) {
9181 auto BeginIt = MergedSDValsSet.begin();
9182 SDValue NewTrueVal = *BeginIt, NewFalseVal = *next(BeginIt);
9183 if (NewTrueVal == FalseVal || NewFalseVal == TrueVal)
9184 std::swap(NewTrueVal, NewFalseVal);
9185 int NewCCMask = 0;
9186 for (auto CC : {0, 1, 2, 3}) {
9187 NewCCMask <<= 1;
9188 NewCCMask |= ((CCMaskVal & (1 << (3 - CC))) != 0)
9189 ? (TrueSDVals[CC] == NewTrueVal)
9190 : (FalseSDVals[CC] == NewTrueVal);
9191 }
9192 CCMaskVal = NewCCMask;
9193 CCMaskVal &= CCValidVal;
9194 TrueVal = NewTrueVal;
9195 FalseVal = NewFalseVal;
9196 IsCombinedCCReg = true;
9197 }
9198 }
9199 // If the condition is trivially false or trivially true after
9200 // combineCCMask, just collapse this SELECT_CCMASK to the indicated value
9201 // (possibly modified by constructCCSDValsFromSELECT).
9202 if (CCMaskVal == 0)
9203 return FalseVal;
9204 if (CCMaskVal == CCValidVal)
9205 return TrueVal;
9206
9207 if (IsCombinedCCReg)
9208 return DAG.getNode(
9209 SystemZISD::SELECT_CCMASK, SDLoc(N), N->getValueType(0), TrueVal,
9210 FalseVal, DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32),
9211 DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32), CCReg);
9212
9213 return SDValue();
9214}
9215
9216SDValue SystemZTargetLowering::combineGET_CCMASK(
9217 SDNode *N, DAGCombinerInfo &DCI) const {
9218
9219 // Optimize away GET_CCMASK (SELECT_CCMASK) if the CC masks are compatible
9220 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1));
9221 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2));
9222 if (!CCValid || !CCMask)
9223 return SDValue();
9224 int CCValidVal = CCValid->getZExtValue();
9225 int CCMaskVal = CCMask->getZExtValue();
9226
9227 SDValue Select = N->getOperand(0);
9228 if (Select->getOpcode() == ISD::TRUNCATE)
9229 Select = Select->getOperand(0);
9230 if (Select->getOpcode() != SystemZISD::SELECT_CCMASK)
9231 return SDValue();
9232
9233 auto *SelectCCValid = dyn_cast<ConstantSDNode>(Select->getOperand(2));
9234 auto *SelectCCMask = dyn_cast<ConstantSDNode>(Select->getOperand(3));
9235 if (!SelectCCValid || !SelectCCMask)
9236 return SDValue();
9237 int SelectCCValidVal = SelectCCValid->getZExtValue();
9238 int SelectCCMaskVal = SelectCCMask->getZExtValue();
9239
9240 auto *TrueVal = dyn_cast<ConstantSDNode>(Select->getOperand(0));
9241 auto *FalseVal = dyn_cast<ConstantSDNode>(Select->getOperand(1));
9242 if (!TrueVal || !FalseVal)
9243 return SDValue();
9244 if (TrueVal->getZExtValue() == 1 && FalseVal->getZExtValue() == 0)
9245 ;
9246 else if (TrueVal->getZExtValue() == 0 && FalseVal->getZExtValue() == 1)
9247 SelectCCMaskVal ^= SelectCCValidVal;
9248 else
9249 return SDValue();
9250
9251 if (SelectCCValidVal & ~CCValidVal)
9252 return SDValue();
9253 if (SelectCCMaskVal != (CCMaskVal & SelectCCValidVal))
9254 return SDValue();
9255
9256 return Select->getOperand(4);
9257}
9258
9259SDValue SystemZTargetLowering::combineIntDIVREM(
9260 SDNode *N, DAGCombinerInfo &DCI) const {
9261 SelectionDAG &DAG = DCI.DAG;
9262 EVT VT = N->getValueType(0);
9263 // In the case where the divisor is a vector of constants a cheaper
9264 // sequence of instructions can replace the divide. BuildSDIV is called to
9265 // do this during DAG combining, but it only succeeds when it can build a
9266 // multiplication node. The only option for SystemZ is ISD::SMUL_LOHI, and
9267 // since it is not Legal but Custom it can only happen before
9268 // legalization. Therefore we must scalarize this early before Combine
9269 // 1. For widened vectors, this is already the result of type legalization.
9270 if (DCI.Level == BeforeLegalizeTypes && VT.isVector() && isTypeLegal(VT) &&
9271 DAG.isConstantIntBuildVectorOrConstantInt(N->getOperand(1)))
9272 return DAG.UnrollVectorOp(N);
9273 return SDValue();
9274}
9275
9276
9277// Transform a right shift of a multiply-and-add into a multiply-and-add-high.
9278// This is closely modeled after the common-code combineShiftToMULH.
9279SDValue SystemZTargetLowering::combineShiftToMulAddHigh(
9280 SDNode *N, DAGCombinerInfo &DCI) const {
9281 SelectionDAG &DAG = DCI.DAG;
9282 SDLoc DL(N);
9283
9284 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
9285 "SRL or SRA node is required here!");
9286
9287 if (!Subtarget.hasVector())
9288 return SDValue();
9289
9290 // Check the shift amount. Proceed with the transformation if the shift
9291 // amount is constant.
9292 ConstantSDNode *ShiftAmtSrc = isConstOrConstSplat(N->getOperand(1));
9293 if (!ShiftAmtSrc)
9294 return SDValue();
9295
9296 // The operation feeding into the shift must be an add.
9297 SDValue ShiftOperand = N->getOperand(0);
9298 if (ShiftOperand.getOpcode() != ISD::ADD)
9299 return SDValue();
9300
9301 // One operand of the add must be a multiply.
9302 SDValue MulOp = ShiftOperand.getOperand(0);
9303 SDValue AddOp = ShiftOperand.getOperand(1);
9304 if (MulOp.getOpcode() != ISD::MUL) {
9305 if (AddOp.getOpcode() != ISD::MUL)
9306 return SDValue();
9307 std::swap(MulOp, AddOp);
9308 }
9309
9310 // All operands must be equivalent extend nodes.
9311 SDValue LeftOp = MulOp.getOperand(0);
9312 SDValue RightOp = MulOp.getOperand(1);
9313
9314 bool IsSignExt = LeftOp.getOpcode() == ISD::SIGN_EXTEND;
9315 bool IsZeroExt = LeftOp.getOpcode() == ISD::ZERO_EXTEND;
9316
9317 if (!IsSignExt && !IsZeroExt)
9318 return SDValue();
9319
9320 EVT NarrowVT = LeftOp.getOperand(0).getValueType();
9321 unsigned NarrowVTSize = NarrowVT.getScalarSizeInBits();
9322
9323 SDValue MulhRightOp;
9324 if (ConstantSDNode *Constant = isConstOrConstSplat(RightOp)) {
9325 unsigned ActiveBits = IsSignExt
9326 ? Constant->getAPIntValue().getSignificantBits()
9327 : Constant->getAPIntValue().getActiveBits();
9328 if (ActiveBits > NarrowVTSize)
9329 return SDValue();
9330 MulhRightOp = DAG.getConstant(
9331 Constant->getAPIntValue().trunc(NarrowVT.getScalarSizeInBits()), DL,
9332 NarrowVT);
9333 } else {
9334 if (LeftOp.getOpcode() != RightOp.getOpcode())
9335 return SDValue();
9336 // Check that the two extend nodes are the same type.
9337 if (NarrowVT != RightOp.getOperand(0).getValueType())
9338 return SDValue();
9339 MulhRightOp = RightOp.getOperand(0);
9340 }
9341
9342 SDValue MulhAddOp;
9343 if (ConstantSDNode *Constant = isConstOrConstSplat(AddOp)) {
9344 unsigned ActiveBits = IsSignExt
9345 ? Constant->getAPIntValue().getSignificantBits()
9346 : Constant->getAPIntValue().getActiveBits();
9347 if (ActiveBits > NarrowVTSize)
9348 return SDValue();
9349 MulhAddOp = DAG.getConstant(
9350 Constant->getAPIntValue().trunc(NarrowVT.getScalarSizeInBits()), DL,
9351 NarrowVT);
9352 } else {
9353 if (LeftOp.getOpcode() != AddOp.getOpcode())
9354 return SDValue();
9355 // Check that the two extend nodes are the same type.
9356 if (NarrowVT != AddOp.getOperand(0).getValueType())
9357 return SDValue();
9358 MulhAddOp = AddOp.getOperand(0);
9359 }
9360
9361 EVT WideVT = LeftOp.getValueType();
9362 // Proceed with the transformation if the wide types match.
9363 assert((WideVT == RightOp.getValueType()) &&
9364 "Cannot have a multiply node with two different operand types.");
9365 assert((WideVT == AddOp.getValueType()) &&
9366 "Cannot have an add node with two different operand types.");
9367
9368 // Proceed with the transformation if the wide type is twice as large
9369 // as the narrow type.
9370 if (WideVT.getScalarSizeInBits() != 2 * NarrowVTSize)
9371 return SDValue();
9372
9373 // Check the shift amount with the narrow type size.
9374 // Proceed with the transformation if the shift amount is the width
9375 // of the narrow type.
9376 unsigned ShiftAmt = ShiftAmtSrc->getZExtValue();
9377 if (ShiftAmt != NarrowVTSize)
9378 return SDValue();
9379
9380 // Proceed if we support the multiply-and-add-high operation.
9381 if (!(NarrowVT == MVT::v16i8 || NarrowVT == MVT::v8i16 ||
9382 NarrowVT == MVT::v4i32 ||
9383 (Subtarget.hasVectorEnhancements3() &&
9384 (NarrowVT == MVT::v2i64 || NarrowVT == MVT::i128))))
9385 return SDValue();
9386
9387 // Emit the VMAH (signed) or VMALH (unsigned) operation.
9388 SDValue Result = DAG.getNode(IsSignExt ? SystemZISD::VMAH : SystemZISD::VMALH,
9389 DL, NarrowVT, LeftOp.getOperand(0),
9390 MulhRightOp, MulhAddOp);
9391 bool IsSigned = N->getOpcode() == ISD::SRA;
9392 return DAG.getExtOrTrunc(IsSigned, Result, DL, WideVT);
9393}
9394
9395// Op is an operand of a multiplication. Check whether this can be folded
9396// into an even/odd widening operation; if so, return the opcode to be used
9397// and update Op to the appropriate sub-operand. Note that the caller must
9398// verify that *both* operands of the multiplication support the operation.
9400 const SystemZSubtarget &Subtarget,
9401 SDValue &Op) {
9402 EVT VT = Op.getValueType();
9403
9404 // Check for (sign/zero_extend_vector_inreg (vector_shuffle)) corresponding
9405 // to selecting the even or odd vector elements.
9406 if (VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
9407 (Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
9408 Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG)) {
9409 bool IsSigned = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
9410 unsigned NumElts = VT.getVectorNumElements();
9411 Op = Op.getOperand(0);
9412 if (Op.getValueType().getVectorNumElements() == 2 * NumElts &&
9413 Op.getOpcode() == ISD::VECTOR_SHUFFLE) {
9415 ArrayRef<int> ShuffleMask = SVN->getMask();
9416 bool CanUseEven = true, CanUseOdd = true;
9417 for (unsigned Elt = 0; Elt < NumElts; Elt++) {
9418 if (ShuffleMask[Elt] == -1)
9419 continue;
9420 if (unsigned(ShuffleMask[Elt]) != 2 * Elt)
9421 CanUseEven = false;
9422 if (unsigned(ShuffleMask[Elt]) != 2 * Elt + 1)
9423 CanUseOdd = false;
9424 }
9425 Op = Op.getOperand(0);
9426 if (CanUseEven)
9427 return IsSigned ? SystemZISD::VME : SystemZISD::VMLE;
9428 if (CanUseOdd)
9429 return IsSigned ? SystemZISD::VMO : SystemZISD::VMLO;
9430 }
9431 }
9432
9433 // For z17, we can also support the v2i64->i128 case, which looks like
9434 // (sign/zero_extend (extract_vector_elt X 0/1))
9435 if (VT == MVT::i128 && Subtarget.hasVectorEnhancements3() &&
9436 (Op.getOpcode() == ISD::SIGN_EXTEND ||
9437 Op.getOpcode() == ISD::ZERO_EXTEND)) {
9438 bool IsSigned = Op.getOpcode() == ISD::SIGN_EXTEND;
9439 Op = Op.getOperand(0);
9440 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9441 Op.getOperand(0).getValueType() == MVT::v2i64 &&
9442 Op.getOperand(1).getOpcode() == ISD::Constant) {
9443 unsigned Elem = Op.getConstantOperandVal(1);
9444 Op = Op.getOperand(0);
9445 if (Elem == 0)
9446 return IsSigned ? SystemZISD::VME : SystemZISD::VMLE;
9447 if (Elem == 1)
9448 return IsSigned ? SystemZISD::VMO : SystemZISD::VMLO;
9449 }
9450 }
9451
9452 return 0;
9453}
9454
9455SDValue SystemZTargetLowering::combineMUL(
9456 SDNode *N, DAGCombinerInfo &DCI) const {
9457 SelectionDAG &DAG = DCI.DAG;
9458
9459 // Detect even/odd widening multiplication.
9460 SDValue Op0 = N->getOperand(0);
9461 SDValue Op1 = N->getOperand(1);
9462 unsigned OpcodeCand0 = detectEvenOddMultiplyOperand(DAG, Subtarget, Op0);
9463 unsigned OpcodeCand1 = detectEvenOddMultiplyOperand(DAG, Subtarget, Op1);
9464 if (OpcodeCand0 && OpcodeCand0 == OpcodeCand1)
9465 return DAG.getNode(OpcodeCand0, SDLoc(N), N->getValueType(0), Op0, Op1);
9466
9467 return SDValue();
9468}
9469
9470SDValue SystemZTargetLowering::combineINTRINSIC(
9471 SDNode *N, DAGCombinerInfo &DCI) const {
9472 SelectionDAG &DAG = DCI.DAG;
9473
9474 unsigned Id = N->getConstantOperandVal(1);
9475 switch (Id) {
9476 // VECTOR LOAD (RIGHTMOST) WITH LENGTH with a length operand of 15
9477 // or larger is simply a vector load.
9478 case Intrinsic::s390_vll:
9479 case Intrinsic::s390_vlrl:
9480 if (auto *C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
9481 if (C->getZExtValue() >= 15)
9482 return DAG.getLoad(N->getValueType(0), SDLoc(N), N->getOperand(0),
9483 N->getOperand(3), MachinePointerInfo());
9484 break;
9485 // Likewise for VECTOR STORE (RIGHTMOST) WITH LENGTH.
9486 case Intrinsic::s390_vstl:
9487 case Intrinsic::s390_vstrl:
9488 if (auto *C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
9489 if (C->getZExtValue() >= 15)
9490 return DAG.getStore(N->getOperand(0), SDLoc(N), N->getOperand(2),
9491 N->getOperand(4), MachinePointerInfo());
9492 break;
9493 }
9494
9495 return SDValue();
9496}
9497
9498SDValue SystemZTargetLowering::unwrapAddress(SDValue N) const {
9499 if (N->getOpcode() == SystemZISD::PCREL_WRAPPER)
9500 return N->getOperand(0);
9501 return N;
9502}
9503
9505 DAGCombinerInfo &DCI) const {
9506 switch(N->getOpcode()) {
9507 default: break;
9508 case ISD::ZERO_EXTEND: return combineZERO_EXTEND(N, DCI);
9509 case ISD::SIGN_EXTEND: return combineSIGN_EXTEND(N, DCI);
9510 case ISD::SIGN_EXTEND_INREG: return combineSIGN_EXTEND_INREG(N, DCI);
9511 case SystemZISD::MERGE_HIGH:
9512 case SystemZISD::MERGE_LOW: return combineMERGE(N, DCI);
9513 case ISD::LOAD: return combineLOAD(N, DCI);
9514 case ISD::STORE: return combineSTORE(N, DCI);
9515 case ISD::VECTOR_SHUFFLE: return combineVECTOR_SHUFFLE(N, DCI);
9516 case ISD::EXTRACT_VECTOR_ELT: return combineEXTRACT_VECTOR_ELT(N, DCI);
9517 case SystemZISD::JOIN_DWORDS: return combineJOIN_DWORDS(N, DCI);
9519 case ISD::FP_ROUND: return combineFP_ROUND(N, DCI);
9521 case ISD::FP_EXTEND: return combineFP_EXTEND(N, DCI);
9522 case ISD::SINT_TO_FP:
9523 case ISD::UINT_TO_FP: return combineINT_TO_FP(N, DCI);
9524 case ISD::FCOPYSIGN: return combineFCOPYSIGN(N, DCI);
9525 case ISD::BSWAP: return combineBSWAP(N, DCI);
9526 case ISD::SETCC: return combineSETCC(N, DCI);
9527 case SystemZISD::BR_CCMASK: return combineBR_CCMASK(N, DCI);
9528 case SystemZISD::SELECT_CCMASK: return combineSELECT_CCMASK(N, DCI);
9529 case SystemZISD::GET_CCMASK: return combineGET_CCMASK(N, DCI);
9530 case ISD::SRL:
9531 case ISD::SRA: return combineShiftToMulAddHigh(N, DCI);
9532 case ISD::MUL: return combineMUL(N, DCI);
9533 case ISD::SDIV:
9534 case ISD::UDIV:
9535 case ISD::SREM:
9536 case ISD::UREM: return combineIntDIVREM(N, DCI);
9538 case ISD::INTRINSIC_VOID: return combineINTRINSIC(N, DCI);
9539 }
9540
9541 return SDValue();
9542}
9543
9544// Return the demanded elements for the OpNo source operand of Op. DemandedElts
9545// are for Op.
9546static APInt getDemandedSrcElements(SDValue Op, const APInt &DemandedElts,
9547 unsigned OpNo) {
9548 EVT VT = Op.getValueType();
9549 unsigned NumElts = (VT.isVector() ? VT.getVectorNumElements() : 1);
9550 APInt SrcDemE;
9551 unsigned Opcode = Op.getOpcode();
9552 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
9553 unsigned Id = Op.getConstantOperandVal(0);
9554 switch (Id) {
9555 case Intrinsic::s390_vpksh: // PACKS
9556 case Intrinsic::s390_vpksf:
9557 case Intrinsic::s390_vpksg:
9558 case Intrinsic::s390_vpkshs: // PACKS_CC
9559 case Intrinsic::s390_vpksfs:
9560 case Intrinsic::s390_vpksgs:
9561 case Intrinsic::s390_vpklsh: // PACKLS
9562 case Intrinsic::s390_vpklsf:
9563 case Intrinsic::s390_vpklsg:
9564 case Intrinsic::s390_vpklshs: // PACKLS_CC
9565 case Intrinsic::s390_vpklsfs:
9566 case Intrinsic::s390_vpklsgs:
9567 // VECTOR PACK truncates the elements of two source vectors into one.
9568 SrcDemE = DemandedElts;
9569 if (OpNo == 2)
9570 SrcDemE.lshrInPlace(NumElts / 2);
9571 SrcDemE = SrcDemE.trunc(NumElts / 2);
9572 break;
9573 // VECTOR UNPACK extends half the elements of the source vector.
9574 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
9575 case Intrinsic::s390_vuphh:
9576 case Intrinsic::s390_vuphf:
9577 case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH
9578 case Intrinsic::s390_vuplhh:
9579 case Intrinsic::s390_vuplhf:
9580 SrcDemE = APInt(NumElts * 2, 0);
9581 SrcDemE.insertBits(DemandedElts, 0);
9582 break;
9583 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
9584 case Intrinsic::s390_vuplhw:
9585 case Intrinsic::s390_vuplf:
9586 case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW
9587 case Intrinsic::s390_vupllh:
9588 case Intrinsic::s390_vupllf:
9589 SrcDemE = APInt(NumElts * 2, 0);
9590 SrcDemE.insertBits(DemandedElts, NumElts);
9591 break;
9592 case Intrinsic::s390_vpdi: {
9593 // VECTOR PERMUTE DWORD IMMEDIATE selects one element from each source.
9594 SrcDemE = APInt(NumElts, 0);
9595 if (!DemandedElts[OpNo - 1])
9596 break;
9597 unsigned Mask = Op.getConstantOperandVal(3);
9598 unsigned MaskBit = ((OpNo - 1) ? 1 : 4);
9599 // Demand input element 0 or 1, given by the mask bit value.
9600 SrcDemE.setBit((Mask & MaskBit)? 1 : 0);
9601 break;
9602 }
9603 case Intrinsic::s390_vsldb: {
9604 // VECTOR SHIFT LEFT DOUBLE BY BYTE
9605 assert(VT == MVT::v16i8 && "Unexpected type.");
9606 unsigned FirstIdx = Op.getConstantOperandVal(3);
9607 assert (FirstIdx > 0 && FirstIdx < 16 && "Unused operand.");
9608 unsigned NumSrc0Els = 16 - FirstIdx;
9609 SrcDemE = APInt(NumElts, 0);
9610 if (OpNo == 1) {
9611 APInt DemEls = DemandedElts.trunc(NumSrc0Els);
9612 SrcDemE.insertBits(DemEls, FirstIdx);
9613 } else {
9614 APInt DemEls = DemandedElts.lshr(NumSrc0Els);
9615 SrcDemE.insertBits(DemEls, 0);
9616 }
9617 break;
9618 }
9619 case Intrinsic::s390_vperm:
9620 SrcDemE = APInt::getAllOnes(NumElts);
9621 break;
9622 default:
9623 llvm_unreachable("Unhandled intrinsic.");
9624 break;
9625 }
9626 } else {
9627 switch (Opcode) {
9628 case SystemZISD::JOIN_DWORDS:
9629 // Scalar operand.
9630 SrcDemE = APInt(1, 1);
9631 break;
9632 case SystemZISD::SELECT_CCMASK:
9633 SrcDemE = DemandedElts;
9634 break;
9635 default:
9636 llvm_unreachable("Unhandled opcode.");
9637 break;
9638 }
9639 }
9640 return SrcDemE;
9641}
9642
9644 const APInt &DemandedElts,
9645 const SelectionDAG &DAG, unsigned Depth,
9646 unsigned OpNo) {
9647 APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo);
9648 APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1);
9649 KnownBits LHSKnown =
9650 DAG.computeKnownBits(Op.getOperand(OpNo), Src0DemE, Depth + 1);
9651 KnownBits RHSKnown =
9652 DAG.computeKnownBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1);
9653 Known = LHSKnown.intersectWith(RHSKnown);
9654}
9655
9656void
9659 const APInt &DemandedElts,
9660 const SelectionDAG &DAG,
9661 unsigned Depth) const {
9662 Known.resetAll();
9663
9664 // Intrinsic CC result is returned in the two low bits.
9665 unsigned Tmp0, Tmp1; // not used
9666 if (Op.getResNo() == 1 && isIntrinsicWithCC(Op, Tmp0, Tmp1)) {
9667 Known.Zero.setBitsFrom(2);
9668 return;
9669 }
9670 [[maybe_unused]] EVT VT = Op.getValueType();
9671 if (Op.getResNo() != 0)
9672 return;
9673 assert (Known.getBitWidth() == VT.getScalarSizeInBits() &&
9674 "KnownBits does not match VT in bitwidth");
9675 assert ((!VT.isVector() ||
9676 (DemandedElts.getBitWidth() == VT.getVectorNumElements())) &&
9677 "DemandedElts does not match VT number of elements");
9678 unsigned BitWidth = Known.getBitWidth();
9679 unsigned Opcode = Op.getOpcode();
9680 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
9681 bool IsLogical = false;
9682 unsigned Id = Op.getConstantOperandVal(0);
9683 switch (Id) {
9684 case Intrinsic::s390_vpksh: // PACKS
9685 case Intrinsic::s390_vpksf:
9686 case Intrinsic::s390_vpksg:
9687 case Intrinsic::s390_vpkshs: // PACKS_CC
9688 case Intrinsic::s390_vpksfs:
9689 case Intrinsic::s390_vpksgs:
9690 case Intrinsic::s390_vpklsh: // PACKLS
9691 case Intrinsic::s390_vpklsf:
9692 case Intrinsic::s390_vpklsg:
9693 case Intrinsic::s390_vpklshs: // PACKLS_CC
9694 case Intrinsic::s390_vpklsfs:
9695 case Intrinsic::s390_vpklsgs:
9696 case Intrinsic::s390_vpdi:
9697 case Intrinsic::s390_vsldb:
9698 case Intrinsic::s390_vperm:
9699 computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 1);
9700 break;
9701 case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH
9702 case Intrinsic::s390_vuplhh:
9703 case Intrinsic::s390_vuplhf:
9704 case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW
9705 case Intrinsic::s390_vupllh:
9706 case Intrinsic::s390_vupllf:
9707 IsLogical = true;
9708 [[fallthrough]];
9709 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
9710 case Intrinsic::s390_vuphh:
9711 case Intrinsic::s390_vuphf:
9712 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
9713 case Intrinsic::s390_vuplhw:
9714 case Intrinsic::s390_vuplf: {
9715 SDValue SrcOp = Op.getOperand(1);
9716 APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 0);
9717 Known = DAG.computeKnownBits(SrcOp, SrcDemE, Depth + 1);
9718 if (IsLogical) {
9719 Known = Known.zext(BitWidth);
9720 } else
9721 Known = Known.sext(BitWidth);
9722 break;
9723 }
9724 default:
9725 break;
9726 }
9727 } else {
9728 switch (Opcode) {
9729 case SystemZISD::JOIN_DWORDS:
9730 case SystemZISD::SELECT_CCMASK:
9731 computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 0);
9732 break;
9733 case SystemZISD::REPLICATE: {
9734 SDValue SrcOp = Op.getOperand(0);
9735 Known = DAG.computeKnownBits(SrcOp, Depth + 1);
9736 if (Known.getBitWidth() < BitWidth && isa<ConstantSDNode>(SrcOp))
9737 Known = Known.sext(BitWidth); // VREPI sign extends the immedate.
9738 break;
9739 }
9740 default:
9741 break;
9742 }
9743 }
9744
9745 // Known has the width of the source operand(s). Adjust if needed to match
9746 // the passed bitwidth.
9747 if (Known.getBitWidth() != BitWidth)
9748 Known = Known.anyextOrTrunc(BitWidth);
9749}
9750
9751static unsigned computeNumSignBitsBinOp(SDValue Op, const APInt &DemandedElts,
9752 const SelectionDAG &DAG, unsigned Depth,
9753 unsigned OpNo) {
9754 APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo);
9755 unsigned LHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo), Src0DemE, Depth + 1);
9756 if (LHS == 1) return 1; // Early out.
9757 APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1);
9758 unsigned RHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1);
9759 if (RHS == 1) return 1; // Early out.
9760 unsigned Common = std::min(LHS, RHS);
9761 unsigned SrcBitWidth = Op.getOperand(OpNo).getScalarValueSizeInBits();
9762 EVT VT = Op.getValueType();
9763 unsigned VTBits = VT.getScalarSizeInBits();
9764 if (SrcBitWidth > VTBits) { // PACK
9765 unsigned SrcExtraBits = SrcBitWidth - VTBits;
9766 if (Common > SrcExtraBits)
9767 return (Common - SrcExtraBits);
9768 return 1;
9769 }
9770 assert (SrcBitWidth == VTBits && "Expected operands of same bitwidth.");
9771 return Common;
9772}
9773
9774unsigned
9776 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9777 unsigned Depth) const {
9778 if (Op.getResNo() != 0)
9779 return 1;
9780 unsigned Opcode = Op.getOpcode();
9781 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
9782 unsigned Id = Op.getConstantOperandVal(0);
9783 switch (Id) {
9784 case Intrinsic::s390_vpksh: // PACKS
9785 case Intrinsic::s390_vpksf:
9786 case Intrinsic::s390_vpksg:
9787 case Intrinsic::s390_vpkshs: // PACKS_CC
9788 case Intrinsic::s390_vpksfs:
9789 case Intrinsic::s390_vpksgs:
9790 case Intrinsic::s390_vpklsh: // PACKLS
9791 case Intrinsic::s390_vpklsf:
9792 case Intrinsic::s390_vpklsg:
9793 case Intrinsic::s390_vpklshs: // PACKLS_CC
9794 case Intrinsic::s390_vpklsfs:
9795 case Intrinsic::s390_vpklsgs:
9796 case Intrinsic::s390_vpdi:
9797 case Intrinsic::s390_vsldb:
9798 case Intrinsic::s390_vperm:
9799 return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 1);
9800 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
9801 case Intrinsic::s390_vuphh:
9802 case Intrinsic::s390_vuphf:
9803 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
9804 case Intrinsic::s390_vuplhw:
9805 case Intrinsic::s390_vuplf: {
9806 SDValue PackedOp = Op.getOperand(1);
9807 APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 1);
9808 unsigned Tmp = DAG.ComputeNumSignBits(PackedOp, SrcDemE, Depth + 1);
9809 EVT VT = Op.getValueType();
9810 unsigned VTBits = VT.getScalarSizeInBits();
9811 Tmp += VTBits - PackedOp.getScalarValueSizeInBits();
9812 return Tmp;
9813 }
9814 default:
9815 break;
9816 }
9817 } else {
9818 switch (Opcode) {
9819 case SystemZISD::SELECT_CCMASK:
9820 return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 0);
9821 default:
9822 break;
9823 }
9824 }
9825
9826 return 1;
9827}
9828
9830 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9831 UndefPoisonKind Kind, unsigned Depth) const {
9832 switch (Op->getOpcode()) {
9833 case SystemZISD::PCREL_WRAPPER:
9834 case SystemZISD::PCREL_OFFSET:
9835 return true;
9836 }
9837 return false;
9838}
9839
9840unsigned
9842 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
9843 unsigned StackAlign = TFI->getStackAlignment();
9844 assert(StackAlign >=1 && isPowerOf2_32(StackAlign) &&
9845 "Unexpected stack alignment");
9846 // The default stack probe size is 4096 if the function has no
9847 // stack-probe-size attribute.
9848 unsigned StackProbeSize =
9849 MF.getFunction().getFnAttributeAsParsedInteger("stack-probe-size", 4096);
9850 // Round down to the stack alignment.
9851 StackProbeSize &= ~(StackAlign - 1);
9852 return StackProbeSize ? StackProbeSize : StackAlign;
9853}
9854
9855//===----------------------------------------------------------------------===//
9856// Custom insertion
9857//===----------------------------------------------------------------------===//
9858
9859// Force base value Base into a register before MI. Return the register.
9861 const SystemZInstrInfo *TII) {
9862 MachineBasicBlock *MBB = MI.getParent();
9863 MachineFunction &MF = *MBB->getParent();
9864 MachineRegisterInfo &MRI = MF.getRegInfo();
9865
9866 if (Base.isReg()) {
9867 // Copy Base into a new virtual register to help register coalescing in
9868 // cases with multiple uses.
9869 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
9870 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::COPY), Reg)
9871 .add(Base);
9872 return Reg;
9873 }
9874
9875 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
9876 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LA), Reg)
9877 .add(Base)
9878 .addImm(0)
9879 .addReg(0);
9880 return Reg;
9881}
9882
9883// The CC operand of MI might be missing a kill marker because there
9884// were multiple uses of CC, and ISel didn't know which to mark.
9885// Figure out whether MI should have had a kill marker.
9887 // Scan forward through BB for a use/def of CC.
9889 for (MachineBasicBlock::iterator miE = MBB->end(); miI != miE; ++miI) {
9890 const MachineInstr &MI = *miI;
9891 if (MI.readsRegister(SystemZ::CC, /*TRI=*/nullptr))
9892 return false;
9893 if (MI.definesRegister(SystemZ::CC, /*TRI=*/nullptr))
9894 break; // Should have kill-flag - update below.
9895 }
9896
9897 // If we hit the end of the block, check whether CC is live into a
9898 // successor.
9899 if (miI == MBB->end()) {
9900 for (const MachineBasicBlock *Succ : MBB->successors())
9901 if (Succ->isLiveIn(SystemZ::CC))
9902 return false;
9903 }
9904
9905 return true;
9906}
9907
9908// Return true if it is OK for this Select pseudo-opcode to be cascaded
9909// together with other Select pseudo-opcodes into a single basic-block with
9910// a conditional jump around it.
9912 switch (MI.getOpcode()) {
9913 case SystemZ::Select32:
9914 case SystemZ::Select64:
9915 case SystemZ::Select128:
9916 case SystemZ::SelectF32:
9917 case SystemZ::SelectF64:
9918 case SystemZ::SelectF128:
9919 case SystemZ::SelectVR32:
9920 case SystemZ::SelectVR64:
9921 case SystemZ::SelectVR128:
9922 return true;
9923
9924 default:
9925 return false;
9926 }
9927}
9928
9929// Helper function, which inserts PHI functions into SinkMBB:
9930// %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ],
9931// where %FalseValue(i) and %TrueValue(i) are taken from Selects.
9933 MachineBasicBlock *TrueMBB,
9934 MachineBasicBlock *FalseMBB,
9935 MachineBasicBlock *SinkMBB) {
9936 MachineFunction *MF = TrueMBB->getParent();
9938
9939 MachineInstr *FirstMI = Selects.front();
9940 unsigned CCValid = FirstMI->getOperand(3).getImm();
9941 unsigned CCMask = FirstMI->getOperand(4).getImm();
9942
9943 MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
9944
9945 // As we are creating the PHIs, we have to be careful if there is more than
9946 // one. Later Selects may reference the results of earlier Selects, but later
9947 // PHIs have to reference the individual true/false inputs from earlier PHIs.
9948 // That also means that PHI construction must work forward from earlier to
9949 // later, and that the code must maintain a mapping from earlier PHI's
9950 // destination registers, and the registers that went into the PHI.
9952
9953 for (auto *MI : Selects) {
9954 Register DestReg = MI->getOperand(0).getReg();
9955 Register TrueReg = MI->getOperand(1).getReg();
9956 Register FalseReg = MI->getOperand(2).getReg();
9957
9958 // If this Select we are generating is the opposite condition from
9959 // the jump we generated, then we have to swap the operands for the
9960 // PHI that is going to be generated.
9961 if (MI->getOperand(4).getImm() == (CCValid ^ CCMask))
9962 std::swap(TrueReg, FalseReg);
9963
9964 if (auto It = RegRewriteTable.find(TrueReg); It != RegRewriteTable.end())
9965 TrueReg = It->second.first;
9966
9967 if (auto It = RegRewriteTable.find(FalseReg); It != RegRewriteTable.end())
9968 FalseReg = It->second.second;
9969
9970 DebugLoc DL = MI->getDebugLoc();
9971 BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(SystemZ::PHI), DestReg)
9972 .addReg(TrueReg).addMBB(TrueMBB)
9973 .addReg(FalseReg).addMBB(FalseMBB);
9974
9975 // Add this PHI to the rewrite table.
9976 RegRewriteTable[DestReg] = std::make_pair(TrueReg, FalseReg);
9977 }
9978
9979 MF->getProperties().resetNoPHIs();
9980}
9981
9983SystemZTargetLowering::emitAdjCallStack(MachineInstr &MI,
9984 MachineBasicBlock *BB) const {
9985 MachineFunction &MF = *BB->getParent();
9986 MachineFrameInfo &MFI = MF.getFrameInfo();
9987 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
9988 assert(TFL->hasReservedCallFrame(MF) &&
9989 "ADJSTACKDOWN and ADJSTACKUP should be no-ops");
9990 (void)TFL;
9991 // Get the MaxCallFrameSize value and erase MI since it serves no further
9992 // purpose as the call frame is statically reserved in the prolog. Set
9993 // AdjustsStack as MI is *not* mapped as a frame instruction.
9994 uint32_t NumBytes = MI.getOperand(0).getImm();
9995 if (NumBytes > MFI.getMaxCallFrameSize())
9996 MFI.setMaxCallFrameSize(NumBytes);
9997 MFI.setAdjustsStack(true);
9998
9999 MI.eraseFromParent();
10000 return BB;
10001}
10002
10003// Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
10005SystemZTargetLowering::emitSelect(MachineInstr &MI,
10006 MachineBasicBlock *MBB) const {
10007 assert(isSelectPseudo(MI) && "Bad call to emitSelect()");
10008 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10009
10010 unsigned CCValid = MI.getOperand(3).getImm();
10011 unsigned CCMask = MI.getOperand(4).getImm();
10012
10013 // If we have a sequence of Select* pseudo instructions using the
10014 // same condition code value, we want to expand all of them into
10015 // a single pair of basic blocks using the same condition.
10016 SmallVector<MachineInstr*, 8> Selects;
10017 SmallVector<MachineInstr*, 8> DbgValues;
10018 Selects.push_back(&MI);
10019 unsigned Count = 0;
10020 for (MachineInstr &NextMI : llvm::make_range(
10021 std::next(MachineBasicBlock::iterator(MI)), MBB->end())) {
10022 if (isSelectPseudo(NextMI)) {
10023 assert(NextMI.getOperand(3).getImm() == CCValid &&
10024 "Bad CCValid operands since CC was not redefined.");
10025 if (NextMI.getOperand(4).getImm() == CCMask ||
10026 NextMI.getOperand(4).getImm() == (CCValid ^ CCMask)) {
10027 Selects.push_back(&NextMI);
10028 continue;
10029 }
10030 break;
10031 }
10032 if (NextMI.definesRegister(SystemZ::CC, /*TRI=*/nullptr) ||
10033 NextMI.usesCustomInsertionHook())
10034 break;
10035 bool User = false;
10036 for (auto *SelMI : Selects)
10037 if (NextMI.readsVirtualRegister(SelMI->getOperand(0).getReg())) {
10038 User = true;
10039 break;
10040 }
10041 if (NextMI.isDebugInstr()) {
10042 if (User) {
10043 assert(NextMI.isDebugValue() && "Unhandled debug opcode.");
10044 DbgValues.push_back(&NextMI);
10045 }
10046 } else if (User || ++Count > 20)
10047 break;
10048 }
10049
10050 MachineInstr *LastMI = Selects.back();
10051 bool CCKilled = (LastMI->killsRegister(SystemZ::CC, /*TRI=*/nullptr) ||
10052 checkCCKill(*LastMI, MBB));
10053 MachineBasicBlock *StartMBB = MBB;
10054 MachineBasicBlock *JoinMBB = SystemZ::splitBlockAfter(LastMI, MBB);
10055 MachineBasicBlock *FalseMBB = SystemZ::emitBlockAfter(StartMBB);
10056
10057 // Unless CC was killed in the last Select instruction, mark it as
10058 // live-in to both FalseMBB and JoinMBB.
10059 if (!CCKilled) {
10060 FalseMBB->addLiveIn(SystemZ::CC);
10061 JoinMBB->addLiveIn(SystemZ::CC);
10062 }
10063
10064 // StartMBB:
10065 // BRC CCMask, JoinMBB
10066 // # fallthrough to FalseMBB
10067 MBB = StartMBB;
10068 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::BRC))
10069 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
10070 MBB->addSuccessor(JoinMBB);
10071 MBB->addSuccessor(FalseMBB);
10072
10073 // FalseMBB:
10074 // # fallthrough to JoinMBB
10075 MBB = FalseMBB;
10076 MBB->addSuccessor(JoinMBB);
10077
10078 // JoinMBB:
10079 // %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
10080 // ...
10081 MBB = JoinMBB;
10082 createPHIsForSelects(Selects, StartMBB, FalseMBB, MBB);
10083 for (auto *SelMI : Selects)
10084 SelMI->eraseFromParent();
10085
10087 for (auto *DbgMI : DbgValues)
10088 MBB->splice(InsertPos, StartMBB, DbgMI);
10089
10090 return JoinMBB;
10091}
10092
10093// Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
10094// StoreOpcode is the store to use and Invert says whether the store should
10095// happen when the condition is false rather than true. If a STORE ON
10096// CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
10097MachineBasicBlock *SystemZTargetLowering::emitCondStore(MachineInstr &MI,
10099 unsigned StoreOpcode,
10100 unsigned STOCOpcode,
10101 bool Invert) const {
10102 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10103
10104 Register SrcReg = MI.getOperand(0).getReg();
10105 MachineOperand Base = MI.getOperand(1);
10106 int64_t Disp = MI.getOperand(2).getImm();
10107 Register IndexReg = MI.getOperand(3).getReg();
10108 unsigned CCValid = MI.getOperand(4).getImm();
10109 unsigned CCMask = MI.getOperand(5).getImm();
10110 DebugLoc DL = MI.getDebugLoc();
10111
10112 StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
10113
10114 // ISel pattern matching also adds a load memory operand of the same
10115 // address, so take special care to find the storing memory operand.
10116 MachineMemOperand *MMO = nullptr;
10117 for (auto *I : MI.memoperands())
10118 if (I->isStore()) {
10119 MMO = I;
10120 break;
10121 }
10122
10123 // Use STOCOpcode if possible. We could use different store patterns in
10124 // order to avoid matching the index register, but the performance trade-offs
10125 // might be more complicated in that case.
10126 if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) {
10127 if (Invert)
10128 CCMask ^= CCValid;
10129
10130 BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
10131 .addReg(SrcReg)
10132 .add(Base)
10133 .addImm(Disp)
10134 .addImm(CCValid)
10135 .addImm(CCMask)
10136 .addMemOperand(MMO);
10137
10138 MI.eraseFromParent();
10139 return MBB;
10140 }
10141
10142 // Get the condition needed to branch around the store.
10143 if (!Invert)
10144 CCMask ^= CCValid;
10145
10146 MachineBasicBlock *StartMBB = MBB;
10147 MachineBasicBlock *JoinMBB = SystemZ::splitBlockBefore(MI, MBB);
10148 MachineBasicBlock *FalseMBB = SystemZ::emitBlockAfter(StartMBB);
10149
10150 // Unless CC was killed in the CondStore instruction, mark it as
10151 // live-in to both FalseMBB and JoinMBB.
10152 if (!MI.killsRegister(SystemZ::CC, /*TRI=*/nullptr) &&
10153 !checkCCKill(MI, JoinMBB)) {
10154 FalseMBB->addLiveIn(SystemZ::CC);
10155 JoinMBB->addLiveIn(SystemZ::CC);
10156 }
10157
10158 // StartMBB:
10159 // BRC CCMask, JoinMBB
10160 // # fallthrough to FalseMBB
10161 MBB = StartMBB;
10162 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10163 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
10164 MBB->addSuccessor(JoinMBB);
10165 MBB->addSuccessor(FalseMBB);
10166
10167 // FalseMBB:
10168 // store %SrcReg, %Disp(%Index,%Base)
10169 // # fallthrough to JoinMBB
10170 MBB = FalseMBB;
10171 BuildMI(MBB, DL, TII->get(StoreOpcode))
10172 .addReg(SrcReg)
10173 .add(Base)
10174 .addImm(Disp)
10175 .addReg(IndexReg)
10176 .addMemOperand(MMO);
10177 MBB->addSuccessor(JoinMBB);
10178
10179 MI.eraseFromParent();
10180 return JoinMBB;
10181}
10182
10183// Implement EmitInstrWithCustomInserter for pseudo [SU]Cmp128Hi instruction MI.
10185SystemZTargetLowering::emitICmp128Hi(MachineInstr &MI,
10187 bool Unsigned) const {
10188 MachineFunction &MF = *MBB->getParent();
10189 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10190 MachineRegisterInfo &MRI = MF.getRegInfo();
10191
10192 // Synthetic instruction to compare 128-bit values.
10193 // Sets CC 1 if Op0 > Op1, sets a different CC otherwise.
10194 Register Op0 = MI.getOperand(0).getReg();
10195 Register Op1 = MI.getOperand(1).getReg();
10196
10197 MachineBasicBlock *StartMBB = MBB;
10198 MachineBasicBlock *JoinMBB = SystemZ::splitBlockAfter(MI, MBB);
10199 MachineBasicBlock *HiEqMBB = SystemZ::emitBlockAfter(StartMBB);
10200
10201 // StartMBB:
10202 //
10203 // Use VECTOR ELEMENT COMPARE [LOGICAL] to compare the high parts.
10204 // Swap the inputs to get:
10205 // CC 1 if high(Op0) > high(Op1)
10206 // CC 2 if high(Op0) < high(Op1)
10207 // CC 0 if high(Op0) == high(Op1)
10208 //
10209 // If CC != 0, we'd done, so jump over the next instruction.
10210 //
10211 // VEC[L]G Op1, Op0
10212 // JNE JoinMBB
10213 // # fallthrough to HiEqMBB
10214 MBB = StartMBB;
10215 int HiOpcode = Unsigned? SystemZ::VECLG : SystemZ::VECG;
10216 BuildMI(MBB, MI.getDebugLoc(), TII->get(HiOpcode))
10217 .addReg(Op1).addReg(Op0);
10218 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::BRC))
10220 MBB->addSuccessor(JoinMBB);
10221 MBB->addSuccessor(HiEqMBB);
10222
10223 // HiEqMBB:
10224 //
10225 // Otherwise, use VECTOR COMPARE HIGH LOGICAL.
10226 // Since we already know the high parts are equal, the CC
10227 // result will only depend on the low parts:
10228 // CC 1 if low(Op0) > low(Op1)
10229 // CC 3 if low(Op0) <= low(Op1)
10230 //
10231 // VCHLGS Tmp, Op0, Op1
10232 // # fallthrough to JoinMBB
10233 MBB = HiEqMBB;
10234 Register Temp = MRI.createVirtualRegister(&SystemZ::VR128BitRegClass);
10235 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::VCHLGS), Temp)
10236 .addReg(Op0).addReg(Op1);
10237 MBB->addSuccessor(JoinMBB);
10238
10239 // Mark CC as live-in to JoinMBB.
10240 JoinMBB->addLiveIn(SystemZ::CC);
10241
10242 MI.eraseFromParent();
10243 return JoinMBB;
10244}
10245
10246// Implement EmitInstrWithCustomInserter for subword pseudo ATOMIC_LOADW_* or
10247// ATOMIC_SWAPW instruction MI. BinOpcode is the instruction that performs
10248// the binary operation elided by "*", or 0 for ATOMIC_SWAPW. Invert says
10249// whether the field should be inverted after performing BinOpcode (e.g. for
10250// NAND).
10251MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadBinary(
10252 MachineInstr &MI, MachineBasicBlock *MBB, unsigned BinOpcode,
10253 bool Invert) const {
10254 MachineFunction &MF = *MBB->getParent();
10255 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10256 MachineRegisterInfo &MRI = MF.getRegInfo();
10257
10258 // Extract the operands. Base can be a register or a frame index.
10259 // Src2 can be a register or immediate.
10260 Register Dest = MI.getOperand(0).getReg();
10261 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
10262 int64_t Disp = MI.getOperand(2).getImm();
10263 MachineOperand Src2 = earlyUseOperand(MI.getOperand(3));
10264 Register BitShift = MI.getOperand(4).getReg();
10265 Register NegBitShift = MI.getOperand(5).getReg();
10266 unsigned BitSize = MI.getOperand(6).getImm();
10267 DebugLoc DL = MI.getDebugLoc();
10268
10269 // Get the right opcodes for the displacement.
10270 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
10271 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
10272 assert(LOpcode && CSOpcode && "Displacement out of range");
10273
10274 // Create virtual registers for temporary results.
10275 Register OrigVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10276 Register OldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10277 Register NewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10278 Register RotatedOldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10279 Register RotatedNewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10280
10281 // Insert a basic block for the main loop.
10282 MachineBasicBlock *StartMBB = MBB;
10283 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10284 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10285
10286 // StartMBB:
10287 // ...
10288 // %OrigVal = L Disp(%Base)
10289 // # fall through to LoopMBB
10290 MBB = StartMBB;
10291 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
10292 MBB->addSuccessor(LoopMBB);
10293
10294 // LoopMBB:
10295 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
10296 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
10297 // %RotatedNewVal = OP %RotatedOldVal, %Src2
10298 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
10299 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
10300 // JNE LoopMBB
10301 // # fall through to DoneMBB
10302 MBB = LoopMBB;
10303 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
10304 .addReg(OrigVal).addMBB(StartMBB)
10305 .addReg(Dest).addMBB(LoopMBB);
10306 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
10307 .addReg(OldVal).addReg(BitShift).addImm(0);
10308 if (Invert) {
10309 // Perform the operation normally and then invert every bit of the field.
10310 Register Tmp = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10311 BuildMI(MBB, DL, TII->get(BinOpcode), Tmp)
10312 .addReg(RotatedOldVal)
10313 .add(Src2)
10314 .setOperandDead(3);
10315 // XILF with the upper BitSize bits set.
10316 BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
10317 .addReg(Tmp)
10318 .addImm(-1U << (32 - BitSize))
10319 .setOperandDead(3);
10320 } else if (BinOpcode)
10321 // A simply binary operation.
10322 BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
10323 .addReg(RotatedOldVal)
10324 .add(Src2)
10325 .setOperandDead(3);
10326 else
10327 // Use RISBG to rotate Src2 into position and use it to replace the
10328 // field in RotatedOldVal.
10329 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
10330 .addReg(RotatedOldVal)
10331 .addReg(Src2.getReg())
10332 .addImm(32)
10333 .addImm(31 + BitSize)
10334 .addImm(32 - BitSize)
10335 .setOperandDead(6);
10336 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
10337 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
10338 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
10339 .addReg(OldVal)
10340 .addReg(NewVal)
10341 .add(Base)
10342 .addImm(Disp);
10343 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10345 MBB->addSuccessor(LoopMBB);
10346 MBB->addSuccessor(DoneMBB);
10347
10348 MI.eraseFromParent();
10349 return DoneMBB;
10350}
10351
10352// Implement EmitInstrWithCustomInserter for subword pseudo
10353// ATOMIC_LOADW_{,U}{MIN,MAX} instruction MI. CompareOpcode is the
10354// instruction that should be used to compare the current field with the
10355// minimum or maximum value. KeepOldMask is the BRC condition-code mask
10356// for when the current field should be kept.
10357MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadMinMax(
10358 MachineInstr &MI, MachineBasicBlock *MBB, unsigned CompareOpcode,
10359 unsigned KeepOldMask) 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 Register Dest = MI.getOperand(0).getReg();
10366 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
10367 int64_t Disp = MI.getOperand(2).getImm();
10368 Register Src2 = MI.getOperand(3).getReg();
10369 Register BitShift = MI.getOperand(4).getReg();
10370 Register NegBitShift = MI.getOperand(5).getReg();
10371 unsigned BitSize = MI.getOperand(6).getImm();
10372 DebugLoc DL = MI.getDebugLoc();
10373
10374 // Get the right opcodes for the displacement.
10375 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
10376 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
10377 assert(LOpcode && CSOpcode && "Displacement out of range");
10378
10379 // Create virtual registers for temporary results.
10380 Register OrigVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10381 Register OldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10382 Register NewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10383 Register RotatedOldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10384 Register RotatedAltVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10385 Register RotatedNewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10386
10387 // Insert 3 basic blocks for the loop.
10388 MachineBasicBlock *StartMBB = MBB;
10389 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10390 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10391 MachineBasicBlock *UseAltMBB = SystemZ::emitBlockAfter(LoopMBB);
10392 MachineBasicBlock *UpdateMBB = SystemZ::emitBlockAfter(UseAltMBB);
10393
10394 // StartMBB:
10395 // ...
10396 // %OrigVal = L Disp(%Base)
10397 // # fall through to LoopMBB
10398 MBB = StartMBB;
10399 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
10400 MBB->addSuccessor(LoopMBB);
10401
10402 // LoopMBB:
10403 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
10404 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
10405 // CompareOpcode %RotatedOldVal, %Src2
10406 // BRC KeepOldMask, UpdateMBB
10407 MBB = LoopMBB;
10408 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
10409 .addReg(OrigVal).addMBB(StartMBB)
10410 .addReg(Dest).addMBB(UpdateMBB);
10411 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
10412 .addReg(OldVal).addReg(BitShift).addImm(0);
10413 BuildMI(MBB, DL, TII->get(CompareOpcode))
10414 .addReg(RotatedOldVal).addReg(Src2);
10415 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10416 .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
10417 MBB->addSuccessor(UpdateMBB);
10418 MBB->addSuccessor(UseAltMBB);
10419
10420 // UseAltMBB:
10421 // %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
10422 // # fall through to UpdateMBB
10423 MBB = UseAltMBB;
10424 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
10425 .addReg(RotatedOldVal)
10426 .addReg(Src2)
10427 .addImm(32)
10428 .addImm(31 + BitSize)
10429 .addImm(0)
10430 .setOperandDead(6);
10431 MBB->addSuccessor(UpdateMBB);
10432
10433 // UpdateMBB:
10434 // %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
10435 // [ %RotatedAltVal, UseAltMBB ]
10436 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
10437 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
10438 // JNE LoopMBB
10439 // # fall through to DoneMBB
10440 MBB = UpdateMBB;
10441 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
10442 .addReg(RotatedOldVal).addMBB(LoopMBB)
10443 .addReg(RotatedAltVal).addMBB(UseAltMBB);
10444 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
10445 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
10446 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
10447 .addReg(OldVal)
10448 .addReg(NewVal)
10449 .add(Base)
10450 .addImm(Disp);
10451 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10453 MBB->addSuccessor(LoopMBB);
10454 MBB->addSuccessor(DoneMBB);
10455
10456 MI.eraseFromParent();
10457 return DoneMBB;
10458}
10459
10460// Implement EmitInstrWithCustomInserter for subword pseudo ATOMIC_CMP_SWAPW
10461// instruction MI.
10463SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr &MI,
10464 MachineBasicBlock *MBB) const {
10465 MachineFunction &MF = *MBB->getParent();
10466 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10467 MachineRegisterInfo &MRI = MF.getRegInfo();
10468
10469 // Extract the operands. Base can be a register or a frame index.
10470 Register Dest = MI.getOperand(0).getReg();
10471 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
10472 int64_t Disp = MI.getOperand(2).getImm();
10473 Register CmpVal = MI.getOperand(3).getReg();
10474 Register OrigSwapVal = MI.getOperand(4).getReg();
10475 Register BitShift = MI.getOperand(5).getReg();
10476 Register NegBitShift = MI.getOperand(6).getReg();
10477 int64_t BitSize = MI.getOperand(7).getImm();
10478 DebugLoc DL = MI.getDebugLoc();
10479
10480 const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
10481
10482 // Get the right opcodes for the displacement and zero-extension.
10483 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
10484 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
10485 unsigned ZExtOpcode = BitSize == 8 ? SystemZ::LLCR : SystemZ::LLHR;
10486 assert(LOpcode && CSOpcode && "Displacement out of range");
10487
10488 // Create virtual registers for temporary results.
10489 Register OrigOldVal = MRI.createVirtualRegister(RC);
10490 Register OldVal = MRI.createVirtualRegister(RC);
10491 Register SwapVal = MRI.createVirtualRegister(RC);
10492 Register StoreVal = MRI.createVirtualRegister(RC);
10493 Register OldValRot = MRI.createVirtualRegister(RC);
10494 Register RetryOldVal = MRI.createVirtualRegister(RC);
10495 Register RetrySwapVal = MRI.createVirtualRegister(RC);
10496
10497 // Insert 2 basic blocks for the loop.
10498 MachineBasicBlock *StartMBB = MBB;
10499 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10500 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10501 MachineBasicBlock *SetMBB = SystemZ::emitBlockAfter(LoopMBB);
10502
10503 // StartMBB:
10504 // ...
10505 // %OrigOldVal = L Disp(%Base)
10506 // # fall through to LoopMBB
10507 MBB = StartMBB;
10508 BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
10509 .add(Base)
10510 .addImm(Disp)
10511 .addReg(0);
10512 MBB->addSuccessor(LoopMBB);
10513
10514 // LoopMBB:
10515 // %OldVal = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
10516 // %SwapVal = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
10517 // %OldValRot = RLL %OldVal, BitSize(%BitShift)
10518 // ^^ The low BitSize bits contain the field
10519 // of interest.
10520 // %RetrySwapVal = RISBG32 %SwapVal, %OldValRot, 32, 63-BitSize, 0
10521 // ^^ Replace the upper 32-BitSize bits of the
10522 // swap value with those that we loaded and rotated.
10523 // %Dest = LL[CH] %OldValRot
10524 // CR %Dest, %CmpVal
10525 // JNE DoneMBB
10526 // # Fall through to SetMBB
10527 MBB = LoopMBB;
10528 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
10529 .addReg(OrigOldVal).addMBB(StartMBB)
10530 .addReg(RetryOldVal).addMBB(SetMBB);
10531 BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
10532 .addReg(OrigSwapVal).addMBB(StartMBB)
10533 .addReg(RetrySwapVal).addMBB(SetMBB);
10534 BuildMI(MBB, DL, TII->get(SystemZ::RLL), OldValRot)
10535 .addReg(OldVal).addReg(BitShift).addImm(BitSize);
10536 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
10537 .addReg(SwapVal)
10538 .addReg(OldValRot)
10539 .addImm(32)
10540 .addImm(63 - BitSize)
10541 .addImm(0)
10542 .setOperandDead(6);
10543 BuildMI(MBB, DL, TII->get(ZExtOpcode), Dest)
10544 .addReg(OldValRot);
10545 BuildMI(MBB, DL, TII->get(SystemZ::CR))
10546 .addReg(Dest).addReg(CmpVal);
10547 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10550 MBB->addSuccessor(DoneMBB);
10551 MBB->addSuccessor(SetMBB);
10552
10553 // SetMBB:
10554 // %StoreVal = RLL %RetrySwapVal, -BitSize(%NegBitShift)
10555 // ^^ Rotate the new field to its proper position.
10556 // %RetryOldVal = CS %OldVal, %StoreVal, Disp(%Base)
10557 // JNE LoopMBB
10558 // # fall through to ExitMBB
10559 MBB = SetMBB;
10560 BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
10561 .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
10562 BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
10563 .addReg(OldVal)
10564 .addReg(StoreVal)
10565 .add(Base)
10566 .addImm(Disp);
10567 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10569 MBB->addSuccessor(LoopMBB);
10570 MBB->addSuccessor(DoneMBB);
10571
10572 // If the CC def wasn't dead in the ATOMIC_CMP_SWAPW, mark CC as live-in
10573 // to the block after the loop. At this point, CC may have been defined
10574 // either by the CR in LoopMBB or by the CS in SetMBB.
10575 if (!MI.registerDefIsDead(SystemZ::CC, /*TRI=*/nullptr))
10576 DoneMBB->addLiveIn(SystemZ::CC);
10577
10578 MI.eraseFromParent();
10579 return DoneMBB;
10580}
10581
10583SystemZTargetLowering::emitMemMemWrapper(MachineInstr &MI,
10585 unsigned Opcode, bool IsMemset) const {
10586 MachineFunction &MF = *MBB->getParent();
10587 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10588 MachineRegisterInfo &MRI = MF.getRegInfo();
10589 DebugLoc DL = MI.getDebugLoc();
10590
10591 MachineOperand DestBase = earlyUseOperand(MI.getOperand(0));
10592 uint64_t DestDisp = MI.getOperand(1).getImm();
10593 MachineOperand SrcBase = MachineOperand::CreateReg(0U, false);
10594 uint64_t SrcDisp;
10595
10596 // Fold the displacement Disp if it is out of range.
10597 auto foldDisplIfNeeded = [&](MachineOperand &Base, uint64_t &Disp) -> void {
10598 if (!isUInt<12>(Disp)) {
10599 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10600 unsigned Opcode = TII->getOpcodeForOffset(SystemZ::LA, Disp);
10601 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII->get(Opcode), Reg)
10602 .add(Base).addImm(Disp).addReg(0);
10604 Disp = 0;
10605 }
10606 };
10607
10608 if (!IsMemset) {
10609 SrcBase = earlyUseOperand(MI.getOperand(2));
10610 SrcDisp = MI.getOperand(3).getImm();
10611 } else {
10612 SrcBase = DestBase;
10613 SrcDisp = DestDisp++;
10614 foldDisplIfNeeded(DestBase, DestDisp);
10615 }
10616
10617 MachineOperand &LengthMO = MI.getOperand(IsMemset ? 2 : 4);
10618 bool IsImmForm = LengthMO.isImm();
10619 bool IsRegForm = !IsImmForm;
10620
10621 // Build and insert one Opcode of Length, with special treatment for memset.
10622 auto insertMemMemOp = [&](MachineBasicBlock *InsMBB,
10624 MachineOperand DBase, uint64_t DDisp,
10625 MachineOperand SBase, uint64_t SDisp,
10626 unsigned Length) -> void {
10627 assert(Length > 0 && Length <= 256 && "Building memory op with bad length.");
10628 if (IsMemset) {
10629 MachineOperand ByteMO = earlyUseOperand(MI.getOperand(3));
10630 if (ByteMO.isImm())
10631 BuildMI(*InsMBB, InsPos, DL, TII->get(SystemZ::MVI))
10632 .add(SBase).addImm(SDisp).add(ByteMO);
10633 else
10634 BuildMI(*InsMBB, InsPos, DL, TII->get(SystemZ::STC))
10635 .add(ByteMO).add(SBase).addImm(SDisp).addReg(0);
10636 if (--Length == 0)
10637 return;
10638 }
10639 BuildMI(*MBB, InsPos, DL, TII->get(Opcode))
10640 .add(DBase).addImm(DDisp).addImm(Length)
10641 .add(SBase).addImm(SDisp)
10642 .setMemRefs(MI.memoperands());
10643 };
10644
10645 bool NeedsLoop = false;
10646 uint64_t ImmLength = 0;
10647 Register LenAdjReg = SystemZ::NoRegister;
10648 if (IsImmForm) {
10649 ImmLength = LengthMO.getImm();
10650 ImmLength += IsMemset ? 2 : 1; // Add back the subtracted adjustment.
10651 if (ImmLength == 0) {
10652 MI.eraseFromParent();
10653 return MBB;
10654 }
10655 if (Opcode == SystemZ::CLC) {
10656 if (ImmLength > 3 * 256)
10657 // A two-CLC sequence is a clear win over a loop, not least because
10658 // it needs only one branch. A three-CLC sequence needs the same
10659 // number of branches as a loop (i.e. 2), but is shorter. That
10660 // brings us to lengths greater than 768 bytes. It seems relatively
10661 // likely that a difference will be found within the first 768 bytes,
10662 // so we just optimize for the smallest number of branch
10663 // instructions, in order to avoid polluting the prediction buffer
10664 // too much.
10665 NeedsLoop = true;
10666 } else if (ImmLength > 6 * 256)
10667 // The heuristic we use is to prefer loops for anything that would
10668 // require 7 or more MVCs. With these kinds of sizes there isn't much
10669 // to choose between straight-line code and looping code, since the
10670 // time will be dominated by the MVCs themselves.
10671 NeedsLoop = true;
10672 } else {
10673 NeedsLoop = true;
10674 LenAdjReg = LengthMO.getReg();
10675 }
10676
10677 // When generating more than one CLC, all but the last will need to
10678 // branch to the end when a difference is found.
10679 MachineBasicBlock *EndMBB =
10680 (Opcode == SystemZ::CLC && (ImmLength > 256 || NeedsLoop)
10682 : nullptr);
10683
10684 if (NeedsLoop) {
10685 Register StartCountReg =
10686 MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
10687 if (IsImmForm) {
10688 TII->loadImmediate(*MBB, MI, StartCountReg, ImmLength / 256);
10689 ImmLength &= 255;
10690 } else {
10691 BuildMI(*MBB, MI, DL, TII->get(SystemZ::SRLG), StartCountReg)
10692 .addReg(LenAdjReg)
10693 .addReg(0)
10694 .addImm(8);
10695 }
10696
10697 bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
10698 auto loadZeroAddress = [&]() -> MachineOperand {
10699 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10700 BuildMI(*MBB, MI, DL, TII->get(SystemZ::LGHI), Reg).addImm(0);
10701 return MachineOperand::CreateReg(Reg, false);
10702 };
10703 if (DestBase.isReg() && DestBase.getReg() == SystemZ::NoRegister)
10704 DestBase = loadZeroAddress();
10705 if (SrcBase.isReg() && SrcBase.getReg() == SystemZ::NoRegister)
10706 SrcBase = HaveSingleBase ? DestBase : loadZeroAddress();
10707
10708 MachineBasicBlock *StartMBB = nullptr;
10709 MachineBasicBlock *LoopMBB = nullptr;
10710 MachineBasicBlock *NextMBB = nullptr;
10711 MachineBasicBlock *DoneMBB = nullptr;
10712 MachineBasicBlock *AllDoneMBB = nullptr;
10713
10714 Register StartSrcReg = forceReg(MI, SrcBase, TII);
10715 Register StartDestReg =
10716 (HaveSingleBase ? StartSrcReg : forceReg(MI, DestBase, TII));
10717
10718 const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
10719 Register ThisSrcReg = MRI.createVirtualRegister(RC);
10720 Register ThisDestReg =
10721 (HaveSingleBase ? ThisSrcReg : MRI.createVirtualRegister(RC));
10722 Register NextSrcReg = MRI.createVirtualRegister(RC);
10723 Register NextDestReg =
10724 (HaveSingleBase ? NextSrcReg : MRI.createVirtualRegister(RC));
10725 RC = &SystemZ::GR64BitRegClass;
10726 Register ThisCountReg = MRI.createVirtualRegister(RC);
10727 Register NextCountReg = MRI.createVirtualRegister(RC);
10728
10729 if (IsRegForm) {
10730 AllDoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10731 StartMBB = SystemZ::emitBlockAfter(MBB);
10732 LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10733 NextMBB = (EndMBB ? SystemZ::emitBlockAfter(LoopMBB) : LoopMBB);
10734 DoneMBB = SystemZ::emitBlockAfter(NextMBB);
10735
10736 // MBB:
10737 // # Jump to AllDoneMBB if LenAdjReg means 0, or fall thru to StartMBB.
10738 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10739 .addReg(LenAdjReg).addImm(IsMemset ? -2 : -1);
10740 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10742 .addMBB(AllDoneMBB);
10743 MBB->addSuccessor(AllDoneMBB);
10744 if (!IsMemset)
10745 MBB->addSuccessor(StartMBB);
10746 else {
10747 // MemsetOneCheckMBB:
10748 // # Jump to MemsetOneMBB for a memset of length 1, or
10749 // # fall thru to StartMBB.
10750 MachineBasicBlock *MemsetOneCheckMBB = SystemZ::emitBlockAfter(MBB);
10751 MachineBasicBlock *MemsetOneMBB = SystemZ::emitBlockAfter(&*MF.rbegin());
10752 MBB->addSuccessor(MemsetOneCheckMBB);
10753 MBB = MemsetOneCheckMBB;
10754 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10755 .addReg(LenAdjReg).addImm(-1);
10756 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10758 .addMBB(MemsetOneMBB);
10759 MBB->addSuccessor(MemsetOneMBB, {10, 100});
10760 MBB->addSuccessor(StartMBB, {90, 100});
10761
10762 // MemsetOneMBB:
10763 // # Jump back to AllDoneMBB after a single MVI or STC.
10764 MBB = MemsetOneMBB;
10765 insertMemMemOp(MBB, MBB->end(),
10766 MachineOperand::CreateReg(StartDestReg, false), DestDisp,
10767 MachineOperand::CreateReg(StartSrcReg, false), SrcDisp,
10768 1);
10769 BuildMI(MBB, DL, TII->get(SystemZ::J)).addMBB(AllDoneMBB);
10770 MBB->addSuccessor(AllDoneMBB);
10771 }
10772
10773 // StartMBB:
10774 // # Jump to DoneMBB if %StartCountReg is zero, or fall through to LoopMBB.
10775 MBB = StartMBB;
10776 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10777 .addReg(StartCountReg).addImm(0);
10778 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10780 .addMBB(DoneMBB);
10781 MBB->addSuccessor(DoneMBB);
10782 MBB->addSuccessor(LoopMBB);
10783 }
10784 else {
10785 StartMBB = MBB;
10786 DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10787 LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10788 NextMBB = (EndMBB ? SystemZ::emitBlockAfter(LoopMBB) : LoopMBB);
10789
10790 // StartMBB:
10791 // # fall through to LoopMBB
10792 MBB->addSuccessor(LoopMBB);
10793
10794 DestBase = MachineOperand::CreateReg(NextDestReg, false);
10795 SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
10796 if (EndMBB && !ImmLength)
10797 // If the loop handled the whole CLC range, DoneMBB will be empty with
10798 // CC live-through into EndMBB, so add it as live-in.
10799 DoneMBB->addLiveIn(SystemZ::CC);
10800 }
10801
10802 // LoopMBB:
10803 // %ThisDestReg = phi [ %StartDestReg, StartMBB ],
10804 // [ %NextDestReg, NextMBB ]
10805 // %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
10806 // [ %NextSrcReg, NextMBB ]
10807 // %ThisCountReg = phi [ %StartCountReg, StartMBB ],
10808 // [ %NextCountReg, NextMBB ]
10809 // ( PFD 2, 768+DestDisp(%ThisDestReg) )
10810 // Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
10811 // ( JLH EndMBB )
10812 //
10813 // The prefetch is used only for MVC. The JLH is used only for CLC.
10814 MBB = LoopMBB;
10815 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
10816 .addReg(StartDestReg).addMBB(StartMBB)
10817 .addReg(NextDestReg).addMBB(NextMBB);
10818 if (!HaveSingleBase)
10819 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
10820 .addReg(StartSrcReg).addMBB(StartMBB)
10821 .addReg(NextSrcReg).addMBB(NextMBB);
10822 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
10823 .addReg(StartCountReg).addMBB(StartMBB)
10824 .addReg(NextCountReg).addMBB(NextMBB);
10825 if (Opcode == SystemZ::MVC)
10826 BuildMI(MBB, DL, TII->get(SystemZ::PFD))
10828 .addReg(ThisDestReg).addImm(DestDisp - IsMemset + 768).addReg(0);
10829 insertMemMemOp(MBB, MBB->end(),
10830 MachineOperand::CreateReg(ThisDestReg, false), DestDisp,
10831 MachineOperand::CreateReg(ThisSrcReg, false), SrcDisp, 256);
10832 if (EndMBB) {
10833 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10835 .addMBB(EndMBB);
10836 MBB->addSuccessor(EndMBB);
10837 MBB->addSuccessor(NextMBB);
10838 }
10839
10840 // NextMBB:
10841 // %NextDestReg = LA 256(%ThisDestReg)
10842 // %NextSrcReg = LA 256(%ThisSrcReg)
10843 // %NextCountReg = AGHI %ThisCountReg, -1
10844 // CGHI %NextCountReg, 0
10845 // JLH LoopMBB
10846 // # fall through to DoneMBB
10847 //
10848 // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
10849 MBB = NextMBB;
10850 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
10851 .addReg(ThisDestReg).addImm(256).addReg(0);
10852 if (!HaveSingleBase)
10853 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
10854 .addReg(ThisSrcReg).addImm(256).addReg(0);
10855 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
10856 .addReg(ThisCountReg)
10857 .addImm(-1)
10858 .setOperandDead(3);
10859 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10860 .addReg(NextCountReg).addImm(0);
10861 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10863 .addMBB(LoopMBB);
10864 MBB->addSuccessor(LoopMBB);
10865 MBB->addSuccessor(DoneMBB);
10866
10867 MBB = DoneMBB;
10868 if (IsRegForm) {
10869 // DoneMBB:
10870 // # Make PHIs for RemDestReg/RemSrcReg as the loop may or may not run.
10871 // # Use EXecute Relative Long for the remainder of the bytes. The target
10872 // instruction of the EXRL will have a length field of 1 since 0 is an
10873 // illegal value. The number of bytes processed becomes (%LenAdjReg &
10874 // 0xff) + 1.
10875 // # Fall through to AllDoneMBB.
10876 Register RemSrcReg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10877 Register RemDestReg = HaveSingleBase ? RemSrcReg
10878 : MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10879 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RemDestReg)
10880 .addReg(StartDestReg).addMBB(StartMBB)
10881 .addReg(NextDestReg).addMBB(NextMBB);
10882 if (!HaveSingleBase)
10883 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RemSrcReg)
10884 .addReg(StartSrcReg).addMBB(StartMBB)
10885 .addReg(NextSrcReg).addMBB(NextMBB);
10886 if (IsMemset)
10887 insertMemMemOp(MBB, MBB->end(),
10888 MachineOperand::CreateReg(RemDestReg, false), DestDisp,
10889 MachineOperand::CreateReg(RemSrcReg, false), SrcDisp, 1);
10890 MachineInstrBuilder EXRL_MIB =
10891 BuildMI(MBB, DL, TII->get(SystemZ::EXRL_Pseudo))
10892 .addImm(Opcode)
10893 .addReg(LenAdjReg)
10894 .addReg(RemDestReg).addImm(DestDisp)
10895 .addReg(RemSrcReg).addImm(SrcDisp);
10896 MBB->addSuccessor(AllDoneMBB);
10897 MBB = AllDoneMBB;
10898 if (Opcode != SystemZ::MVC) {
10899 EXRL_MIB.addReg(SystemZ::CC, RegState::ImplicitDefine);
10900 if (EndMBB)
10901 MBB->addLiveIn(SystemZ::CC);
10902 }
10903 }
10904 MF.getProperties().resetNoPHIs();
10905 }
10906
10907 // Handle any remaining bytes with straight-line code.
10908 while (ImmLength > 0) {
10909 uint64_t ThisLength = std::min(ImmLength, uint64_t(256));
10910 // The previous iteration might have created out-of-range displacements.
10911 // Apply them using LA/LAY if so.
10912 foldDisplIfNeeded(DestBase, DestDisp);
10913 foldDisplIfNeeded(SrcBase, SrcDisp);
10914 insertMemMemOp(MBB, MI, DestBase, DestDisp, SrcBase, SrcDisp, ThisLength);
10915 DestDisp += ThisLength;
10916 SrcDisp += ThisLength;
10917 ImmLength -= ThisLength;
10918 // If there's another CLC to go, branch to the end if a difference
10919 // was found.
10920 if (EndMBB && ImmLength > 0) {
10921 MachineBasicBlock *NextMBB = SystemZ::splitBlockBefore(MI, MBB);
10922 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10924 .addMBB(EndMBB);
10925 MBB->addSuccessor(EndMBB);
10926 MBB->addSuccessor(NextMBB);
10927 MBB = NextMBB;
10928 }
10929 }
10930 if (EndMBB) {
10931 MBB->addSuccessor(EndMBB);
10932 MBB = EndMBB;
10933 MBB->addLiveIn(SystemZ::CC);
10934 }
10935
10936 MI.eraseFromParent();
10937 return MBB;
10938}
10939
10941SystemZTargetLowering::emitMemmoveImm(MachineInstr &MI,
10942 MachineBasicBlock *MBB) const {
10943 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10944
10945 DebugLoc DL = MI.getDebugLoc();
10946 MachineOperand DstAddr = earlyUseOperand(MI.getOperand(0));
10947 MachineOperand SrcAddr = earlyUseOperand(MI.getOperand(1));
10948 uint64_t Len = MI.getOperand(2).getImm();
10949 assert(Len > 0 && Len <= 256 && "Memmove of of unsupported constant length.");
10950
10951 // Use MVC or MVCRL after comparing the addresses.
10952 MachineBasicBlock *DoneMBB = SystemZ::splitBlockAfter(MI, MBB);
10953 MachineBasicBlock *MvcMBB = SystemZ::emitBlockAfter(MBB);
10954 MachineBasicBlock *MvcrlMBB = SystemZ::emitBlockAfter(MvcMBB);
10955 MBB->addSuccessor(MvcMBB);
10956 MBB->addSuccessor(MvcrlMBB);
10957 MvcMBB->addSuccessor(DoneMBB);
10958 MvcrlMBB->addSuccessor(DoneMBB);
10959
10960 BuildMI(MBB, DL, TII->get(SystemZ::CLGR)).add(SrcAddr).add(DstAddr);
10961 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10963 .addMBB(MvcrlMBB);
10964
10965 BuildMI(MvcMBB, DL, TII->get(SystemZ::MVC))
10966 .add(DstAddr).addImm(0)
10967 .addImm(Len)
10968 .add(SrcAddr).addImm(0)
10969 .setMemRefs(MI.memoperands());
10970 BuildMI(MvcMBB, DL, TII->get(SystemZ::J)).addMBB(DoneMBB);
10971
10972 BuildMI(MvcrlMBB, DL, TII->get(SystemZ::LHI), SystemZ::R0L).addImm(Len - 1);
10973 BuildMI(MvcrlMBB, DL, TII->get(SystemZ::MVCRL))
10974 .add(DstAddr).addImm(0)
10975 .add(SrcAddr).addImm(0)
10976 .setMemRefs(MI.memoperands());
10977
10978 MI.eraseFromParent();
10979 return DoneMBB;
10980}
10981
10982// Decompose string pseudo-instruction MI into a loop that continually performs
10983// Opcode until CC != 3.
10984MachineBasicBlock *SystemZTargetLowering::emitStringWrapper(
10985 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
10986 MachineFunction &MF = *MBB->getParent();
10987 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10988 MachineRegisterInfo &MRI = MF.getRegInfo();
10989 DebugLoc DL = MI.getDebugLoc();
10990
10991 uint64_t End1Reg = MI.getOperand(0).getReg();
10992 uint64_t Start1Reg = MI.getOperand(1).getReg();
10993 uint64_t Start2Reg = MI.getOperand(2).getReg();
10994 uint64_t CharReg = MI.getOperand(3).getReg();
10995
10996 const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
10997 uint64_t This1Reg = MRI.createVirtualRegister(RC);
10998 uint64_t This2Reg = MRI.createVirtualRegister(RC);
10999 uint64_t End2Reg = MRI.createVirtualRegister(RC);
11000
11001 MachineBasicBlock *StartMBB = MBB;
11002 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
11003 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
11004
11005 // StartMBB:
11006 // # fall through to LoopMBB
11007 MBB->addSuccessor(LoopMBB);
11008
11009 // LoopMBB:
11010 // %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
11011 // %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
11012 // R0L = %CharReg
11013 // %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
11014 // JO LoopMBB
11015 // # fall through to DoneMBB
11016 //
11017 // The load of R0L can be hoisted by post-RA LICM.
11018 MBB = LoopMBB;
11019
11020 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
11021 .addReg(Start1Reg).addMBB(StartMBB)
11022 .addReg(End1Reg).addMBB(LoopMBB);
11023 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
11024 .addReg(Start2Reg).addMBB(StartMBB)
11025 .addReg(End2Reg).addMBB(LoopMBB);
11026 BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
11027 BuildMI(MBB, DL, TII->get(Opcode))
11028 .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
11029 .addReg(This1Reg).addReg(This2Reg);
11030 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11032 MBB->addSuccessor(LoopMBB);
11033 MBB->addSuccessor(DoneMBB);
11034
11035 DoneMBB->addLiveIn(SystemZ::CC);
11036
11037 MI.eraseFromParent();
11038 return DoneMBB;
11039}
11040
11041// Update TBEGIN instruction with final opcode and register clobbers.
11042MachineBasicBlock *SystemZTargetLowering::emitTransactionBegin(
11043 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode,
11044 bool NoFloat) const {
11045 MachineFunction &MF = *MBB->getParent();
11046 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11047 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11048
11049 // Update opcode.
11050 MI.setDesc(TII->get(Opcode));
11051
11052 // We cannot handle a TBEGIN that clobbers the stack or frame pointer.
11053 // Make sure to add the corresponding GRSM bits if they are missing.
11054 uint64_t Control = MI.getOperand(2).getImm();
11055 static const unsigned GPRControlBit[16] = {
11056 0x8000, 0x8000, 0x4000, 0x4000, 0x2000, 0x2000, 0x1000, 0x1000,
11057 0x0800, 0x0800, 0x0400, 0x0400, 0x0200, 0x0200, 0x0100, 0x0100
11058 };
11059 Control |= GPRControlBit[15];
11060 if (TFI->hasFP(MF))
11061 Control |= GPRControlBit[11];
11062 MI.getOperand(2).setImm(Control);
11063
11064 // Add GPR clobbers.
11065 for (int I = 0; I < 16; I++) {
11066 if ((Control & GPRControlBit[I]) == 0) {
11067 unsigned Reg = SystemZMC::GR64Regs[I];
11068 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
11069 }
11070 }
11071
11072 // Add FPR/VR clobbers.
11073 if (!NoFloat && (Control & 4) != 0) {
11074 if (Subtarget.hasVector()) {
11075 for (unsigned Reg : SystemZMC::VR128Regs) {
11076 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
11077 }
11078 } else {
11079 for (unsigned Reg : SystemZMC::FP64Regs) {
11080 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
11081 }
11082 }
11083 }
11084
11085 return MBB;
11086}
11087
11088MachineBasicBlock *SystemZTargetLowering::emitLoadAndTestCmp0(
11089 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
11090 MachineFunction &MF = *MBB->getParent();
11091 MachineRegisterInfo *MRI = &MF.getRegInfo();
11092 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11093 DebugLoc DL = MI.getDebugLoc();
11094
11095 Register SrcReg = MI.getOperand(0).getReg();
11096
11097 // Create new virtual register of the same class as source.
11098 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
11099 Register DstReg = MRI->createVirtualRegister(RC);
11100
11101 // Replace pseudo with a normal load-and-test that models the def as
11102 // well.
11103 BuildMI(*MBB, MI, DL, TII->get(Opcode), DstReg)
11104 .addReg(SrcReg)
11105 .setMIFlags(MI.getFlags());
11106 MI.eraseFromParent();
11107
11108 return MBB;
11109}
11110
11111MachineBasicBlock *SystemZTargetLowering::emitProbedAlloca(
11113 MachineFunction &MF = *MBB->getParent();
11114 MachineRegisterInfo *MRI = &MF.getRegInfo();
11115 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11116 DebugLoc DL = MI.getDebugLoc();
11117 const unsigned ProbeSize = getStackProbeSize(MF);
11118 Register DstReg = MI.getOperand(0).getReg();
11119 Register SizeReg = MI.getOperand(2).getReg();
11120
11121 MachineBasicBlock *StartMBB = MBB;
11122 MachineBasicBlock *DoneMBB = SystemZ::splitBlockAfter(MI, MBB);
11123 MachineBasicBlock *LoopTestMBB = SystemZ::emitBlockAfter(StartMBB);
11124 MachineBasicBlock *LoopBodyMBB = SystemZ::emitBlockAfter(LoopTestMBB);
11125 MachineBasicBlock *TailTestMBB = SystemZ::emitBlockAfter(LoopBodyMBB);
11126 MachineBasicBlock *TailMBB = SystemZ::emitBlockAfter(TailTestMBB);
11127
11128 MachineMemOperand *VolLdMMO = MF.getMachineMemOperand(MachinePointerInfo(),
11130
11131 Register PHIReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11132 Register IncReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11133
11134 // LoopTestMBB
11135 // BRC TailTestMBB
11136 // # fallthrough to LoopBodyMBB
11137 StartMBB->addSuccessor(LoopTestMBB);
11138 MBB = LoopTestMBB;
11139 BuildMI(MBB, DL, TII->get(SystemZ::PHI), PHIReg)
11140 .addReg(SizeReg)
11141 .addMBB(StartMBB)
11142 .addReg(IncReg)
11143 .addMBB(LoopBodyMBB);
11144 BuildMI(MBB, DL, TII->get(SystemZ::CLGFI))
11145 .addReg(PHIReg)
11146 .addImm(ProbeSize);
11147 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11149 .addMBB(TailTestMBB);
11150 MBB->addSuccessor(LoopBodyMBB);
11151 MBB->addSuccessor(TailTestMBB);
11152
11153 // LoopBodyMBB: Allocate and probe by means of a volatile compare.
11154 // J LoopTestMBB
11155 MBB = LoopBodyMBB;
11156 BuildMI(MBB, DL, TII->get(SystemZ::SLGFI), IncReg)
11157 .addReg(PHIReg)
11158 .addImm(ProbeSize)
11159 .setOperandDead(3);
11160 BuildMI(MBB, DL, TII->get(SystemZ::SLGFI), SystemZ::R15D)
11161 .addReg(SystemZ::R15D)
11162 .addImm(ProbeSize)
11163 .setOperandDead(3);
11164 BuildMI(MBB, DL, TII->get(SystemZ::CG))
11165 .addReg(SystemZ::R15D)
11166 .addReg(SystemZ::R15D)
11167 .addImm(ProbeSize - 8)
11168 .addReg(0)
11169 .setOperandDead(4)
11170 .setMemRefs(VolLdMMO);
11171 BuildMI(MBB, DL, TII->get(SystemZ::J)).addMBB(LoopTestMBB);
11172 MBB->addSuccessor(LoopTestMBB);
11173
11174 // TailTestMBB
11175 // BRC DoneMBB
11176 // # fallthrough to TailMBB
11177 MBB = TailTestMBB;
11178 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
11179 .addReg(PHIReg)
11180 .addImm(0);
11181 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11183 .addMBB(DoneMBB);
11184 MBB->addSuccessor(TailMBB);
11185 MBB->addSuccessor(DoneMBB);
11186
11187 // TailMBB
11188 // # fallthrough to DoneMBB
11189 MBB = TailMBB;
11190 BuildMI(MBB, DL, TII->get(SystemZ::SLGR), SystemZ::R15D)
11191 .addReg(SystemZ::R15D)
11192 .addReg(PHIReg)
11193 .setOperandDead(3);
11194 BuildMI(MBB, DL, TII->get(SystemZ::CG))
11195 .addReg(SystemZ::R15D)
11196 .addReg(SystemZ::R15D)
11197 .addImm(-8)
11198 .addReg(PHIReg)
11199 .setOperandDead(4)
11200 .setMemRefs(VolLdMMO);
11201 MBB->addSuccessor(DoneMBB);
11202
11203 // DoneMBB
11204 MBB = DoneMBB;
11205 BuildMI(*MBB, MBB->begin(), DL, TII->get(TargetOpcode::COPY), DstReg)
11206 .addReg(SystemZ::R15D);
11207
11208 MI.eraseFromParent();
11209 return DoneMBB;
11210}
11211
11212SDValue SystemZTargetLowering::
11213getBackchainAddress(SDValue SP, SelectionDAG &DAG) const {
11215 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>();
11216 SDLoc DL(SP);
11217 return DAG.getNode(ISD::ADD, DL, MVT::i64, SP,
11218 DAG.getIntPtrConstant(TFL->getBackchainOffset(MF), DL));
11219}
11220
11221// Replace a _STACKGUARD_DAG pseudo with a _STACKGUARD pseudo, adding
11222// a dead early-clobber def reg that will be used as a scratch register
11223// when the pseudo is expanded.
11224MachineBasicBlock *SystemZTargetLowering::emitStackGuardPseudo(
11225 MachineInstr &MI, MachineBasicBlock *MBB, unsigned PseudoOp) const {
11226 MachineRegisterInfo *MRI = &MBB->getParent()->getRegInfo();
11227 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11228 DebugLoc DL = MI.getDebugLoc();
11229 Register AddrReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11230 BuildMI(*MBB, MI, DL, TII->get(PseudoOp), AddrReg)
11231 .addFrameIndex(MI.getOperand(0).getIndex())
11232 .addImm(MI.getOperand(1).getImm());
11233 MI.eraseFromParent();
11234 return MBB;
11235}
11236
11239 switch (MI.getOpcode()) {
11240 case SystemZ::ADJCALLSTACKDOWN:
11241 case SystemZ::ADJCALLSTACKUP:
11242 return emitAdjCallStack(MI, MBB);
11243
11244 case SystemZ::Select32:
11245 case SystemZ::Select64:
11246 case SystemZ::Select128:
11247 case SystemZ::SelectF32:
11248 case SystemZ::SelectF64:
11249 case SystemZ::SelectF128:
11250 case SystemZ::SelectVR32:
11251 case SystemZ::SelectVR64:
11252 case SystemZ::SelectVR128:
11253 return emitSelect(MI, MBB);
11254
11255 case SystemZ::CondStore8Mux:
11256 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
11257 case SystemZ::CondStore8MuxInv:
11258 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
11259 case SystemZ::CondStore16Mux:
11260 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
11261 case SystemZ::CondStore16MuxInv:
11262 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
11263 case SystemZ::CondStore32Mux:
11264 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, false);
11265 case SystemZ::CondStore32MuxInv:
11266 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, true);
11267 case SystemZ::CondStore8:
11268 return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
11269 case SystemZ::CondStore8Inv:
11270 return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
11271 case SystemZ::CondStore16:
11272 return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
11273 case SystemZ::CondStore16Inv:
11274 return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
11275 case SystemZ::CondStore32:
11276 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
11277 case SystemZ::CondStore32Inv:
11278 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
11279 case SystemZ::CondStore64:
11280 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
11281 case SystemZ::CondStore64Inv:
11282 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
11283 case SystemZ::CondStoreF32:
11284 return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
11285 case SystemZ::CondStoreF32Inv:
11286 return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
11287 case SystemZ::CondStoreF64:
11288 return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
11289 case SystemZ::CondStoreF64Inv:
11290 return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
11291
11292 case SystemZ::SCmp128Hi:
11293 return emitICmp128Hi(MI, MBB, false);
11294 case SystemZ::UCmp128Hi:
11295 return emitICmp128Hi(MI, MBB, true);
11296
11297
11298 case SystemZ::ATOMIC_SWAPW:
11299 return emitAtomicLoadBinary(MI, MBB, 0);
11300
11301 case SystemZ::ATOMIC_LOADW_AR:
11302 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR);
11303 case SystemZ::ATOMIC_LOADW_AFI:
11304 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI);
11305
11306 case SystemZ::ATOMIC_LOADW_SR:
11307 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR);
11308
11309 case SystemZ::ATOMIC_LOADW_NR:
11310 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR);
11311 case SystemZ::ATOMIC_LOADW_NILH:
11312 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH);
11313
11314 case SystemZ::ATOMIC_LOADW_OR:
11315 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR);
11316 case SystemZ::ATOMIC_LOADW_OILH:
11317 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH);
11318
11319 case SystemZ::ATOMIC_LOADW_XR:
11320 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR);
11321 case SystemZ::ATOMIC_LOADW_XILF:
11322 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF);
11323
11324 case SystemZ::ATOMIC_LOADW_NRi:
11325 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, true);
11326 case SystemZ::ATOMIC_LOADW_NILHi:
11327 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, true);
11328
11329 case SystemZ::ATOMIC_LOADW_MIN:
11330 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR, SystemZ::CCMASK_CMP_LE);
11331 case SystemZ::ATOMIC_LOADW_MAX:
11332 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR, SystemZ::CCMASK_CMP_GE);
11333 case SystemZ::ATOMIC_LOADW_UMIN:
11334 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR, SystemZ::CCMASK_CMP_LE);
11335 case SystemZ::ATOMIC_LOADW_UMAX:
11336 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR, SystemZ::CCMASK_CMP_GE);
11337
11338 case SystemZ::ATOMIC_CMP_SWAPW:
11339 return emitAtomicCmpSwapW(MI, MBB);
11340 case SystemZ::MVCImm:
11341 case SystemZ::MVCReg:
11342 return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
11343 case SystemZ::NCImm:
11344 return emitMemMemWrapper(MI, MBB, SystemZ::NC);
11345 case SystemZ::OCImm:
11346 return emitMemMemWrapper(MI, MBB, SystemZ::OC);
11347 case SystemZ::XCImm:
11348 case SystemZ::XCReg:
11349 return emitMemMemWrapper(MI, MBB, SystemZ::XC);
11350 case SystemZ::CLCImm:
11351 case SystemZ::CLCReg:
11352 return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
11353 case SystemZ::MemsetImmImm:
11354 case SystemZ::MemsetImmReg:
11355 case SystemZ::MemsetRegImm:
11356 case SystemZ::MemsetRegReg:
11357 return emitMemMemWrapper(MI, MBB, SystemZ::MVC, true/*IsMemset*/);
11358 case SystemZ::MemmoveImm:
11359 return emitMemmoveImm(MI, MBB);
11360 case SystemZ::CLSTLoop:
11361 return emitStringWrapper(MI, MBB, SystemZ::CLST);
11362 case SystemZ::MVSTLoop:
11363 return emitStringWrapper(MI, MBB, SystemZ::MVST);
11364 case SystemZ::SRSTLoop:
11365 return emitStringWrapper(MI, MBB, SystemZ::SRST);
11366 case SystemZ::TBEGIN:
11367 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, false);
11368 case SystemZ::TBEGIN_nofloat:
11369 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, true);
11370 case SystemZ::TBEGINC:
11371 return emitTransactionBegin(MI, MBB, SystemZ::TBEGINC, true);
11372 case SystemZ::LTEBRCompare_Pseudo:
11373 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTEBR);
11374 case SystemZ::LTDBRCompare_Pseudo:
11375 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTDBR);
11376 case SystemZ::LTXBRCompare_Pseudo:
11377 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTXBR);
11378
11379 case SystemZ::PROBED_ALLOCA:
11380 return emitProbedAlloca(MI, MBB);
11381 case SystemZ::EH_SjLj_SetJmp:
11382 return emitEHSjLjSetJmp(MI, MBB);
11383 case SystemZ::EH_SjLj_LongJmp:
11384 return emitEHSjLjLongJmp(MI, MBB);
11385
11386 case TargetOpcode::STACKMAP:
11387 case TargetOpcode::PATCHPOINT:
11388 return emitPatchPoint(MI, MBB);
11389
11390 case SystemZ::MOV_STACKGUARD_DAG:
11391 return emitStackGuardPseudo(MI, MBB, SystemZ::MOV_STACKGUARD);
11392
11393 case SystemZ::CMP_STACKGUARD_DAG:
11394 return emitStackGuardPseudo(MI, MBB, SystemZ::CMP_STACKGUARD);
11395
11396 default:
11397 llvm_unreachable("Unexpected instr type to insert");
11398 }
11399}
11400
11401SDValue SystemZTargetLowering::lowerGET_ROUNDING(SDValue Op,
11402 SelectionDAG &DAG) const {
11403 SDLoc dl(Op);
11404 /*
11405 The rounding method is in FPC Byte 3 bits 6-7, and has the following
11406 settings:
11407 00 Round to nearest
11408 01 Round to 0
11409 10 Round to +inf
11410 11 Round to -inf
11411
11412 FLT_ROUNDS, on the other hand, expects the following:
11413 -1 Undefined
11414 0 Round to 0
11415 1 Round to nearest
11416 2 Round to +inf
11417 3 Round to -inf
11418 */
11419
11420 // Save FPC to register.
11421 SDValue Chain = Op.getOperand(0);
11422 SDValue EFPC(
11423 DAG.getMachineNode(SystemZ::EFPC, dl, {MVT::i32, MVT::Other}, Chain), 0);
11424 Chain = EFPC.getValue(1);
11425
11426 // Transform as necessary
11427 SDValue CWD1 = DAG.getNode(ISD::AND, dl, MVT::i32, EFPC,
11428 DAG.getConstant(3, dl, MVT::i32));
11429 // RetVal = (CWD1 ^ (CWD1 >> 1)) ^ 1
11430 SDValue CWD2 = DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1,
11431 DAG.getNode(ISD::SRL, dl, MVT::i32, CWD1,
11432 DAG.getConstant(1, dl, MVT::i32)));
11433
11434 SDValue RetVal = DAG.getNode(ISD::XOR, dl, MVT::i32, CWD2,
11435 DAG.getConstant(1, dl, MVT::i32));
11436 RetVal = DAG.getZExtOrTrunc(RetVal, dl, Op.getValueType());
11437
11438 return DAG.getMergeValues({RetVal, Chain}, dl);
11439}
11440
11441SDValue SystemZTargetLowering::lowerVECREDUCE_ADD(SDValue Op,
11442 SelectionDAG &DAG) const {
11443 EVT VT = Op.getValueType();
11444 Op = Op.getOperand(0);
11445 EVT OpVT = Op.getValueType();
11446
11447 assert(OpVT.isVector() && "Operand type for VECREDUCE_ADD is not a vector.");
11448
11449 SDLoc DL(Op);
11450
11451 // load a 0 vector for the third operand of VSUM.
11452 SDValue Zero = DAG.getSplatBuildVector(OpVT, DL, DAG.getConstant(0, DL, VT));
11453
11454 // execute VSUM.
11455 switch (OpVT.getScalarSizeInBits()) {
11456 case 8:
11457 case 16:
11458 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Zero);
11459 [[fallthrough]];
11460 case 32:
11461 case 64:
11462 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::i128, Op,
11463 DAG.getBitcast(Op.getValueType(), Zero));
11464 break;
11465 case 128:
11466 break; // VSUM over v1i128 should not happen and would be a noop
11467 default:
11468 llvm_unreachable("Unexpected scalar size.");
11469 }
11470 // Cast to original vector type, retrieve last element.
11471 return DAG.getNode(
11472 ISD::EXTRACT_VECTOR_ELT, DL, VT, DAG.getBitcast(OpVT, Op),
11473 DAG.getConstant(OpVT.getVectorNumElements() - 1, DL, MVT::i32));
11474}
11475
11476static void printFunctionArgExts(const Function *F, raw_ostream &OS) {
11477 FunctionType *FT = F->getFunctionType();
11478 const AttributeList &Attrs = F->getAttributes();
11479 if (Attrs.hasRetAttrs())
11480 OS << Attrs.getAsString(AttributeList::ReturnIndex) << " ";
11481 OS << *F->getReturnType() << " @" << F->getName() << "(";
11482 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
11483 if (I)
11484 OS << ", ";
11485 OS << *FT->getParamType(I);
11486 AttributeSet ArgAttrs = Attrs.getParamAttrs(I);
11487 for (auto A : {Attribute::SExt, Attribute::ZExt, Attribute::NoExt})
11488 if (ArgAttrs.hasAttribute(A))
11489 OS << " " << Attribute::getNameFromAttrKind(A);
11490 }
11491 if (F->isVarArg())
11492 OS << ", ...";
11493 OS << ")\n";
11494}
11495
11496bool SystemZTargetLowering::isInternal(const Function *Fn) const {
11497 std::map<const Function *, bool>::iterator Itr = IsInternalCache.find(Fn);
11498 if (Itr == IsInternalCache.end())
11499 Itr = IsInternalCache
11500 .insert(std::pair<const Function *, bool>(
11501 Fn, (Fn->hasLocalLinkage() && !Fn->hasAddressTaken())))
11502 .first;
11503 return Itr->second;
11504}
11505
11506bool SystemZTargetLowering::enableNarrowIntArgsVerification() const {
11507 if (!Subtarget.isTargetELF())
11508 return false;
11509
11511 return EnableIntArgExtCheck;
11512
11513#ifdef NDEBUG
11514 return false;
11515#endif
11516
11518}
11519
11520void SystemZTargetLowering::verifyNarrowIntegerArgs_Call(
11521 CallLoweringInfo &CLI, const SmallVectorImpl<ISD::OutputArg> &Outs,
11522 const Function *F, SDValue Callee) const {
11523 if (!enableNarrowIntArgsVerification())
11524 return;
11525 bool IsInternal = false;
11526 const Function *CalleeFn = nullptr;
11527 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
11528 if ((CalleeFn = dyn_cast<Function>(G->getGlobal())))
11529 IsInternal = isInternal(CalleeFn);
11530 bool C_ABI = CLI.CallConv == CallingConv::C && !IsInternal;
11531 if (!verifyNarrowIntegerArgs(C_ABI, Outs, CalleeFn, /*IsRet=*/false)) {
11532 errs() << "Callee: ";
11533 if (CalleeFn != nullptr)
11534 printFunctionArgExts(CalleeFn, errs());
11535 else
11536 errs() << "-\n";
11537 errs() << "Caller: ";
11539 if (CLI.CB)
11540 errs() << " " << *CLI.CB;
11541 llvm_unreachable("");
11542 }
11543 LLVM_DEBUG(dbgs() << "Outgoing call arguments verified as ABI compliant: ";
11544 if (CalleeFn != nullptr) printFunctionArgExts(CalleeFn, dbgs());
11545 else dbgs() << "-\n";);
11546}
11547
11548void SystemZTargetLowering::verifyNarrowIntegerArgs_Ret(
11550 const Function *F) const {
11551 if (!enableNarrowIntArgsVerification())
11552 return;
11553 bool C_ABI = CallConv == CallingConv::C && !isInternal(F);
11554 if (!verifyNarrowIntegerArgs(C_ABI, Outs, F, /*IsRet=*/true)) {
11555 errs() << "Returning from function: ";
11557 llvm_unreachable("");
11558 }
11559 LLVM_DEBUG(dbgs() << "Return argument verified as ABI compliant : ";
11561}
11562
11563// Verify that narrow integer arguments are extended according to the
11564// function header (calllee for a call, containing function for a ret).
11565// If C_ABI is true, an extension attribute must be present.
11566bool SystemZTargetLowering::verifyNarrowIntegerArgs(
11567 bool C_ABI, const SmallVectorImpl<ISD::OutputArg> &Outs,
11568 const Function *FunHeader, bool IsRet) const {
11569 if (IsRet && Outs.size() != 1)
11570 return true;
11571
11572 for (unsigned i = 0; i < Outs.size(); ++i) {
11573 EVT OrigArgVT = Outs[i].ArgVT;
11574 if (!OrigArgVT.isInteger() || OrigArgVT.getSizeInBits() >= 64)
11575 continue;
11576 assert(Outs[i].VT == MVT::i32 && "Unexpected integer argument VT.");
11577 ISD::ArgFlagsTy Flags = Outs[i].Flags;
11578 unsigned OrigIdx = Outs[i].OrigArgIndex;
11579
11580 // Per the C ABI there must be an extension.
11581 if (C_ABI && !Flags.isSExt() && !Flags.isZExt() && !Flags.isNoExt()) {
11582 errs() << "ERROR: (C ABI violation) missing extension attribute on "
11583 << (IsRet ? "return value" : Twine("arg ") + Twine(OrigIdx))
11584 << ".\n";
11585 return false;
11586 }
11587
11588 // Flags should reflect the attributes of the function header.
11589 if (FunHeader) {
11590 const AttributeList &FunAttrs = FunHeader->getAttributes();
11591 const AttributeSet Attrs =
11592 IsRet ? FunAttrs.getRetAttrs() : FunAttrs.getParamAttrs(OrigIdx);
11593 if (Attrs.hasAttribute(Attribute::SExt) && !Flags.isSExt()) {
11594 errs() << "ERROR: Missing SExt on arg " << OrigIdx << ".\n";
11595 return false;
11596 }
11597 if (Attrs.hasAttribute(Attribute::ZExt) && !Flags.isZExt()) {
11598 errs() << "ERROR: Missing ZExt on arg " << OrigIdx << ".\n";
11599 return false;
11600 }
11601 }
11602 }
11603
11604 return true;
11605}
11606
11608 Module &M, const LibcallLoweringInfo &Libcalls) const {
11609 StringRef GuardMode = M.getStackProtectorGuard();
11610
11611 // In the TLS case, no symbol needs to be inserted.
11612 if (GuardMode == "tls" || GuardMode.empty())
11613 return;
11614
11615 // Otherwise (in the global case), insert the appropriate global variable.
11617}
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:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, const CCValAssign &VA, const SDLoc &DL)
static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, const CCValAssign &VA, const SDLoc &DL)
#define Check(C,...)
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
static bool isSelectPseudo(MachineInstr &MI)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
static bool isUndef(const MachineInstr &MI)
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t High
uint64_t IntrinsicInst * II
#define P(N)
static constexpr MCPhysReg SPReg
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
const char * Msg
This file defines the SmallSet class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SDValue getI128Select(SelectionDAG &DAG, const SDLoc &DL, Comparison C, SDValue TrueOp, SDValue FalseOp)
static SmallVector< SDValue, 4 > simplifyAssumingCCVal(SDValue &Val, SDValue &CC, SelectionDAG &DAG)
static void adjustForTestUnderMask(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static void adjustForLTGFR(Comparison &C)
static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static SDValue joinDwords(SelectionDAG &DAG, const SDLoc &DL, SDValue Op0, SDValue Op1)
#define CONV(X)
static cl::opt< bool > EnableIntArgExtCheck("argext-abi-check", cl::init(false), cl::desc("Verify that narrow int args are properly extended per the " "SystemZ ABI."))
static bool isOnlyUsedByStores(SDValue StoredVal, SelectionDAG &DAG)
static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT, unsigned Opcode, SDValue Op0, SDValue Op1, SDValue &Even, SDValue &Odd)
static void adjustForRedundantAnd(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static SDValue lowerAddrSpaceCast(SDValue Op, SelectionDAG &DAG)
static SDValue buildScalarToVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT, SDValue Value)
static SDValue lowerI128ToGR128(SelectionDAG &DAG, SDValue In)
static bool isSimpleShift(SDValue N, unsigned &ShiftVal)
static SDValue mergeHighParts(SelectionDAG &DAG, const SDLoc &DL, unsigned MergedBits, EVT VT, SDValue Op0, SDValue Op1)
static bool isI128MovedToParts(LoadSDNode *LD, SDNode *&LoPart, SDNode *&HiPart)
static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1)
static uint32_t findZeroVectorIdx(SDValue *Ops, unsigned Num)
static bool isVectorElementSwap(ArrayRef< int > M, EVT VT)
static void getCSAddressAndShifts(SDValue Addr, SelectionDAG &DAG, SDLoc DL, SDValue &AlignedAddr, SDValue &BitShift, SDValue &NegBitShift)
static bool isShlDoublePermute(const SmallVectorImpl< int > &Bytes, unsigned &StartIndex, unsigned &OpNo0, unsigned &OpNo1)
static SDValue getPermuteNode(SelectionDAG &DAG, const SDLoc &DL, const Permute &P, SDValue Op0, SDValue Op1)
static SDNode * emitIntrinsicWithCCAndChain(SelectionDAG &DAG, SDValue Op, unsigned Opcode)
static SDValue getCCResult(SelectionDAG &DAG, SDValue CCReg)
static void adjustForStackGuardCompare(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode, unsigned &CCValid)
static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend, SDValue Op0, SDValue Op1, SDValue &Hi, SDValue &Lo)
static bool isF128MovedToParts(LoadSDNode *LD, SDNode *&LoPart, SDNode *&HiPart)
static void createPHIsForSelects(SmallVector< MachineInstr *, 8 > &Selects, MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB, MachineBasicBlock *SinkMBB)
static SDValue getGeneralPermuteNode(SelectionDAG &DAG, const SDLoc &DL, SDValue *Ops, const SmallVectorImpl< int > &Bytes)
static unsigned getVectorComparisonOrInvert(ISD::CondCode CC, CmpMode Mode, bool &Invert)
static unsigned CCMaskForCondCode(ISD::CondCode CC)
static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static void adjustForFNeg(Comparison &C)
static bool isScalarToVector(SDValue Op)
static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue CCReg, unsigned CCValid, unsigned CCMask)
static bool matchPermute(const SmallVectorImpl< int > &Bytes, const Permute &P, unsigned &OpNo0, unsigned &OpNo1)
static bool isAddCarryChain(SDValue Carry)
static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static MachineOperand earlyUseOperand(MachineOperand Op)
static bool canUseSiblingCall(const CCState &ArgCCInfo, SmallVectorImpl< CCValAssign > &ArgLocs, SmallVectorImpl< ISD::OutputArg > &Outs)
static bool getzOSCalleeAndADA(SelectionDAG &DAG, SDValue &Callee, SDValue &ADA, SDLoc &DL, SDValue &Chain)
static SDValue convertToF16(SDValue Op, SelectionDAG &DAG)
static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask, SelectionDAG &DAG)
static bool shouldSwapCmpOperands(const Comparison &C)
static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType)
static SDValue getADAEntry(SelectionDAG &DAG, SDValue Val, SDLoc DL, unsigned Offset, bool LoadAdr=false)
static SDNode * emitIntrinsicWithCC(SelectionDAG &DAG, SDValue Op, unsigned Opcode)
static void adjustForSubtraction(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static bool getVPermMask(SDValue ShuffleOp, SmallVectorImpl< int > &Bytes)
static const Permute PermuteForms[]
static bool isI128MovedFromParts(SDValue Val, SDValue &LoPart, SDValue &HiPart)
static std::pair< SDValue, int > findCCUse(const SDValue &Val, unsigned Depth=0)
static bool isSubBorrowChain(SDValue Carry)
static void adjustICmp128(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static bool analyzeArgSplit(const SmallVectorImpl< ArgTy > &Args, SmallVector< CCValAssign, 16 > &ArgLocs, unsigned I, MVT &PartVT, unsigned &NumParts)
static 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 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:406
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
static LLVM_ABI StringRef getNameFromAttrKind(Attribute::AttrKind AttrKind)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
A "pseudo-class" with methods for operating on BUILD_VECTORs.
LLVM_ABI bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef, unsigned &SplatBitSize, bool &HasAnyUndefs, unsigned MinSplatBits=0, bool isBigEndian=false) const
Check if this is a constant splat, and if so, find the smallest element size that splats the vector.
LLVM_ABI bool isConstant() const
CCState - This class holds information needed while lowering arguments and return values.
LLVM_ABI void AnalyzeCallResult(const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn Fn)
AnalyzeCallResult - Analyze the return values of a call, incorporating info about the passed values i...
LLVM_ABI bool CheckReturn(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
CheckReturn - Analyze the return values of a function, returning true if the return can be performed ...
LLVM_ABI void AnalyzeReturn(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
AnalyzeReturn - Analyze the returned values of a return, incorporating info about the result values i...
LLVM_ABI void AnalyzeCallOperands(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
AnalyzeCallOperands - Analyze the outgoing arguments to a call, incorporating info about the passed v...
uint64_t getStackSize() const
Returns the size of the currently allocated portion of the stack.
LLVM_ABI void AnalyzeFormalArguments(const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn Fn)
AnalyzeFormalArguments - Analyze an array of argument values, incorporating info about the formals in...
CCValAssign - Represent assignment of one arg/retval to a location.
Register getLocReg() const
LocInfo getLocInfo() const
bool needsCustom() const
bool isExtInLoc() const
int64_t getLocMemOffset() const
This class represents a function call, abstracting a target machine's calling convention.
bool isTailCall() const
MachineConstantPoolValue * getMachineCPVal() const
const Constant * getConstVal() const
uint64_t getZExtValue() const
This is an important base class in LLVM.
Definition Constant.h: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:126
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...
void addLiveIn(MCRegister Reg, Register vreg=Register())
addLiveIn - Add the specified register as a live-in.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool hasOneUse() const
Return true if there is exactly one use of this node.
SDNodeFlags getFlags() const
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
unsigned getNumOperands() const
Return the number of values used by this operation.
unsigned getMachineOpcode() const
This may only be called if isMachineOpcode returns true.
const SDValue & getOperand(unsigned Num) const
bool hasNUsesOfValue(unsigned NUses, unsigned Value) const
Return true if there are exactly NUSES uses of the indicated value.
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
iterator_range< user_iterator > users()
void setFlags(SDNodeFlags NewFlags)
Represents a use of a SDNode.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
bool isMachineOpcode() const
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
const APInt & getConstantOperandAPInt(unsigned i) const
uint64_t getScalarValueSizeInBits() const
unsigned getResNo() const
get the index which selects a specific result in the SDNode
uint64_t getConstantOperandVal(unsigned i) const
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
unsigned getMachineOpcode() const
unsigned getOpcode() const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
SDValue getExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT, unsigned Opcode)
Convert Op, which must be of integer type, to the integer type VT, by either any/sign/zero-extending ...
const TargetSubtargetInfo & getSubtarget() const
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI SDValue getAtomicLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT MemVT, EVT VT, SDValue Chain, SDValue Ptr, MachineMemOperand *MMO)
LLVM_ABI SDValue getConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offs=0, bool isT=false, unsigned TargetFlags=0)
LLVM_ABI bool isConstantIntBuildVectorOrConstantInt(SDValue N, bool AllowOpaques=true) const
Test whether the given value is a constant int or similar node.
LLVM_ABI SDValue UnrollVectorOp(SDNode *N, unsigned ResNE=0)
Utility function used by legalize and lowering to "unroll" a vector operation by splitting out the sc...
LLVM_ABI SDValue getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, unsigned SrcAS, unsigned DestAS, const SDNodeFlags Flags=SDNodeFlags())
Return an AddrSpaceCastSDNode.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
SDValue getGLOBAL_OFFSET_TABLE(EVT VT)
Return a GLOBAL_OFFSET_TABLE node. This does not have a useful SDLoc.
LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, LocationSize Size=LocationSize::precise(0), const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
LLVM_ABI SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDValue Chain, SDValue Ptr, SDValue Val, MachineMemOperand *MMO)
Gets a node for an atomic op, produces result (if relevant) and chain and takes 2 operands.
void addNoMergeSiteInfo(const SDNode *Node, bool NoMerge)
Set NoMergeSiteInfo to be associated with Node if NoMerge is true.
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
const TargetLowering & getTargetLoweringInfo() const
SDValue getTargetJumpTable(int JTI, EVT VT, unsigned TargetFlags=0)
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2, SDValue InGlue, const SDLoc &DL)
Return a new CALLSEQ_END node, which always must have a glue result (to ensure it's not CSE'd).
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI bool isSplatValue(SDValue V, const APInt &DemandedElts, APInt &UndefElts, unsigned Depth=0) const
Test whether V has a splatted value for all the demanded elements.
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
const DataLayout & getDataLayout() const
SDValue getTargetFrameIndex(int FI, EVT VT)
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
SDValue getSignedTargetConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
SDValue getSplatVector(EVT VT, const SDLoc &DL, SDValue Op)
SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, const SDLoc &DL)
Return a new CALLSEQ_START node, that starts new call frame, in which InSize bytes are set up inside ...
LLVM_ABI bool SignBitIsZero(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero.
LLVM_ABI SDValue getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand)
A convenience function for creating TargetInstrInfo::EXTRACT_SUBREG nodes.
LLVM_ABI SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI std::pair< SDValue, SDValue > getStrictFPExtendOrRound(SDValue Op, SDValue Chain, const SDLoc &DL, EVT VT)
Convert Op, which must be a STRICT operation of float type, to the float type VT, by either extending...
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of float type, to the float type VT, by either extending or rounding (by tr...
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI unsigned ComputeNumSignBits(SDValue Op, unsigned Depth=0) const
Return the number of times the sign bit of the register is replicated into the other bits.
SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, unsigned TargetFlags=0)
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op)
Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all elements.
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset)
Create an add instruction with appropriate flags when used for addressing some offset of an object.
LLVMContext * getContext() const
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment)
Create a stack temporary based on the size in bytes and the alignment.
LLVM_ABI SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
SDValue getTargetConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offset=0, unsigned TargetFlags=0)
LLVM_ABI SDValue getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand, SDValue Subreg)
A convenience function for creating TargetInstrInfo::INSERT_SUBREG nodes.
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
LLVM_ABI std::pair< SDValue, SDValue > SplitScalar(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the scalar node with EXTRACT_ELEMENT using the provided VTs and return the low/high part.
LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
This SDNode is used to implement the code generator support for the llvm IR shufflevector instruction...
ArrayRef< int > getMask() const
const_iterator begin() const
Definition SmallSet.h:216
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
size_type size() const
Definition SmallSet.h:171
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
This class is used to represent ISD::STORE nodes.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:490
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition StringRef.h:720
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
iterator end() const
Definition StringRef.h:116
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
A SystemZ-specific class detailing special use registers particular for calling conventions.
static SystemZConstantPoolValue * Create(const GlobalValue *GV, SystemZCP::SystemZCPModifier Modifier)
const SystemZInstrInfo * getInstrInfo() const override
SystemZCallingConventionRegisters * getSpecialRegisters() const
AtomicExpansionKind shouldExpandAtomicRMWInIR(const AtomicRMWInst *RMW) const override
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all.
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
This callback is invoked for operations that are unsupported by the target, which are registered to u...
EVT getOptimalMemOpType(LLVMContext &Context, const MemOp &Op, const AttributeList &FuncAttributes) const override
Returns the target specific optimal type for load and store operations as a result of memset,...
bool hasInlineStackProbe(const MachineFunction &MF) const override
Returns true if stack probing through inline assembly is requested.
MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *BB) const override
This method should be implemented by targets that mark instructions with the 'usesCustomInserter' fla...
MachineBasicBlock * emitEHSjLjSetJmp(MachineInstr &MI, MachineBasicBlock *MBB) const
AtomicExpansionKind shouldCastAtomicLoadInIR(LoadInst *LI) const override
Returns how the given (atomic) load should be cast by the IR-level AtomicExpand pass.
EVT getSetCCResultType(const DataLayout &DL, LLVMContext &, EVT) const override
Return the ValueType of the result of SETCC operations.
bool allowTruncateForTailCall(Type *, Type *) const override
Return true if a truncation from FromTy to ToTy is permitted when deciding whether a call is in tail ...
SDValue LowerAsmOutputForConstraint(SDValue &Chain, SDValue &Flag, const SDLoc &DL, const AsmOperandInfo &Constraint, SelectionDAG &DAG) const override
SDValue LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, const SmallVectorImpl< SDValue > &OutVals, const SDLoc &DL, SelectionDAG &DAG) const override
This hook must be implemented to lower outgoing return values, described by the Outs array,...
MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
MachineBasicBlock * emitEHSjLjLongJmp(MachineInstr &MI, MachineBasicBlock *MBB) const
bool CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, LLVMContext &Context, const Type *RetTy) const override
This hook should be implemented to check whether the return values described by the Outs array can fi...
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.
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.
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:348
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
user_iterator user_begin()
Definition Value.h:404
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
int getNumOccurrences() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h: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
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:845
@ 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:805
@ 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:879
@ 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:906
@ 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:765
@ 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:936
@ 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:814
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:870
@ STRICT_UINT_TO_FP
Definition ISDOpcodes.h:490
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:675
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ STRICT_PSEUDO_FMIN
Definition ISDOpcodes.h:464
@ FSINCOS
FSINCOS - Compute both fsin and fcos as a single operation.
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:355
@ BR_JT
BR_JT - Jumptable branch.
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:553
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:822
@ ATOMIC_LOAD
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:235
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:249
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:682
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:351
@ VECREDUCE_ADD
Integer reductions may have a result type larger than the vector element type.
@ GET_ROUNDING
Returns current rounding mode: -1 Undefined 0 Round to 0 1 Round to nearest, ties to even 2 Round to ...
Definition ISDOpcodes.h:996
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:714
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:787
@ 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:876
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:837
@ 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:925
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:914
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:745
@ 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:831
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:331
@ STRICT_SINT_TO_FP
STRICT_[US]INT_TO_FP - Convert a signed or unsigned integer to a floating point value.
Definition ISDOpcodes.h:489
@ STRICT_FROUNDEVEN
Definition ISDOpcodes.h:469
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:112
@ STRICT_FP_TO_UINT
Definition ISDOpcodes.h:483
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:505
@ STRICT_FP_TO_SINT
STRICT_FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:482
@ FMINIMUM
FMINIMUM/FMAXIMUM - 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:952
@ 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:757
@ 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:813
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:985
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:947
@ 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:882
@ BRCOND
BRCOND - Conditional branch.
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:859
@ 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 bool isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly=false)
Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are 0 o...
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, EVT Type)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
LLVM_ABI CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y).
LLVM_ABI bool isBuildVectorAllZeros(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are 0 or undef.
LLVM_ABI bool isConstantSplatVector(const SDNode *N, APInt &SplatValue)
Node predicates.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
bool isNormalLoad(const SDNode *N)
Returns true if the specified node is a non-extending and unindexed load.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
auto m_Cmp()
Matches any compare instruction and ignore it.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
LLVM_ABI Libcall getSINTTOFP(EVT OpVT, EVT RetVT)
getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getUINTTOFP(EVT OpVT, EVT RetVT)
getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getFPTOSINT(EVT OpVT, EVT RetVT)
getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h: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:42
static bool isImmHH(uint64_t Val)
Definition SystemZ.h:178
const unsigned CCMASK_TEND
Definition SystemZ.h:99
const unsigned CCMASK_CS_EQ
Definition SystemZ.h:69
const unsigned CCMASK_TBEGIN
Definition SystemZ.h:94
const unsigned CCMASK_0
Definition SystemZ.h:29
const MCPhysReg ELFArgFPRs[ELFNumArgFPRs]
MachineBasicBlock * splitBlockBefore(MachineBasicBlock::iterator MI, MachineBasicBlock *MBB)
const unsigned CCMASK_TM_SOME_1
Definition SystemZ.h:84
const unsigned CCMASK_LOGICAL_CARRY
Definition SystemZ.h:62
const unsigned TDCMASK_NORMAL_MINUS
Definition SystemZ.h:124
const unsigned CCMASK_TDC
Definition SystemZ.h:111
const unsigned CCMASK_FCMP
Definition SystemZ.h:50
const unsigned CCMASK_TM_SOME_0
Definition SystemZ.h:83
static bool isImmHL(uint64_t Val)
Definition SystemZ.h:173
const unsigned TDCMASK_SUBNORMAL_MINUS
Definition SystemZ.h:126
const unsigned PFD_READ
Definition SystemZ.h:117
const unsigned CCMASK_1
Definition SystemZ.h:30
const unsigned TDCMASK_NORMAL_PLUS
Definition SystemZ.h:123
const unsigned PFD_WRITE
Definition SystemZ.h:118
const unsigned CCMASK_CMP_GT
Definition SystemZ.h:39
const unsigned TDCMASK_QNAN_MINUS
Definition SystemZ.h:130
const unsigned CCMASK_CS
Definition SystemZ.h:71
const unsigned CCMASK_ANY
Definition SystemZ.h:33
const unsigned CCMASK_ARITH
Definition SystemZ.h:57
const unsigned CCMASK_TM_MIXED_MSB_0
Definition SystemZ.h:80
const unsigned TDCMASK_SUBNORMAL_PLUS
Definition SystemZ.h:125
static bool isImmLL(uint64_t Val)
Definition SystemZ.h:163
const unsigned VectorBits
Definition SystemZ.h:156
static bool isImmLH(uint64_t Val)
Definition SystemZ.h:168
MachineBasicBlock * emitBlockAfter(MachineBasicBlock *MBB)
const unsigned TDCMASK_INFINITY_PLUS
Definition SystemZ.h:127
unsigned reverseCCMask(unsigned CCMask)
const unsigned CCMASK_TM_ALL_0
Definition SystemZ.h:79
const unsigned IPM_CC
Definition SystemZ.h:114
const unsigned CCMASK_CMP_LE
Definition SystemZ.h:41
const unsigned CCMASK_CMP_O
Definition SystemZ.h:46
const unsigned CCMASK_CMP_EQ
Definition SystemZ.h:37
const unsigned VectorBytes
Definition SystemZ.h:160
const unsigned TDCMASK_INFINITY_MINUS
Definition SystemZ.h:128
const unsigned CCMASK_ICMP
Definition SystemZ.h:49
const unsigned CCMASK_VCMP_ALL
Definition SystemZ.h:103
const unsigned CCMASK_VCMP_NONE
Definition SystemZ.h:105
MachineBasicBlock * splitBlockAfter(MachineBasicBlock::iterator MI, MachineBasicBlock *MBB)
const unsigned CCMASK_VCMP
Definition SystemZ.h:106
const unsigned CCMASK_TM_MIXED_MSB_1
Definition SystemZ.h:81
const unsigned CCMASK_TM_MSB_0
Definition SystemZ.h:85
const unsigned CCMASK_ARITH_OVERFLOW
Definition SystemZ.h:56
const unsigned CCMASK_CS_NE
Definition SystemZ.h:70
const unsigned TDCMASK_SNAN_PLUS
Definition SystemZ.h:131
const unsigned CCMASK_TM
Definition SystemZ.h:87
const unsigned CCMASK_3
Definition SystemZ.h:32
const unsigned CCMASK_NONE
Definition SystemZ.h:28
const unsigned CCMASK_CMP_LT
Definition SystemZ.h:38
const unsigned CCMASK_CMP_NE
Definition SystemZ.h:40
const unsigned TDCMASK_ZERO_PLUS
Definition SystemZ.h:121
const unsigned TDCMASK_QNAN_PLUS
Definition SystemZ.h:129
const unsigned TDCMASK_ZERO_MINUS
Definition SystemZ.h:122
unsigned even128(bool Is32bit)
const unsigned CCMASK_TM_ALL_1
Definition SystemZ.h:82
const unsigned CCMASK_LOGICAL_BORROW
Definition SystemZ.h:64
const unsigned ELFNumArgFPRs
const unsigned CCMASK_CMP_UO
Definition SystemZ.h:45
const unsigned CCMASK_LOGICAL
Definition SystemZ.h:66
const unsigned CCMASK_TM_MSB_1
Definition SystemZ.h:86
const unsigned TDCMASK_SNAN_MINUS
Definition SystemZ.h:132
initializer< Ty > init(const Ty &Val)
support::ulittle32_t Word
Definition IRSymtab.h:53
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
NodeAddr< CodeNode * > Code
Definition RDFGraph.h:388
This is an optimization pass for GlobalISel generic memory operations.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
@ Known
Known to have no common set bits.
@ Define
Register definition.
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Done
Definition Threading.h:60
@ Load
The value being inserted comes from a load (InsertElement only).
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition Error.h:198
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
constexpr T maskLeadingOnes(unsigned N)
Create a bitmask with the N left-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:89
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI void dumpBytes(ArrayRef< uint8_t > Bytes, raw_ostream &OS)
Convert ‘Bytes’ to a hex string and output to ‘OS’.
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition bit.h:362
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
LLVM_ABI bool isBitwiseNot(SDValue V, bool AllowUndefs=false)
Returns true if V is a bitwise not operation.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Success
The lock was released successfully.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
AtomicOrdering
Atomic ordering for LLVM's memory model.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ BeforeLegalizeTypes
Definition DAGCombine.h:16
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
@ Fast
Assign the register banks as fast as possible (default).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
constexpr unsigned BitWidth
ExceptionHandling
Definition CodeGen.h:54
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:567
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:78
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:347
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
LLVM_ABI bool isAllOnesConstant(SDValue V)
Returns true if V is an integer constant with all bits set.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
#define EQ(a, b)
Definition regexec.c:65
AddressingMode(bool LongDispl, bool IdxReg)
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Extended Value Type.
Definition ValueTypes.h:35
EVT changeVectorElementTypeToInteger() const
Return a vector with the same number of elements as this vector, but with the element type converted ...
Definition ValueTypes.h:90
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:418
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:145
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:155
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:408
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
Definition ValueTypes.h:404
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:346
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
bool isRound() const
Return true if the size is a power-of-two number of bytes.
Definition ValueTypes.h:271
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:351
bool isVectorOf(EVT EltVT) const
Return true if this is a vector with matching element type.
Definition ValueTypes.h:181
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:165
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:359
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition KnownBits.h:325
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getConstantPool(MachineFunction &MF)
Return a MachinePointerInfo record that refers to the constant pool.
MachinePointerInfo getWithOffset(int64_t O) const
static LLVM_ABI MachinePointerInfo getGOT(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a GOT entry.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
SmallVector< unsigned, 2 > OpVals
bool isVectorConstantLegal(const SystemZSubtarget &Subtarget)
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*...
This contains information for each constraint that we are lowering.
This structure contains all information that is necessary for lowering calls.
SmallVector< ISD::InputArg, 32 > Ins
CallLoweringInfo & setDiscardResult(bool Value=true)
CallLoweringInfo & setZExtResult(bool Value=true)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
CallLoweringInfo & setSExtResult(bool Value=true)
CallLoweringInfo & setNoReturn(bool Value=true)
SmallVector< ISD::OutputArg, 32 > Outs
CallLoweringInfo & setChain(SDValue InChain)
CallLoweringInfo & setCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList, AttributeSet ResultAttrs={})
This structure is used to pass arguments to makeLibCall function.