LLVM 24.0.0git
SystemZISelLowering.cpp
Go to the documentation of this file.
1//===-- SystemZISelLowering.cpp - SystemZ DAG lowering implementation -----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the SystemZTargetLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "SystemZISelLowering.h"
14#include "SystemZCallingConv.h"
17#include "llvm/ADT/SmallSet.h"
22#include "llvm/IR/GlobalAlias.h"
24#include "llvm/IR/Intrinsics.h"
25#include "llvm/IR/IntrinsicsS390.h"
26#include "llvm/IR/Module.h"
31#include <cctype>
32#include <optional>
33
34using namespace llvm;
35
36#define DEBUG_TYPE "systemz-lower"
37
38namespace {
39// Represents information about a comparison.
40struct Comparison {
41 Comparison(SDValue Op0In, SDValue Op1In, SDValue ChainIn)
42 : Op0(Op0In), Op1(Op1In), Chain(ChainIn),
43 Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
44
45 // The operands to the comparison.
46 SDValue Op0, Op1;
47
48 // Chain if this is a strict floating-point comparison.
49 SDValue Chain;
50
51 // The opcode that should be used to compare Op0 and Op1.
52 unsigned Opcode;
53
54 // A SystemZICMP value. Only used for integer comparisons.
55 unsigned ICmpType;
56
57 // The mask of CC values that Opcode can produce.
58 unsigned CCValid;
59
60 // The mask of CC values for which the original condition is true.
61 unsigned CCMask;
62};
63} // end anonymous namespace
64
65// Classify VT as either 32 or 64 bit.
66static bool is32Bit(EVT VT) {
67 switch (VT.getSimpleVT().SimpleTy) {
68 case MVT::i32:
69 return true;
70 case MVT::i64:
71 return false;
72 default:
73 llvm_unreachable("Unsupported type");
74 }
75}
76
77// Return a version of MachineOperand that can be safely used before the
78// final use.
80 if (Op.isReg())
81 Op.setIsKill(false);
82 return Op;
83}
84
86 const SystemZSubtarget &STI)
87 : TargetLowering(TM, STI), Subtarget(STI) {
88 MVT PtrVT = MVT::i64;
89
90 auto *Regs = STI.getSpecialRegisters();
91
92 // Set up the register classes.
93 if (Subtarget.hasHighWord())
94 addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
95 else
96 addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
97 addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass);
98 if (!useSoftFloat()) {
99 if (Subtarget.hasVector()) {
100 addRegisterClass(MVT::f16, &SystemZ::VR16BitRegClass);
101 addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass);
102 addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass);
103 } else {
104 addRegisterClass(MVT::f16, &SystemZ::FP16BitRegClass);
105 addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass);
106 addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass);
107 }
108 if (Subtarget.hasVectorEnhancements1())
109 addRegisterClass(MVT::f128, &SystemZ::VR128BitRegClass);
110 else
111 addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
112
113 if (Subtarget.hasVector()) {
114 addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass);
115 addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass);
116 addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass);
117 addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass);
118 addRegisterClass(MVT::v8f16, &SystemZ::VR128BitRegClass);
119 addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass);
120 addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass);
121 }
122
123 if (Subtarget.hasVector())
124 addRegisterClass(MVT::i128, &SystemZ::VR128BitRegClass);
125 }
126
127 // Without vector support, model GR128 register pairs as v2i64.
128 if (!Subtarget.hasVector())
129 addRegisterClass(MVT::v2i64, &SystemZ::GR128BitRegClass);
130
131 // Compute derived properties from the register classes
132 computeRegisterProperties(Subtarget.getRegisterInfo());
133
134 // Set up special registers.
135 setStackPointerRegisterToSaveRestore(Regs->getStackPointerRegister());
136
137 // TODO: It may be better to default to latency-oriented scheduling, however
138 // LLVM's current latency-oriented scheduler can't handle physreg definitions
139 // such as SystemZ has with CC, so set this to the register-pressure
140 // scheduler, because it can.
142
145
147
148 // Instructions are strings of 2-byte aligned 2-byte values.
150 // For performance reasons we prefer 16-byte alignment.
152
153 // Handle operations that are handled in a similar way for all types.
154 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
155 I <= MVT::LAST_FP_VALUETYPE;
156 ++I) {
158 if (isTypeLegal(VT)) {
159 // Lower SET_CC into an IPM-based sequence.
163
164 // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
166
167 // Lower SELECT_CC and BR_CC into separate comparisons and branches.
170 }
171 }
172
173 // Expand jump table branches as address arithmetic followed by an
174 // indirect jump.
176
177 // Expand BRCOND into a BR_CC (see above).
179
180 // Handle integer types except i128.
181 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
182 I <= MVT::LAST_INTEGER_VALUETYPE;
183 ++I) {
185 if (isTypeLegal(VT) && VT != MVT::i128) {
187
188 // Expand individual DIV and REMs into DIVREMs.
195
196 // Support addition/subtraction with overflow.
199
200 // Support addition/subtraction with carry.
203
204 // Support carry in as value rather than glue.
207
208 // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
209 // available, or if the operand is constant.
211
212 // Use POPCNT on z196 and above.
213 if (Subtarget.hasPopulationCount())
215 else
217
218 // No special instructions for these.
221
222 // Use *MUL_LOHI where possible instead of MULH*.
227
228 // The fp<=>i32/i64 conversions are all Legal except for f16 and for
229 // unsigned on z10 (only z196 and above have native support for
230 // unsigned conversions).
237 // Handle unsigned 32-bit input types as signed 64-bit types on z10.
238 auto OpAction =
239 (!Subtarget.hasFPExtension() && VT == MVT::i32) ? Promote : Custom;
240 setOperationAction(Op, VT, OpAction);
241 }
242 }
243 }
244
245 // Handle i128 if legal.
246 if (isTypeLegal(MVT::i128)) {
247 // No special instructions for these.
254
255 // We may be able to use VSLDB/VSLD/VSRD for these.
258
259 // No special instructions for these before z17.
260 if (!Subtarget.hasVectorEnhancements3()) {
270 } else {
271 // Even if we do have a legal 128-bit multiply, we do not
272 // want 64-bit multiply-high operations to use it.
275 }
276
277 // Support addition/subtraction with carry.
282
283 // Use VPOPCT and add up partial results.
285
286 // Additional instructions available with z17.
287 if (Subtarget.hasVectorEnhancements3()) {
288 setOperationAction(ISD::ABS, MVT::i128, Legal);
289
291 MVT::i128, Legal);
292
294 }
295 }
296
297 // These need custom handling in order to handle the f16 conversions.
306
307 // Lower 8- and 16-bit atomic operations into full i32 operations during
308 // type legalization.
314 {MVT::i8, MVT::i16}, Custom);
315
316 // Whether or not i128 is not a legal type, we need to custom lower
317 // the atomic operations in order to exploit SystemZ instructions.
322
323 // Mark sign/zero extending atomic loads as legal, which will make
324 // DAGCombiner fold extensions into atomic loads if possible.
326 {MVT::i8, MVT::i16, MVT::i32}, Legal);
328 {MVT::i8, MVT::i16}, Legal);
330 MVT::i8, Legal);
331
332 // We can use the CC result of compare-and-swap to implement
333 // the "success" result of ATOMIC_CMP_SWAP_WITH_SUCCESS.
337
339
340 // Traps are legal, as we will convert them to "j .+2".
341 setOperationAction(ISD::TRAP, MVT::Other, Legal);
342
343 // We have native support for a 64-bit CTLZ, via FLOGR.
347
348 // On z17 we have native support for a 64-bit CTTZ, PDEP, and PEXT.
349 if (Subtarget.hasMiscellaneousExtensions4()) {
355 }
356
357 // On z15 we have native support for a 64-bit CTPOP.
358 if (Subtarget.hasMiscellaneousExtensions3()) {
361 }
362
363 // Give LowerOperation the chance to replace 64-bit ORs with subregs.
365
366 // Expand 128 bit shifts without using a libcall.
370
371 // Also expand 256 bit shifts if i128 is a legal type.
372 if (isTypeLegal(MVT::i128)) {
376 }
377
378 // Handle bitcast from fp128 to i128.
379 if (!isTypeLegal(MVT::i128))
381
382 // We have native instructions for i8, i16 and i32 extensions, but not i1.
384 for (MVT VT : MVT::integer_valuetypes()) {
388 }
389
390 // Handle the various types of symbolic address.
396
397 // We need to handle dynamic allocations specially because of the
398 // 160-byte area at the bottom of the stack.
401
404
405 // Handle prefetches with PFD or PFDRL.
407
408 // Handle readcyclecounter with STCKF.
410
412 // Assume by default that all vector operations need to be expanded.
413 for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
414 if (getOperationAction(Opcode, VT) == Legal)
415 setOperationAction(Opcode, VT, Expand);
416
417 // Likewise all truncating stores and extending loads.
418 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
419 setTruncStoreAction(VT, InnerVT, Expand);
422 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
423 }
424
425 if (Subtarget.hasVector() && isTypeLegal(VT)) {
426 // These operations are legal for anything that can be stored in a
427 // vector register, even if there is no native support for the format
428 // as such. In particular, we can do these for v4f32 even though there
429 // are no specific instructions for that format.
435
436 // Likewise, except that we need to replace the nodes with something
437 // more specific.
440 }
441 }
442
443 if (!Subtarget.hasVector()) {
444 // A v2i64 GR128 pair can only be built from or split into its halves.
445 // Loads and stores are expanded to avoid tying up a register pair.
448 MVT::v2i64, Legal);
450 MVT::v2i64, Custom);
451 }
452
453 // Handle integer vector types.
455 if (Subtarget.hasVector() && isTypeLegal(VT)) {
456 // These operations have direct equivalents.
461 if (VT != MVT::v2i64 || Subtarget.hasVectorEnhancements3()) {
465 }
466 if (Subtarget.hasVectorEnhancements3() &&
467 VT != MVT::v16i8 && VT != MVT::v8i16) {
472 }
477 if (Subtarget.hasVectorEnhancements1())
479 else
483
484 // Convert a GPR scalar to a vector by inserting it into element 0.
486
487 // Use a series of unpacks for extensions.
490
491 // Detect shifts/rotates by a scalar amount and convert them into
492 // V*_BY_SCALAR.
497
498 // Add ISD::VECREDUCE_ADD as custom in order to implement
499 // it with VZERO+VSUM
501
502 // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
503 // and inverting the result as necessary.
505
507 Legal);
509 }
510 }
511
512 if (Subtarget.hasVector()) {
513 // There should be no need to check for float types other than v2f64
514 // since <2 x f32> isn't a legal type.
523
532 }
533
534 if (Subtarget.hasVectorEnhancements2()) {
543
552 }
553
554 // Handle floating-point types.
555 if (!useSoftFloat()) {
556 // Promote all f16 operations to float, with some exceptions below.
557 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
558 setOperationAction(Opc, MVT::f16, Promote);
560 for (MVT VT : {MVT::f32, MVT::f64, MVT::f128}) {
561 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
562 setTruncStoreAction(VT, MVT::f16, Expand);
563 }
565 setOperationAction(Op, MVT::f16, Subtarget.hasVector() ? Legal : Custom);
569
570 for (auto Op : {ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN})
571 setOperationAction(Op, MVT::f16, Legal);
572 }
573
574 for (unsigned I = MVT::FIRST_FP_VALUETYPE;
575 I <= MVT::LAST_FP_VALUETYPE;
576 ++I) {
578 if (isTypeLegal(VT) && VT != MVT::f16) {
579 // We can use FI for FRINT.
581
582 // We can use the extended form of FI for other rounding operations.
583 if (Subtarget.hasFPExtension()) {
590 }
591
592 // No special instructions for these.
598
599 // Special treatment.
601
602 // Handle constrained floating-point operations.
611 if (Subtarget.hasFPExtension()) {
618 }
619
620 // Extension from f16 needs libcall.
623 }
624 }
625
626 // Handle floating-point vector types.
627 if (Subtarget.hasVector()) {
628 // Scalar-to-vector conversion is just a subreg.
632
633 // Some insertions and extractions can be done directly but others
634 // need to go via integers.
641
642 // These operations have direct equivalents.
643 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
644 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
645 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
646 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
647 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
648 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
649 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
650 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
651 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
654 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
658
659 // Handle constrained floating-point operations.
673
678 if (Subtarget.hasVectorEnhancements1()) {
681 }
682 }
683
684 // The vector enhancements facility 1 has instructions for these.
685 if (Subtarget.hasVectorEnhancements1()) {
686 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
687 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
688 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
689 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
690 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
691 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
692 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
693 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
694 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
697 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
701
702 for (MVT Type : {MVT::f64, MVT::v2f64, MVT::f32, MVT::v4f32, MVT::f128}) {
711 }
712
713 // Handle constrained floating-point operations.
727 for (auto VT : { MVT::f32, MVT::f64, MVT::f128,
728 MVT::v4f32, MVT::v2f64 }) {
735 }
736 }
737
738 // We only have fused f128 multiply-addition on vector registers.
739 if (!Subtarget.hasVectorEnhancements1()) {
742 }
743
744 // We don't have a copysign instruction on vector registers.
745 if (Subtarget.hasVectorEnhancements1())
747
748 // Needed so that we don't try to implement f128 constant loads using
749 // a load-and-extend of a f80 constant (in cases where the constant
750 // would fit in an f80).
751 for (MVT VT : MVT::fp_valuetypes())
752 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
753
754 // We don't have extending load instruction on vector registers.
755 if (Subtarget.hasVectorEnhancements1()) {
756 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
757 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
758 }
759
760 // Floating-point truncation and stores need to be done separately.
761 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
762 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
763 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
764
765 // We have 64-bit FPR<->GPR moves, but need special handling for
766 // 32-bit forms.
767 if (!Subtarget.hasVector()) {
770 }
771
772 // VASTART and VACOPY need to deal with the SystemZ-specific varargs
773 // structure, but VAEND is a no-op.
777
778 if (Subtarget.isTargetzOS()) {
779 // Handle address space casts between mixed sized pointers.
782 }
783
785
786 // Codes for which we want to perform some z-specific combinations.
790 ISD::LOAD,
803 ISD::SRL,
804 ISD::SRA,
805 ISD::MUL,
806 ISD::SDIV,
807 ISD::UDIV,
808 ISD::SREM,
809 ISD::UREM,
812
813 // Handle intrinsics.
816
817 // We're not using SJLJ for exception handling, but they're implemented
818 // solely to support use of __builtin_setjmp / __builtin_longjmp.
821
822 // We want to use MVC in preference to even a single load/store pair.
823 MaxStoresPerMemcpy = Subtarget.hasVector() ? 2 : 0;
825
826 // Same with memmove.
827 MaxStoresPerMemmove = Subtarget.hasVector() ? 2 : 0;
829
830 // The main memset sequence is a byte store followed by an MVC.
831 // Two STC or MV..I stores win over that, but the kind of fused stores
832 // generated by target-independent code don't when the byte value is
833 // variable. E.g. "STC <reg>;MHI <reg>,257;STH <reg>" is not better
834 // than "STC;MVC". Handle the choice in target-specific code instead.
835 MaxStoresPerMemset = Subtarget.hasVector() ? 2 : 0;
837
838 // Default to having -disable-strictnode-mutation on
839 IsStrictFPEnabled = true;
840}
841
843 return Subtarget.hasSoftFloat();
844}
845
848 // Widen subvectors to the full width rather than promoting integer
849 // elements. This is better because:
850 //
851 // (a) it means that we can handle the ABI for passing and returning
852 // sub-128 vectors without having to handle them as legal types.
853 //
854 // (b) we don't have instructions to extend on load and truncate on store,
855 // so promoting the integers is less efficient.
856 //
857 // (c) there are no multiplication instructions for the widest integer
858 // type (v2i64).
859
860 // Expand (narrow) f16 vectors during type legalization to avoid
861 // operations for all elements as with expansion after widening. Without
862 // vector support, v2i64 is only legal as a GR128 pair, so do not widen or
863 // promote to it.
864 if (!Subtarget.hasVector() || VT.getScalarType() == MVT::f16)
867 if (VT.getScalarSizeInBits() % 8 == 0)
868 return TypeWidenVector;
870}
871
873 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
874 unsigned &NumIntermediates, MVT &RegisterVT) const {
875 // Pass fp16 vectors in VR(s).
876 if (Subtarget.hasVector() && VT.isVectorOf(MVT::f16)) {
877 IntermediateVT = RegisterVT = MVT::v8f16;
878 return NumIntermediates =
880 }
882 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
883 // Without vector support, v2i64 is a GR128 pair, which is never used to pass
884 // values. Pass the elements individually.
885 if (RegisterVT == MVT::v2i64 && !Subtarget.hasVector()) {
886 IntermediateVT = RegisterVT = MVT::i64;
887 NumIntermediates *= 2;
888 NumRegs *= 2;
889 }
890 return NumRegs;
891}
892
895 EVT VT) const {
896 // 128-bit single-element vector types are passed like other vectors,
897 // not like their element type.
898 if (Subtarget.hasVector() && VT.isVector() && VT.getSizeInBits() == 128 &&
899 VT.getVectorNumElements() == 1)
900 return MVT::v16i8;
901 // Pass fp16 vectors in VR(s).
902 if (Subtarget.hasVector() && VT.isVectorOf(MVT::f16))
903 return MVT::v8f16;
904 MVT RegisterVT =
906 if (RegisterVT == MVT::v2i64 && !Subtarget.hasVector())
907 return MVT::i64;
908 return RegisterVT;
909}
910
912 LLVMContext &Context, CallingConv::ID CC, EVT VT) const {
913 // Pass fp16 vectors in VR(s).
914 if (Subtarget.hasVector() && VT.isVectorOf(MVT::f16))
916 unsigned NumRegs =
918 MVT RegisterVT =
920 if (RegisterVT == MVT::v2i64 && !Subtarget.hasVector())
921 return NumRegs * 2;
922 return NumRegs;
923}
924
926 LLVMContext &, EVT VT) const {
927 if (!VT.isVector())
928 return MVT::i32;
930}
931
933 const MachineFunction &MF, EVT VT) const {
934 if (useSoftFloat())
935 return false;
936
937 VT = VT.getScalarType();
938
939 if (!VT.isSimple())
940 return false;
941
942 switch (VT.getSimpleVT().SimpleTy) {
943 case MVT::f32:
944 case MVT::f64:
945 return true;
946 case MVT::f128:
947 return Subtarget.hasVectorEnhancements1();
948 default:
949 break;
950 }
951
952 return false;
953}
954
955// Return true if the constant can be generated with a vector instruction,
956// such as VGM, VGMB or VREPI.
959 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
960 if (!Subtarget.hasVector() ||
961 (isFP128 && !Subtarget.hasVectorEnhancements1()))
962 return false;
963
964 // Try using VECTOR GENERATE BYTE MASK. This is the architecturally-
965 // preferred way of creating all-zero and all-one vectors so give it
966 // priority over other methods below.
967 unsigned Mask = 0;
968 unsigned I = 0;
969 for (; I < SystemZ::VectorBytes; ++I) {
970 uint64_t Byte = IntBits.lshr(I * 8).trunc(8).getZExtValue();
971 if (Byte == 0xff)
972 Mask |= 1ULL << I;
973 else if (Byte != 0)
974 break;
975 }
976 if (I == SystemZ::VectorBytes) {
977 Opcode = SystemZISD::BYTE_MASK;
978 OpVals.push_back(Mask);
980 return true;
981 }
982
983 if (SplatBitSize > 64)
984 return false;
985
986 auto TryValue = [&](uint64_t Value) -> bool {
987 // Try VECTOR REPLICATE IMMEDIATE
988 int64_t SignedValue = SignExtend64(Value, SplatBitSize);
989 if (isInt<16>(SignedValue)) {
990 OpVals.push_back(((unsigned) SignedValue));
991 Opcode = SystemZISD::REPLICATE;
993 SystemZ::VectorBits / SplatBitSize);
994 return true;
995 }
996 // Try VECTOR GENERATE MASK
997 unsigned Start, End;
998 if (TII->isRxSBGMask(Value, SplatBitSize, Start, End)) {
999 // isRxSBGMask returns the bit numbers for a full 64-bit value, with 0
1000 // denoting 1 << 63 and 63 denoting 1. Convert them to bit numbers for
1001 // an SplatBitSize value, so that 0 denotes 1 << (SplatBitSize-1).
1002 OpVals.push_back(Start - (64 - SplatBitSize));
1003 OpVals.push_back(End - (64 - SplatBitSize));
1004 Opcode = SystemZISD::ROTATE_MASK;
1006 SystemZ::VectorBits / SplatBitSize);
1007 return true;
1008 }
1009 return false;
1010 };
1011
1012 // First try assuming that any undefined bits above the highest set bit
1013 // and below the lowest set bit are 1s. This increases the likelihood of
1014 // being able to use a sign-extended element value in VECTOR REPLICATE
1015 // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
1016 uint64_t SplatBitsZ = SplatBits.getZExtValue();
1017 uint64_t SplatUndefZ = SplatUndef.getZExtValue();
1018 unsigned LowerBits = llvm::countr_zero(SplatBitsZ);
1019 unsigned UpperBits = llvm::countl_zero(SplatBitsZ);
1020 uint64_t Lower = SplatUndefZ & maskTrailingOnes<uint64_t>(LowerBits);
1021 uint64_t Upper = SplatUndefZ & maskLeadingOnes<uint64_t>(UpperBits);
1022 if (TryValue(SplatBitsZ | Upper | Lower))
1023 return true;
1024
1025 // Now try assuming that any undefined bits between the first and
1026 // last defined set bits are set. This increases the chances of
1027 // using a non-wraparound mask.
1028 uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
1029 return TryValue(SplatBitsZ | Middle);
1030}
1031
1033 if (IntImm.isSingleWord()) {
1034 IntBits = APInt(128, IntImm.getZExtValue());
1035 IntBits <<= (SystemZ::VectorBits - IntImm.getBitWidth());
1036 } else
1037 IntBits = IntImm;
1038 assert(IntBits.getBitWidth() == 128 && "Unsupported APInt.");
1039
1040 // Find the smallest splat.
1041 SplatBits = IntImm;
1042 unsigned Width = SplatBits.getBitWidth();
1043 while (Width > 8) {
1044 unsigned HalfSize = Width / 2;
1045 APInt HighValue = SplatBits.lshr(HalfSize).trunc(HalfSize);
1046 APInt LowValue = SplatBits.trunc(HalfSize);
1047
1048 // If the two halves do not match, stop here.
1049 if (HighValue != LowValue || 8 > HalfSize)
1050 break;
1051
1052 SplatBits = HighValue;
1053 Width = HalfSize;
1054 }
1055 SplatUndef = 0;
1056 SplatBitSize = Width;
1057}
1058
1060 assert(BVN->isConstant() && "Expected a constant BUILD_VECTOR");
1061 bool HasAnyUndefs;
1062
1063 // Get IntBits by finding the 128 bit splat.
1064 BVN->isConstantSplat(IntBits, SplatUndef, SplatBitSize, HasAnyUndefs, 128,
1065 true);
1066
1067 // Get SplatBits by finding the 8 bit or greater splat.
1068 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 8,
1069 true);
1070}
1071
1074 bool ForCodeSize) const {
1075 // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
1076 if (Imm.isZero() || Imm.isNegZero())
1077 return FPImmAction::Legal;
1078
1082}
1083
1086 MachineBasicBlock *MBB) const {
1087 DebugLoc DL = MI.getDebugLoc();
1088 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1089 const SystemZRegisterInfo *TRI = Subtarget.getRegisterInfo();
1090
1091 MachineFunction *MF = MBB->getParent();
1093
1094 const BasicBlock *BB = MBB->getBasicBlock();
1095 MachineFunction::iterator I = ++MBB->getIterator();
1096
1097 Register DstReg = MI.getOperand(0).getReg();
1098 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
1099 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
1100 (void)TRI;
1101 Register MainDstReg = MRI.createVirtualRegister(RC);
1102 Register RestoreDstReg = MRI.createVirtualRegister(RC);
1103
1104 MVT PVT = getPointerTy(MF->getDataLayout());
1105 assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
1106 // For v = setjmp(buf), we generate.
1107 // Algorithm:
1108 //
1109 // ---------
1110 // | thisMBB |
1111 // ---------
1112 // |
1113 // ------------------------
1114 // | |
1115 // ---------- ---------------
1116 // | mainMBB | | restoreMBB |
1117 // | v = 0 | | v = 1 |
1118 // ---------- ---------------
1119 // | |
1120 // -------------------------
1121 // |
1122 // -----------------------------
1123 // | sinkMBB |
1124 // | phi(v_mainMBB,v_restoreMBB) |
1125 // -----------------------------
1126 // thisMBB:
1127 // buf[FPOffset] = Frame Pointer if hasFP.
1128 // buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB.
1129 // buf[BCOffset] = Backchain value if building with -mbackchain.
1130 // buf[SPOffset] = Stack Pointer.
1131 // buf[LPOffset] = We never write this slot with R13, gcc stores R13 always.
1132 // SjLjSetup restoreMBB
1133 // mainMBB:
1134 // v_main = 0
1135 // sinkMBB:
1136 // v = phi(v_main, v_restore)
1137 // restoreMBB:
1138 // v_restore = 1
1139
1140 MachineBasicBlock *ThisMBB = MBB;
1141 MachineBasicBlock *MainMBB = MF->CreateMachineBasicBlock(BB);
1142 MachineBasicBlock *SinkMBB = MF->CreateMachineBasicBlock(BB);
1143 MachineBasicBlock *RestoreMBB = MF->CreateMachineBasicBlock(BB);
1144
1145 MF->insert(I, MainMBB);
1146 MF->insert(I, SinkMBB);
1147 MF->push_back(RestoreMBB);
1148 RestoreMBB->setMachineBlockAddressTaken();
1149
1151
1152 // Transfer the remainder of BB and its successor edges to sinkMBB.
1153 SinkMBB->splice(SinkMBB->begin(), MBB,
1154 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
1156
1157 // thisMBB:
1158 const int64_t FPOffset = 0; // Slot 1.
1159 const int64_t LabelOffset = 1 * PVT.getStoreSize(); // Slot 2.
1160 const int64_t BCOffset = 2 * PVT.getStoreSize(); // Slot 3.
1161 const int64_t SPOffset = 3 * PVT.getStoreSize(); // Slot 4.
1162
1163 // Buf address.
1164 Register BufReg = MI.getOperand(1).getReg();
1165
1166 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
1167 Register LabelReg = MRI.createVirtualRegister(PtrRC);
1168
1169 // Prepare IP for longjmp.
1170 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::LARL), LabelReg)
1171 .addMBB(RestoreMBB);
1172 // Store IP for return from jmp, slot 2, offset = 1.
1173 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1174 .addReg(LabelReg)
1175 .addReg(BufReg)
1176 .addImm(LabelOffset)
1177 .addReg(0);
1178
1179 auto *SpecialRegs = Subtarget.getSpecialRegisters();
1180 bool HasFP = Subtarget.getFrameLowering()->hasFP(*MF);
1181 if (HasFP) {
1182 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1183 .addReg(SpecialRegs->getFramePointerRegister())
1184 .addReg(BufReg)
1185 .addImm(FPOffset)
1186 .addReg(0);
1187 }
1188
1189 // Store SP.
1190 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1191 .addReg(SpecialRegs->getStackPointerRegister())
1192 .addReg(BufReg)
1193 .addImm(SPOffset)
1194 .addReg(0);
1195
1196 // Slot 3(Offset = 2) Backchain value (if building with -mbackchain).
1197 bool BackChain = MF->getSubtarget<SystemZSubtarget>().hasBackChain();
1198 if (BackChain) {
1199 Register BCReg = MRI.createVirtualRegister(PtrRC);
1200 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
1201 MIB = BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::LG), BCReg)
1202 .addReg(SpecialRegs->getStackPointerRegister())
1203 .addImm(TFL->getBackchainOffset(*MF))
1204 .addReg(0);
1205
1206 BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::STG))
1207 .addReg(BCReg)
1208 .addReg(BufReg)
1209 .addImm(BCOffset)
1210 .addReg(0);
1211 }
1212
1213 // Setup.
1214 MIB = BuildMI(*ThisMBB, MI, DL, TII->get(SystemZ::EH_SjLj_Setup))
1215 .addMBB(RestoreMBB);
1216
1217 const SystemZRegisterInfo *RegInfo = Subtarget.getRegisterInfo();
1218 MIB.addRegMask(RegInfo->getNoPreservedMask());
1219
1220 ThisMBB->addSuccessor(MainMBB);
1221 ThisMBB->addSuccessor(RestoreMBB);
1222
1223 // mainMBB:
1224 BuildMI(MainMBB, DL, TII->get(SystemZ::LHI), MainDstReg).addImm(0);
1225 MainMBB->addSuccessor(SinkMBB);
1226
1227 // sinkMBB:
1228 BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII->get(SystemZ::PHI), DstReg)
1229 .addReg(MainDstReg)
1230 .addMBB(MainMBB)
1231 .addReg(RestoreDstReg)
1232 .addMBB(RestoreMBB);
1233
1234 // restoreMBB.
1235 BuildMI(RestoreMBB, DL, TII->get(SystemZ::LHI), RestoreDstReg).addImm(1);
1236 BuildMI(RestoreMBB, DL, TII->get(SystemZ::J)).addMBB(SinkMBB);
1237 RestoreMBB->addSuccessor(SinkMBB);
1238
1239 MI.eraseFromParent();
1240
1241 return SinkMBB;
1242}
1243
1246 MachineBasicBlock *MBB) const {
1247
1248 DebugLoc DL = MI.getDebugLoc();
1249 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1250
1251 MachineFunction *MF = MBB->getParent();
1253
1254 MVT PVT = getPointerTy(MF->getDataLayout());
1255 assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!");
1256 Register BufReg = MI.getOperand(0).getReg();
1257 const TargetRegisterClass *RC = MRI.getRegClass(BufReg);
1258 auto *SpecialRegs = Subtarget.getSpecialRegisters();
1259
1260 Register Tmp = MRI.createVirtualRegister(RC);
1261 Register BCReg = MRI.createVirtualRegister(RC);
1262
1264
1265 const int64_t FPOffset = 0;
1266 const int64_t LabelOffset = 1 * PVT.getStoreSize();
1267 const int64_t BCOffset = 2 * PVT.getStoreSize();
1268 const int64_t SPOffset = 3 * PVT.getStoreSize();
1269 const int64_t LPOffset = 4 * PVT.getStoreSize();
1270
1271 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG), Tmp)
1272 .addReg(BufReg)
1273 .addImm(LabelOffset)
1274 .addReg(0);
1275
1276 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG),
1277 SpecialRegs->getFramePointerRegister())
1278 .addReg(BufReg)
1279 .addImm(FPOffset)
1280 .addReg(0);
1281
1282 // We are restoring R13 even though we never stored in setjmp from llvm,
1283 // as gcc always stores R13 in builtin_setjmp. We could have mixed code
1284 // gcc setjmp and llvm longjmp.
1285 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG), SystemZ::R13D)
1286 .addReg(BufReg)
1287 .addImm(LPOffset)
1288 .addReg(0);
1289
1290 bool BackChain = MF->getSubtarget<SystemZSubtarget>().hasBackChain();
1291 if (BackChain) {
1292 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG), BCReg)
1293 .addReg(BufReg)
1294 .addImm(BCOffset)
1295 .addReg(0);
1296 }
1297
1298 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::LG),
1299 SpecialRegs->getStackPointerRegister())
1300 .addReg(BufReg)
1301 .addImm(SPOffset)
1302 .addReg(0);
1303
1304 if (BackChain) {
1305 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
1306 BuildMI(*MBB, MI, DL, TII->get(SystemZ::STG))
1307 .addReg(BCReg)
1308 .addReg(SpecialRegs->getStackPointerRegister())
1309 .addImm(TFL->getBackchainOffset(*MF))
1310 .addReg(0);
1311 }
1312
1313 MIB = BuildMI(*MBB, MI, DL, TII->get(SystemZ::BR)).addReg(Tmp);
1314
1315 MI.eraseFromParent();
1316 return MBB;
1317}
1318
1320 const MachineFunction &MF) const {
1321 // Without vector support, a v2i64 store would just be split again.
1322 return MemVT != MVT::v2i64 || Subtarget.hasVector();
1323}
1324
1326 EVT VecVT) const {
1327 // Without vector support, a v2i64 is just a pair of GPRs.
1328 return !Subtarget.hasVector();
1329}
1330
1331/// Returns true if stack probing through inline assembly is requested.
1333 // If the function specifically requests inline stack probes, emit them.
1334 if (MF.getFunction().hasFnAttribute("probe-stack"))
1335 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
1336 "inline-asm";
1337 return false;
1338}
1339
1344
1349
1352 const AtomicRMWInst *RMW) const {
1353 // Don't expand subword operations as they require special treatment.
1354 if (RMW->getType()->isIntegerTy(8) || RMW->getType()->isIntegerTy(16))
1356
1357 // Don't expand if there is a target instruction available.
1358 if (Subtarget.hasInterlockedAccess1() &&
1359 (RMW->getType()->isIntegerTy(32) || RMW->getType()->isIntegerTy(64)) &&
1366
1368}
1369
1371 // We can use CGFI or CLGFI.
1372 return isInt<32>(Imm) || isUInt<32>(Imm);
1373}
1374
1376 // We can use ALGFI or SLGFI.
1377 return isUInt<32>(Imm) || isUInt<32>(-Imm);
1378}
1379
1381 EVT VT, unsigned, Align, MachineMemOperand::Flags, unsigned *Fast) const {
1382 // Unaligned accesses should never be slower than the expanded version.
1383 // We check specifically for aligned accesses in the few cases where
1384 // they are required.
1385 if (Fast)
1386 *Fast = 1;
1387 return true;
1388}
1389
1391 EVT VT = Y.getValueType();
1392
1393 // We can use NC(G)RK for types in GPRs ...
1394 if (VT == MVT::i32 || VT == MVT::i64)
1395 return Subtarget.hasMiscellaneousExtensions3();
1396
1397 // ... or VNC for types in VRs.
1398 if (VT.isVector() || VT == MVT::i128)
1399 return Subtarget.hasVector();
1400
1401 return false;
1402}
1403
1404// Information about the addressing mode for a memory access.
1406 // True if a long displacement is supported.
1408
1409 // True if use of index register is supported.
1411
1412 AddressingMode(bool LongDispl, bool IdxReg) :
1413 LongDisplacement(LongDispl), IndexReg(IdxReg) {}
1414};
1415
1416// Return the desired addressing mode for a Load which has only one use (in
1417// the same block) which is a Store.
1419 Type *Ty) {
1420 // With vector support a Load->Store combination may be combined to either
1421 // an MVC or vector operations and it seems to work best to allow the
1422 // vector addressing mode.
1423 if (HasVector)
1424 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
1425
1426 // Otherwise only the MVC case is special.
1427 bool MVC = Ty->isIntegerTy(8);
1428 return AddressingMode(!MVC/*LongDispl*/, !MVC/*IdxReg*/);
1429}
1430
1431// Return the addressing mode which seems most desirable given an LLVM
1432// Instruction pointer.
1433static AddressingMode
1436 switch (II->getIntrinsicID()) {
1437 default: break;
1438 case Intrinsic::memset:
1439 case Intrinsic::memmove:
1440 case Intrinsic::memcpy:
1441 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
1442 }
1443 }
1444
1445 if (isa<LoadInst>(I) && I->hasOneUse()) {
1446 auto *SingleUser = cast<Instruction>(*I->user_begin());
1447 if (SingleUser->getParent() == I->getParent()) {
1448 if (isa<ICmpInst>(SingleUser)) {
1449 if (auto *C = dyn_cast<ConstantInt>(SingleUser->getOperand(1)))
1450 if (C->getBitWidth() <= 64 &&
1451 (isInt<16>(C->getSExtValue()) || isUInt<16>(C->getZExtValue())))
1452 // Comparison of memory with 16 bit signed / unsigned immediate
1453 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
1454 } else if (isa<StoreInst>(SingleUser))
1455 // Load->Store
1456 return getLoadStoreAddrMode(HasVector, I->getType());
1457 }
1458 } else if (auto *StoreI = dyn_cast<StoreInst>(I)) {
1459 if (auto *LoadI = dyn_cast<LoadInst>(StoreI->getValueOperand()))
1460 if (LoadI->hasOneUse() && LoadI->getParent() == I->getParent())
1461 // Load->Store
1462 return getLoadStoreAddrMode(HasVector, LoadI->getType());
1463 }
1464
1465 if (HasVector && (isa<LoadInst>(I) || isa<StoreInst>(I))) {
1466
1467 // * Use LDE instead of LE/LEY for z13 to avoid partial register
1468 // dependencies (LDE only supports small offsets).
1469 // * Utilize the vector registers to hold floating point
1470 // values (vector load / store instructions only support small
1471 // offsets).
1472
1473 Type *MemAccessTy = (isa<LoadInst>(I) ? I->getType() :
1474 I->getOperand(0)->getType());
1475 bool IsFPAccess = MemAccessTy->isFloatingPointTy();
1476 bool IsVectorAccess = MemAccessTy->isVectorTy();
1477
1478 // A store of an extracted vector element will be combined into a VSTE type
1479 // instruction.
1480 if (!IsVectorAccess && isa<StoreInst>(I)) {
1481 Value *DataOp = I->getOperand(0);
1482 if (isa<ExtractElementInst>(DataOp))
1483 IsVectorAccess = true;
1484 }
1485
1486 // A load which gets inserted into a vector element will be combined into a
1487 // VLE type instruction.
1488 if (!IsVectorAccess && isa<LoadInst>(I) && I->hasOneUse()) {
1489 User *LoadUser = *I->user_begin();
1490 if (isa<InsertElementInst>(LoadUser))
1491 IsVectorAccess = true;
1492 }
1493
1494 if (IsFPAccess || IsVectorAccess)
1495 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
1496 }
1497
1498 return AddressingMode(true/*LongDispl*/, true/*IdxReg*/);
1499}
1500
1502 const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I) const {
1503 // Punt on globals for now, although they can be used in limited
1504 // RELATIVE LONG cases.
1505 if (AM.BaseGV)
1506 return false;
1507
1508 // Require a 20-bit signed offset.
1509 if (!isInt<20>(AM.BaseOffs))
1510 return false;
1511
1512 bool RequireD12 =
1513 Subtarget.hasVector() && (Ty->isVectorTy() || Ty->isIntegerTy(128));
1514 AddressingMode SupportedAM(!RequireD12, true);
1515 if (I != nullptr)
1516 SupportedAM = supportedAddressingMode(I, Subtarget.hasVector());
1517
1518 if (!SupportedAM.LongDisplacement && !isUInt<12>(AM.BaseOffs))
1519 return false;
1520
1521 if (!SupportedAM.IndexReg)
1522 // No indexing allowed.
1523 return AM.Scale == 0;
1524 else
1525 // Indexing is OK but no scale factor can be applied.
1526 return AM.Scale == 0 || AM.Scale == 1;
1527}
1528
1530 LLVMContext &Context, std::vector<EVT> &MemOps, unsigned Limit,
1531 const MemOp &Op, unsigned DstAS, unsigned SrcAS,
1532 const AttributeList &FuncAttributes, EVT *LargestVT) const {
1533
1534 assert(Limit != ~0U &&
1535 "Expected EmitTargetCodeForMemXXX() to handle AlwaysInline cases.");
1536
1537 if (Op.isZeroMemset())
1538 return false; // Memset zero: Use XC.
1539
1540 const int MVCFastLen = 16;
1541 // Use MVC up to 16 bytes for memcpy. Small memset uses STC/MVI for first
1542 // byte.
1543 if (Op.isMemcpy() && Op.size() <= MVCFastLen)
1544 return false;
1545 if (Op.isMemset() && Op.size() - 1 <= MVCFastLen)
1546 return false;
1547
1548 // Avoid unaligned VL/VST:s.
1549 if ((Op.size() >= 16 && !Op.isAligned(Align(8))) ||
1550 (Op.size() >= 25 && Op.size() <= 31))
1551 return false;
1552
1554 Context, MemOps, Limit, Op, DstAS, SrcAS, FuncAttributes, LargestVT);
1555}
1556
1558 LLVMContext &Context, const MemOp &Op,
1559 const AttributeList &FuncAttributes) const {
1560 return Subtarget.hasVector() ? MVT::v2i64 : MVT::Other;
1561}
1562
1563bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
1564 if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
1565 return false;
1566 unsigned FromBits = FromType->getPrimitiveSizeInBits().getFixedValue();
1567 unsigned ToBits = ToType->getPrimitiveSizeInBits().getFixedValue();
1568 return FromBits > ToBits;
1569}
1570
1572 if (!FromVT.isInteger() || !ToVT.isInteger())
1573 return false;
1574 unsigned FromBits = FromVT.getFixedSizeInBits();
1575 unsigned ToBits = ToVT.getFixedSizeInBits();
1576 return FromBits > ToBits;
1577}
1578
1580 unsigned Opc = N->getOpcode();
1581 if ((Opc == ISD::SINT_TO_FP || Opc == ISD::UINT_TO_FP) && VT.isVector() &&
1582 VT.getScalarSizeInBits() < N->getValueType(0).getScalarSizeInBits())
1583 return false;
1585}
1586
1587//===----------------------------------------------------------------------===//
1588// Inline asm support
1589//===----------------------------------------------------------------------===//
1590
1593 if (Constraint.size() == 1) {
1594 switch (Constraint[0]) {
1595 case 'a': // Address register
1596 case 'd': // Data register (equivalent to 'r')
1597 case 'f': // Floating-point register
1598 case 'h': // High-part register
1599 case 'r': // General-purpose register
1600 case 'v': // Vector register
1601 return C_RegisterClass;
1602
1603 case 'Q': // Memory with base and unsigned 12-bit displacement
1604 case 'R': // Likewise, plus an index
1605 case 'S': // Memory with base and signed 20-bit displacement
1606 case 'T': // Likewise, plus an index
1607 case 'm': // Equivalent to 'T'.
1608 return C_Memory;
1609
1610 case 'I': // Unsigned 8-bit constant
1611 case 'J': // Unsigned 12-bit constant
1612 case 'K': // Signed 16-bit constant
1613 case 'L': // Signed 20-bit displacement (on all targets we support)
1614 case 'M': // 0x7fffffff
1615 return C_Immediate;
1616
1617 default:
1618 break;
1619 }
1620 } else if (Constraint.size() == 2 && Constraint[0] == 'Z') {
1621 switch (Constraint[1]) {
1622 case 'Q': // Address with base and unsigned 12-bit displacement
1623 case 'R': // Likewise, plus an index
1624 case 'S': // Address with base and signed 20-bit displacement
1625 case 'T': // Likewise, plus an index
1626 return C_Address;
1627
1628 default:
1629 break;
1630 }
1631 } else if (Constraint.size() == 5 && Constraint.starts_with("{")) {
1632 if (StringRef("{@cc}").compare(Constraint) == 0)
1633 return C_Other;
1634 }
1635 return TargetLowering::getConstraintType(Constraint);
1636}
1637
1640 AsmOperandInfo &Info, const char *Constraint) const {
1642 Value *CallOperandVal = Info.CallOperandVal;
1643 // If we don't have a value, we can't do a match,
1644 // but allow it at the lowest weight.
1645 if (!CallOperandVal)
1646 return CW_Default;
1647 Type *type = CallOperandVal->getType();
1648 // Look at the constraint type.
1649 switch (*Constraint) {
1650 default:
1651 Weight = TargetLowering::getSingleConstraintMatchWeight(Info, Constraint);
1652 break;
1653
1654 case 'a': // Address register
1655 case 'd': // Data register (equivalent to 'r')
1656 case 'h': // High-part register
1657 case 'r': // General-purpose register
1658 Weight =
1659 CallOperandVal->getType()->isIntegerTy() ? CW_Register : CW_Default;
1660 break;
1661
1662 case 'f': // Floating-point register
1663 if (!useSoftFloat())
1664 Weight = type->isFloatingPointTy() ? CW_Register : CW_Default;
1665 break;
1666
1667 case 'v': // Vector register
1668 if (Subtarget.hasVector())
1669 Weight = (type->isVectorTy() || type->isFloatingPointTy()) ? CW_Register
1670 : CW_Default;
1671 break;
1672
1673 case 'I': // Unsigned 8-bit constant
1674 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1675 if (isUInt<8>(C->getZExtValue()))
1676 Weight = CW_Constant;
1677 break;
1678
1679 case 'J': // Unsigned 12-bit constant
1680 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1681 if (isUInt<12>(C->getZExtValue()))
1682 Weight = CW_Constant;
1683 break;
1684
1685 case 'K': // Signed 16-bit constant
1686 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1687 if (isInt<16>(C->getSExtValue()))
1688 Weight = CW_Constant;
1689 break;
1690
1691 case 'L': // Signed 20-bit displacement (on all targets we support)
1692 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1693 if (isInt<20>(C->getSExtValue()))
1694 Weight = CW_Constant;
1695 break;
1696
1697 case 'M': // 0x7fffffff
1698 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1699 if (C->getZExtValue() == 0x7fffffff)
1700 Weight = CW_Constant;
1701 break;
1702 }
1703 return Weight;
1704}
1705
1706// Parse a "{tNNN}" register constraint for which the register type "t"
1707// has already been verified. MC is the class associated with "t" and
1708// Map maps 0-based register numbers to LLVM register numbers.
1709static std::pair<unsigned, const TargetRegisterClass *>
1711 const unsigned *Map, unsigned Size) {
1712 assert(*(Constraint.end()-1) == '}' && "Missing '}'");
1713 if (isdigit(Constraint[2])) {
1714 unsigned Index;
1715 bool Failed =
1716 Constraint.slice(2, Constraint.size() - 1).getAsInteger(10, Index);
1717 if (!Failed && Index < Size && Map[Index])
1718 return std::make_pair(Map[Index], RC);
1719 }
1720 return std::make_pair(0U, nullptr);
1721}
1722
1723std::pair<unsigned, const TargetRegisterClass *>
1725 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
1726 if (Constraint.size() == 1) {
1727 // GCC Constraint Letters
1728 switch (Constraint[0]) {
1729 default: break;
1730 case 'd': // Data register (equivalent to 'r')
1731 case 'r': // General-purpose register
1732 // MVT::Other has no size, e.g. an aggregate operand that could not be
1733 // converted to an integer type.
1734 if (VT == MVT::Other)
1735 break;
1736 if (VT.getSizeInBits() == 64)
1737 return std::make_pair(0U, &SystemZ::GR64BitRegClass);
1738 else if (VT.getSizeInBits() == 128)
1739 return std::make_pair(0U, &SystemZ::GR128BitRegClass);
1740 return std::make_pair(0U, &SystemZ::GR32BitRegClass);
1741
1742 case 'a': // Address register
1743 if (VT == MVT::i64)
1744 return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
1745 else if (VT == MVT::i128)
1746 return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
1747 return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
1748
1749 case 'h': // High-part register (an LLVM extension)
1750 return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
1751
1752 case 'f': // Floating-point register
1753 if (!useSoftFloat()) {
1754 if (VT == MVT::Other)
1755 break;
1756 if (VT.getSizeInBits() == 16)
1757 return std::make_pair(0U, &SystemZ::FP16BitRegClass);
1758 else if (VT.getSizeInBits() == 64)
1759 return std::make_pair(0U, &SystemZ::FP64BitRegClass);
1760 else if (VT.getSizeInBits() == 128)
1761 return std::make_pair(0U, &SystemZ::FP128BitRegClass);
1762 return std::make_pair(0U, &SystemZ::FP32BitRegClass);
1763 }
1764 break;
1765
1766 case 'v': // Vector register
1767 if (Subtarget.hasVector()) {
1768 if (VT == MVT::Other)
1769 break;
1770 if (VT.getSizeInBits() == 16)
1771 return std::make_pair(0U, &SystemZ::VR16BitRegClass);
1772 if (VT.getSizeInBits() == 32)
1773 return std::make_pair(0U, &SystemZ::VR32BitRegClass);
1774 if (VT.getSizeInBits() == 64)
1775 return std::make_pair(0U, &SystemZ::VR64BitRegClass);
1776 return std::make_pair(0U, &SystemZ::VR128BitRegClass);
1777 }
1778 break;
1779 }
1780 }
1781 if (Constraint.starts_with("{")) {
1782
1783 // A clobber constraint (e.g. ~{f0}) will have MVT::Other which is illegal
1784 // to check the size on.
1785 auto getVTSizeInBits = [&VT]() {
1786 return VT == MVT::Other ? 0 : VT.getSizeInBits();
1787 };
1788
1789 // We need to override the default register parsing for GPRs and FPRs
1790 // because the interpretation depends on VT. The internal names of
1791 // the registers are also different from the external names
1792 // (F0D and F0S instead of F0, etc.).
1793 if (Constraint[1] == 'r') {
1794 if (getVTSizeInBits() == 32)
1795 return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
1797 if (getVTSizeInBits() == 128)
1798 return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
1800 return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
1802 }
1803 if (Constraint[1] == 'f') {
1804 if (useSoftFloat())
1805 return std::make_pair(
1806 0u, static_cast<const TargetRegisterClass *>(nullptr));
1807 if (getVTSizeInBits() == 16)
1808 return parseRegisterNumber(Constraint, &SystemZ::FP16BitRegClass,
1810 if (getVTSizeInBits() == 32)
1811 return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
1813 if (getVTSizeInBits() == 128)
1814 return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
1816 return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
1818 }
1819 if (Constraint[1] == 'v') {
1820 if (!Subtarget.hasVector())
1821 return std::make_pair(
1822 0u, static_cast<const TargetRegisterClass *>(nullptr));
1823 if (getVTSizeInBits() == 16)
1824 return parseRegisterNumber(Constraint, &SystemZ::VR16BitRegClass,
1826 if (getVTSizeInBits() == 32)
1827 return parseRegisterNumber(Constraint, &SystemZ::VR32BitRegClass,
1829 if (getVTSizeInBits() == 64)
1830 return parseRegisterNumber(Constraint, &SystemZ::VR64BitRegClass,
1832 return parseRegisterNumber(Constraint, &SystemZ::VR128BitRegClass,
1834 }
1835 if (Constraint[1] == '@') {
1836 if (StringRef("{@cc}").compare(Constraint) == 0)
1837 return std::make_pair(SystemZ::CC, &SystemZ::CCRRegClass);
1838 }
1839 }
1840 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1841}
1842
1843// FIXME? Maybe this could be a TableGen attribute on some registers and
1844// this table could be generated automatically from RegInfo.
1847 const MachineFunction &MF) const {
1848 Register Reg =
1850 .Case("r4", Subtarget.isTargetXPLINK64() ? SystemZ::R4D
1851 : SystemZ::NoRegister)
1852 .Case("r15",
1853 Subtarget.isTargetELF() ? SystemZ::R15D : SystemZ::NoRegister)
1854 .Default(Register());
1855
1856 return Reg;
1857}
1858
1860 ExceptionHandling EH, const Constant *PersonalityFn) const {
1861 return Subtarget.isTargetXPLINK64() ? SystemZ::R1D : SystemZ::R6D;
1862}
1863
1865 ExceptionHandling EH, const Constant *PersonalityFn) const {
1866 return Subtarget.isTargetXPLINK64() ? SystemZ::R2D : SystemZ::R7D;
1867}
1868
1869// Convert condition code in CCReg to an i32 value.
1871 SDLoc DL(CCReg);
1872 SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, CCReg);
1873 return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM,
1874 DAG.getConstant(SystemZ::IPM_CC, DL, MVT::i32));
1875}
1876
1877// Lower @cc targets via setcc.
1879 SDValue &Chain, SDValue &Glue, const SDLoc &DL,
1880 const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
1881 if (StringRef("{@cc}").compare(OpInfo.ConstraintCode) != 0)
1882 return SDValue();
1883
1884 // Check that return type is valid.
1885 if (OpInfo.ConstraintVT.isVector() || !OpInfo.ConstraintVT.isInteger() ||
1886 OpInfo.ConstraintVT.getSizeInBits() < 8)
1887 report_fatal_error("Glue output operand is of invalid type");
1888
1889 if (Glue.getNode()) {
1890 Glue = DAG.getCopyFromReg(Chain, DL, SystemZ::CC, MVT::i32, Glue);
1891 Chain = Glue.getValue(1);
1892 } else
1893 Glue = DAG.getCopyFromReg(Chain, DL, SystemZ::CC, MVT::i32);
1894 return getCCResult(DAG, Glue);
1895}
1896
1898 SDValue Op, StringRef Constraint, std::vector<SDValue> &Ops,
1899 SelectionDAG &DAG) const {
1900 // Only support length 1 constraints for now.
1901 if (Constraint.size() == 1) {
1902 switch (Constraint[0]) {
1903 case 'I': // Unsigned 8-bit constant
1904 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1905 if (isUInt<8>(C->getZExtValue()))
1906 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1907 Op.getValueType()));
1908 return;
1909
1910 case 'J': // Unsigned 12-bit constant
1911 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1912 if (isUInt<12>(C->getZExtValue()))
1913 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1914 Op.getValueType()));
1915 return;
1916
1917 case 'K': // Signed 16-bit constant
1918 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1919 if (isInt<16>(C->getSExtValue()))
1920 Ops.push_back(DAG.getSignedTargetConstant(
1921 C->getSExtValue(), SDLoc(Op), Op.getValueType()));
1922 return;
1923
1924 case 'L': // Signed 20-bit displacement (on all targets we support)
1925 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1926 if (isInt<20>(C->getSExtValue()))
1927 Ops.push_back(DAG.getSignedTargetConstant(
1928 C->getSExtValue(), SDLoc(Op), Op.getValueType()));
1929 return;
1930
1931 case 'M': // 0x7fffffff
1932 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1933 if (C->getZExtValue() == 0x7fffffff)
1934 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1935 Op.getValueType()));
1936 return;
1937 }
1938 }
1940}
1941
1942//===----------------------------------------------------------------------===//
1943// Calling conventions
1944//===----------------------------------------------------------------------===//
1945
1946#define GET_CALLING_CONV_IMPL
1947#include "SystemZGenCallingConv.inc"
1948
1950 CallingConv::ID) const {
1951 static const MCPhysReg ScratchRegs[] = { SystemZ::R0D, SystemZ::R1D,
1952 SystemZ::R14D, 0 };
1953 return ScratchRegs;
1954}
1955
1957 Type *ToType) const {
1958 return isTruncateFree(FromType, ToType);
1959}
1960
1962 return CI->isTailCall();
1963}
1964
1965// Value is a value that has been passed to us in the location described by VA
1966// (and so has type VA.getLocVT()). Convert Value to VA.getValVT(), chaining
1967// any loads onto Chain.
1969 CCValAssign &VA, SDValue Chain,
1970 SDValue Value) {
1971 // If the argument has been promoted from a smaller type, insert an
1972 // assertion to capture this.
1973 if (VA.getLocInfo() == CCValAssign::SExt)
1975 DAG.getValueType(VA.getValVT()));
1976 else if (VA.getLocInfo() == CCValAssign::ZExt)
1978 DAG.getValueType(VA.getValVT()));
1979
1980 if (VA.isExtInLoc())
1981 Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
1982 else if (VA.getLocInfo() == CCValAssign::BCvt) {
1983 // If this is a short vector argument loaded from the stack,
1984 // extend from i64 to full vector size and then bitcast.
1985 assert(VA.getLocVT() == MVT::i64);
1986 assert(VA.getValVT().isVector());
1987 Value = DAG.getBuildVector(MVT::v2i64, DL, {Value, DAG.getUNDEF(MVT::i64)});
1988 Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
1989 } else
1990 assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
1991 return Value;
1992}
1993
1994// Value is a value of type VA.getValVT() that we need to copy into
1995// the location described by VA. Return a copy of Value converted to
1996// VA.getValVT(). The caller is responsible for handling indirect values.
1998 CCValAssign &VA, SDValue Value) {
1999 switch (VA.getLocInfo()) {
2000 case CCValAssign::SExt:
2001 return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
2002 case CCValAssign::ZExt:
2003 return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
2004 case CCValAssign::AExt:
2005 return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
2006 case CCValAssign::BCvt: {
2007 assert(VA.getLocVT() == MVT::i64 || VA.getLocVT() == MVT::i128);
2008 assert(VA.getValVT().isVector() || VA.getValVT() == MVT::f32 ||
2009 VA.getValVT() == MVT::f64 || VA.getValVT() == MVT::f128);
2010 // For an f32 vararg we need to first promote it to an f64 and then
2011 // bitcast it to an i64.
2012 if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i64)
2013 Value = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f64, Value);
2014 MVT BitCastToType = VA.getValVT().isVector() && VA.getLocVT() == MVT::i64
2015 ? MVT::v2i64
2016 : VA.getLocVT();
2017 Value = DAG.getNode(ISD::BITCAST, DL, BitCastToType, Value);
2018 // For ELF, this is a short vector argument to be stored to the stack,
2019 // bitcast to v2i64 and then extract first element.
2020 if (BitCastToType == MVT::v2i64)
2021 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
2022 DAG.getConstant(0, DL, MVT::i32));
2023 return Value;
2024 }
2025 case CCValAssign::Full:
2026 return Value;
2027 default:
2028 llvm_unreachable("Unhandled getLocInfo()");
2029 }
2030}
2031
2033 SDLoc DL(In);
2034 SDValue Lo, Hi;
2035 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128)) {
2036 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, In);
2037 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
2038 DAG.getNode(ISD::SRL, DL, MVT::i128, In,
2039 DAG.getConstant(64, DL, MVT::i32)));
2040 } else {
2041 std::tie(Lo, Hi) = DAG.SplitScalar(In, DL, MVT::i64, MVT::i64);
2042 }
2043
2044 return DAG.getNode(SystemZISD::PAIR128, DL, MVT::v2i64, Hi, Lo);
2045}
2046
2048 SDLoc DL(In);
2049 SDValue Hi = DAG.getTargetExtractSubreg(SystemZ::subreg_h64,
2050 DL, MVT::i64, In);
2051 SDValue Lo = DAG.getTargetExtractSubreg(SystemZ::subreg_l64,
2052 DL, MVT::i64, In);
2053
2054 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128)) {
2055 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, Lo);
2056 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, Hi);
2057 Hi = DAG.getNode(ISD::SHL, DL, MVT::i128, Hi,
2058 DAG.getConstant(64, DL, MVT::i32));
2059 return DAG.getNode(ISD::OR, DL, MVT::i128, Lo, Hi);
2060 } else {
2061 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128, Lo, Hi);
2062 }
2063}
2064
2066 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
2067 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
2068 EVT ValueVT = Val.getValueType();
2069 if (ValueVT.getSizeInBits() == 128 && NumParts == 1 && PartVT == MVT::Untyped) {
2070 // Inline assembly operand.
2071 Parts[0] = lowerI128ToGR128(DAG, DAG.getBitcast(MVT::i128, Val));
2072 return true;
2073 }
2074
2075 return false;
2076}
2077
2079 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
2080 MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const {
2081 if (ValueVT.getSizeInBits() == 128 && NumParts == 1 && PartVT == MVT::Untyped) {
2082 // Inline assembly operand.
2083 SDValue Res = lowerGR128ToI128(DAG, Parts[0]);
2084 return DAG.getBitcast(ValueVT, Res);
2085 }
2086
2087 return SDValue();
2088}
2089
2090// The first part of a split stack argument is at index I in Args (and
2091// ArgLocs). Return the type of a part and the number of them by reference.
2092template <class ArgTy>
2094 SmallVector<CCValAssign, 16> &ArgLocs, unsigned I,
2095 MVT &PartVT, unsigned &NumParts) {
2096 if (!Args[I].Flags.isSplit())
2097 return false;
2098 assert(I < ArgLocs.size() && ArgLocs.size() == Args.size() &&
2099 "ArgLocs havoc.");
2100 PartVT = ArgLocs[I].getValVT();
2101 NumParts = 1;
2102 for (unsigned PartIdx = I + 1;; ++PartIdx) {
2103 assert(PartIdx != ArgLocs.size() && "SplitEnd not found.");
2104 assert(ArgLocs[PartIdx].getValVT() == PartVT && "Unsupported split.");
2105 ++NumParts;
2106 if (Args[PartIdx].Flags.isSplitEnd())
2107 break;
2108 }
2109 return true;
2110}
2111
2112// Return the virtual register holding the incoming "ADA" special register (R5)
2113// of an XPLINK function, creating it on first use. LowerFormalArguments is not
2114// called for naked functions, but those still get R5 on entry and may use it to
2115// address globals and functions.
2117 SystemZMachineFunctionInfo *FuncInfo =
2119 Register ADAvReg = FuncInfo->getADAVirtualRegister();
2120 if (ADAvReg)
2121 return ADAvReg;
2122
2124 ADAvReg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
2125 auto *Regs = static_cast<SystemZXPLINK64Registers *>(
2127 MRI.addLiveIn(Regs->getADARegister(), ADAvReg);
2128 FuncInfo->setADAVirtualRegister(ADAvReg);
2129 return ADAvReg;
2130}
2131
2133 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
2134 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2135 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2137 MachineFrameInfo &MFI = MF.getFrameInfo();
2139 SystemZMachineFunctionInfo *FuncInfo =
2141 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>();
2142 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2143
2144 // Assign locations to all of the incoming arguments.
2146 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2147 CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
2148 FuncInfo->setSizeOfFnParams(CCInfo.getStackSize());
2149
2150 unsigned NumFixedGPRs = 0;
2151 unsigned NumFixedFPRs = 0;
2152 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
2153 SDValue ArgValue;
2154 CCValAssign &VA = ArgLocs[I];
2155 EVT LocVT = VA.getLocVT();
2156 if (VA.isRegLoc()) {
2157 // Arguments passed in registers
2158 const TargetRegisterClass *RC;
2159 switch (LocVT.getSimpleVT().SimpleTy) {
2160 default:
2161 // Integers smaller than i64 should be promoted to i64.
2162 llvm_unreachable("Unexpected argument type");
2163 case MVT::i32:
2164 NumFixedGPRs += 1;
2165 RC = &SystemZ::GR32BitRegClass;
2166 break;
2167 case MVT::i64:
2168 NumFixedGPRs += 1;
2169 RC = &SystemZ::GR64BitRegClass;
2170 break;
2171 case MVT::f16:
2172 NumFixedFPRs += 1;
2173 RC = &SystemZ::FP16BitRegClass;
2174 break;
2175 case MVT::f32:
2176 NumFixedFPRs += 1;
2177 RC = &SystemZ::FP32BitRegClass;
2178 break;
2179 case MVT::f64:
2180 NumFixedFPRs += 1;
2181 RC = &SystemZ::FP64BitRegClass;
2182 break;
2183 case MVT::f128:
2184 NumFixedFPRs += 2;
2185 RC = &SystemZ::FP128BitRegClass;
2186 break;
2187 case MVT::v16i8:
2188 case MVT::v8i16:
2189 case MVT::v4i32:
2190 case MVT::v2i64:
2191 case MVT::v8f16:
2192 case MVT::v4f32:
2193 case MVT::v2f64:
2194 RC = &SystemZ::VR128BitRegClass;
2195 break;
2196 }
2197
2198 Register VReg = MRI.createVirtualRegister(RC);
2199 MRI.addLiveIn(VA.getLocReg(), VReg);
2200 ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
2201 } else {
2202 assert(VA.isMemLoc() && "Argument not register or memory");
2203
2204 // Create the frame index object for this incoming parameter.
2205 // FIXME: Pre-include call frame size in the offset, should not
2206 // need to manually add it here.
2207 int64_t ArgSPOffset = VA.getLocMemOffset();
2208 if (Subtarget.isTargetXPLINK64()) {
2209 auto &XPRegs =
2210 Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
2211 ArgSPOffset += XPRegs.getCallFrameSize();
2212 }
2213 int FI =
2214 MFI.CreateFixedObject(LocVT.getSizeInBits() / 8, ArgSPOffset, true);
2215
2216 // Create the SelectionDAG nodes corresponding to a load
2217 // from this parameter. Unpromoted ints and floats are
2218 // passed as right-justified 8-byte values.
2219 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2220 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32 ||
2221 VA.getLocVT() == MVT::f16) {
2222 unsigned SlotOffs = VA.getLocVT() == MVT::f16 ? 6 : 4;
2223 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2224 DAG.getIntPtrConstant(SlotOffs, DL));
2225 }
2226 ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
2228 }
2229
2230 // Convert the value of the argument register into the value that's
2231 // being passed.
2232 if (VA.getLocInfo() == CCValAssign::Indirect) {
2233 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
2235 // If the original argument was split (e.g. i128), we need
2236 // to load all parts of it here (using the same address).
2237 MVT PartVT;
2238 unsigned NumParts;
2239 if (analyzeArgSplit(Ins, ArgLocs, I, PartVT, NumParts)) {
2240 for (unsigned PartIdx = 1; PartIdx < NumParts; ++PartIdx) {
2241 ++I;
2242 CCValAssign &PartVA = ArgLocs[I];
2243 unsigned PartOffset = Ins[I].PartOffset;
2244 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
2245 DAG.getIntPtrConstant(PartOffset, DL));
2246 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
2248 assert(PartOffset && "Offset should be non-zero.");
2249 }
2250 }
2251 } else if (Subtarget.isTargetXPLINK64() &&
2252 (VA.getLocInfo() == CCValAssign::SExt ||
2253 VA.getLocInfo() == CCValAssign::ZExt) &&
2254 Ins[I].ArgVT.isSimple()) {
2255 // Some prior z/OS compilers do not always perform the extension of
2256 // short integer arguments or pointers. To accommodate those, do not
2257 // rely on that extension by avoiding any AssertSext/AssertZext nodes by
2258 // directly truncating ArgValue to the original argument type.
2259 MVT OrigVT = Ins[I].ArgVT.getSimpleVT();
2260 InVals.push_back(DAG.getNode(ISD::TRUNCATE, DL, OrigVT, ArgValue));
2261 } else
2262 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
2263 }
2264
2265 if (IsVarArg && Subtarget.isTargetXPLINK64()) {
2266 // Save the number of non-varargs registers for later use by va_start, etc.
2267 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
2268 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
2269
2270 auto *Regs = static_cast<SystemZXPLINK64Registers *>(
2271 Subtarget.getSpecialRegisters());
2272
2273 // Likewise the address (in the form of a frame index) of where the
2274 // first stack vararg would be. The 1-byte size here is arbitrary.
2275 // FIXME: Pre-include call frame size in the offset, should not
2276 // need to manually add it here.
2277 int64_t VarArgOffset = CCInfo.getStackSize() + Regs->getCallFrameSize();
2278 int FI = MFI.CreateFixedObject(1, VarArgOffset, true);
2279 FuncInfo->setVarArgsFrameIndex(FI);
2280 }
2281
2282 if (IsVarArg && Subtarget.isTargetELF()) {
2283 // Save the number of non-varargs registers for later use by va_start, etc.
2284 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
2285 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
2286
2287 // Likewise the address (in the form of a frame index) of where the
2288 // first stack vararg would be. The 1-byte size here is arbitrary.
2289 int64_t VarArgsOffset = CCInfo.getStackSize();
2290 FuncInfo->setVarArgsFrameIndex(
2291 MFI.CreateFixedObject(1, VarArgsOffset, true));
2292
2293 // ...and a similar frame index for the caller-allocated save area
2294 // that will be used to store the incoming registers.
2295 int64_t RegSaveOffset =
2296 -SystemZMC::ELFCallFrameSize + TFL->getRegSpillOffset(MF, SystemZ::R2D) - 16;
2297 unsigned RegSaveIndex = MFI.CreateFixedObject(1, RegSaveOffset, true);
2298 FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
2299
2300 // Store the FPR varargs in the reserved frame slots. (We store the
2301 // GPRs as part of the prologue.)
2302 if (NumFixedFPRs < SystemZ::ELFNumArgFPRs && !useSoftFloat()) {
2304 for (unsigned I = NumFixedFPRs; I < SystemZ::ELFNumArgFPRs; ++I) {
2305 unsigned Offset = TFL->getRegSpillOffset(MF, SystemZ::ELFArgFPRs[I]);
2306 int FI =
2308 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2310 &SystemZ::FP64BitRegClass);
2311 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
2312 MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
2314 }
2315 // Join the stores, which are independent of one another.
2316 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2317 ArrayRef(&MemOps[NumFixedFPRs],
2318 SystemZ::ELFNumArgFPRs - NumFixedFPRs));
2319 }
2320 }
2321
2322 return Chain;
2323}
2324
2325static bool canUseSiblingCall(const CCState &ArgCCInfo,
2328 // Punt if there are any indirect or stack arguments, or if the call
2329 // needs the callee-saved argument register R6, or if the call uses
2330 // the callee-saved register arguments SwiftSelf and SwiftError.
2331 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
2332 CCValAssign &VA = ArgLocs[I];
2334 return false;
2335 if (!VA.isRegLoc())
2336 return false;
2337 Register Reg = VA.getLocReg();
2338 if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
2339 return false;
2340 if (Outs[I].Flags.isSwiftSelf() || Outs[I].Flags.isSwiftError())
2341 return false;
2342 }
2343 return true;
2344}
2345
2347 unsigned Offset, bool LoadAdr = false) {
2351
2352 SDValue Reg = DAG.getRegister(ADAvReg, PtrVT);
2353 SDValue Ofs = DAG.getTargetConstant(Offset, DL, PtrVT);
2354
2355 SDValue Result = DAG.getNode(SystemZISD::ADA_ENTRY, DL, PtrVT, Val, Reg, Ofs);
2356 if (!LoadAdr)
2357 Result = DAG.getLoad(
2358 PtrVT, DL, DAG.getEntryNode(), Result, MachinePointerInfo(), Align(8),
2360
2361 return Result;
2362}
2363
2364// ADA access using Global value
2365// Note: for functions, address of descriptor is returned
2367 EVT PtrVT) {
2368 unsigned ADAtype;
2369 bool LoadAddr = false;
2370 const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV);
2371 bool IsFunction =
2372 (isa<Function>(GV)) || (GA && isa<Function>(GA->getAliaseeObject()));
2373 bool IsInternal = (GV->hasInternalLinkage() || GV->hasPrivateLinkage());
2374
2375 if (IsFunction) {
2376 if (IsInternal) {
2378 LoadAddr = true;
2379 } else
2381 } else {
2383 }
2384 SDValue Val = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ADAtype);
2385
2386 return getADAEntry(DAG, Val, DL, 0, LoadAddr);
2387}
2388
2389static bool getzOSCalleeAndADA(SelectionDAG &DAG, SDValue &Callee, SDValue &ADA,
2390 SDLoc &DL, SDValue &Chain) {
2391 unsigned ADADelta = 0; // ADA offset in desc.
2392 unsigned EPADelta = 8; // EPA offset in desc.
2395
2396 // XPLink calling convention.
2397 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2398 bool IsInternal = (G->getGlobal()->hasInternalLinkage() ||
2399 G->getGlobal()->hasPrivateLinkage());
2400 if (IsInternal) {
2402 ADA = DAG.getCopyFromReg(Chain, DL, ADAvReg, PtrVT);
2403 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
2404 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2405 return true;
2406 } else {
2408 G->getGlobal(), DL, PtrVT, 0, SystemZII::MO_ADA_DIRECT_FUNC_DESC);
2409 ADA = getADAEntry(DAG, GA, DL, ADADelta);
2410 Callee = getADAEntry(DAG, GA, DL, EPADelta);
2411 }
2412 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2414 E->getSymbol(), PtrVT, SystemZII::MO_ADA_DIRECT_FUNC_DESC);
2415 ADA = getADAEntry(DAG, ES, DL, ADADelta);
2416 Callee = getADAEntry(DAG, ES, DL, EPADelta);
2417 } else {
2418 // Function pointer case
2419 ADA = DAG.getNode(ISD::ADD, DL, PtrVT, Callee,
2420 DAG.getConstant(ADADelta, DL, PtrVT));
2421 ADA = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), ADA,
2423 Callee = DAG.getNode(ISD::ADD, DL, PtrVT, Callee,
2424 DAG.getConstant(EPADelta, DL, PtrVT));
2425 Callee = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Callee,
2427 }
2428 return false;
2429}
2430
2431SDValue
2433 SmallVectorImpl<SDValue> &InVals) const {
2434 SelectionDAG &DAG = CLI.DAG;
2435 SDLoc &DL = CLI.DL;
2437 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2439 SDValue Chain = CLI.Chain;
2440 SDValue Callee = CLI.Callee;
2441 bool &IsTailCall = CLI.IsTailCall;
2442 CallingConv::ID CallConv = CLI.CallConv;
2443 bool IsVarArg = CLI.IsVarArg;
2445 EVT PtrVT = getPointerTy(MF.getDataLayout());
2446 LLVMContext &Ctx = *DAG.getContext();
2447 SystemZCallingConventionRegisters *Regs = Subtarget.getSpecialRegisters();
2448
2449 // FIXME: z/OS support to be added in later.
2450 if (Subtarget.isTargetXPLINK64()) {
2451 if (CLI.CB && CLI.CB->isMustTailCall())
2452 report_fatal_error("musttail call is not supported on XPLINK64");
2453 IsTailCall = false;
2454 }
2455
2456 // Integer args <=32 bits should have an extension attribute.
2457 verifyNarrowIntegerArgs_Call(CLI, Outs, &MF.getFunction(), Callee);
2458
2459 // Analyze the operands of the call, assigning locations to each operand.
2461 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, Ctx);
2462 ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
2463
2464 // We don't support GuaranteedTailCallOpt, only automatically-detected
2465 // sibling calls.
2466 if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs, Outs))
2467 IsTailCall = false;
2468
2469 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
2470 report_fatal_error("failed to perform tail call elimination on a call "
2471 "site marked musttail");
2472
2473 // Get a count of how many bytes are to be pushed on the stack.
2474 unsigned NumBytes = ArgCCInfo.getStackSize();
2475
2476 // Mark the start of the call.
2477 if (!IsTailCall)
2478 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
2479
2480 // Copy argument values to their designated locations.
2482 SmallVector<SDValue, 8> MemOpChains;
2483 SDValue StackPtr;
2484 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
2485 CCValAssign &VA = ArgLocs[I];
2486 SDValue ArgValue = OutVals[I];
2487
2488 if (VA.getLocInfo() == CCValAssign::Indirect) {
2489 // Store the argument in a stack slot and pass its address.
2490 EVT SlotVT;
2491 MVT PartVT;
2492 unsigned NumParts = 1;
2493 if (analyzeArgSplit(Outs, ArgLocs, I, PartVT, NumParts))
2494 SlotVT = EVT::getIntegerVT(Ctx, PartVT.getSizeInBits() * NumParts);
2495 else
2496 SlotVT = Outs[I].VT;
2497 SDValue SpillSlot = DAG.CreateStackTemporary(SlotVT);
2498 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2499
2500 MachinePointerInfo StackPtrInfo =
2502 MemOpChains.push_back(
2503 DAG.getStore(Chain, DL, ArgValue, SpillSlot, StackPtrInfo));
2504 // If the original argument was split (e.g. i128), we need
2505 // to store all parts of it here (and pass just one address).
2506 assert(Outs[I].PartOffset == 0);
2507 for (unsigned PartIdx = 1; PartIdx < NumParts; ++PartIdx) {
2508 ++I;
2509 SDValue PartValue = OutVals[I];
2510 unsigned PartOffset = Outs[I].PartOffset;
2511 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
2512 DAG.getIntPtrConstant(PartOffset, DL));
2513 MemOpChains.push_back(
2514 DAG.getStore(Chain, DL, PartValue, Address,
2515 StackPtrInfo.getWithOffset(PartOffset)));
2516 assert(PartOffset && "Offset should be non-zero.");
2517 assert((PartOffset + PartValue.getValueType().getStoreSize() <=
2518 SlotVT.getStoreSize()) && "Not enough space for argument part!");
2519 }
2520 ArgValue = SpillSlot;
2521 } else
2522 ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
2523
2524 if (VA.isRegLoc()) {
2525 // In XPLINK64, for the 128-bit vararg case, ArgValue is bitcasted to a
2526 // MVT::i128 type. We decompose the 128-bit type to a pair of its high
2527 // and low values.
2528 if (VA.getLocVT() == MVT::i128)
2529 ArgValue = lowerI128ToGR128(DAG, ArgValue);
2530 // Queue up the argument copies and emit them at the end.
2531 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
2532 } else {
2533 assert(VA.isMemLoc() && "Argument not register or memory");
2534
2535 // Work out the address of the stack slot. Unpromoted ints and
2536 // floats are passed as right-justified 8-byte values.
2537 if (!StackPtr.getNode())
2538 StackPtr = DAG.getCopyFromReg(Chain, DL,
2539 Regs->getStackPointerRegister(), PtrVT);
2540 unsigned Offset = Regs->getStackPointerBias() + Regs->getCallFrameSize() +
2541 VA.getLocMemOffset();
2542 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
2543 Offset += 4;
2544 else if (VA.getLocVT() == MVT::f16)
2545 Offset += 6;
2546 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
2548
2549 // Emit the store.
2550 MemOpChains.push_back(
2551 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
2552
2553 // Although long doubles or vectors are passed through the stack when
2554 // they are vararg (non-fixed arguments), if a long double or vector
2555 // occupies the third and fourth slot of the argument list GPR3 should
2556 // still shadow the third slot of the argument list.
2557 if (Subtarget.isTargetXPLINK64() && VA.needsCustom()) {
2558 SDValue ShadowArgValue =
2559 DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, ArgValue,
2560 DAG.getIntPtrConstant(1, DL));
2561 RegsToPass.push_back(std::make_pair(SystemZ::R3D, ShadowArgValue));
2562 }
2563 }
2564 }
2565
2566 // Join the stores, which are independent of one another.
2567 if (!MemOpChains.empty())
2568 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2569
2570 // Accept direct calls by converting symbolic call addresses to the
2571 // associated Target* opcodes. Force %r1 to be used for indirect
2572 // tail calls.
2573 SDValue Glue;
2574
2575 if (Subtarget.isTargetXPLINK64()) {
2576 SDValue ADA;
2577 bool IsBRASL = getzOSCalleeAndADA(DAG, Callee, ADA, DL, Chain);
2578 if (!IsBRASL) {
2579 unsigned CalleeReg = static_cast<SystemZXPLINK64Registers *>(Regs)
2580 ->getAddressOfCalleeRegister();
2581 Chain = DAG.getCopyToReg(Chain, DL, CalleeReg, Callee, Glue);
2582 Glue = Chain.getValue(1);
2583 Callee = DAG.getRegister(CalleeReg, Callee.getValueType());
2584 }
2585 RegsToPass.push_back(std::make_pair(
2586 static_cast<SystemZXPLINK64Registers *>(Regs)->getADARegister(), ADA));
2587 } else {
2588 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2589 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
2590 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2591 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2592 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
2593 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2594 } else if (IsTailCall) {
2595 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
2596 Glue = Chain.getValue(1);
2597 Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
2598 }
2599 }
2600
2601 // Build a sequence of copy-to-reg nodes, chained and glued together.
2602 for (const auto &[Reg, N] : RegsToPass) {
2603 Chain = DAG.getCopyToReg(Chain, DL, Reg, N, Glue);
2604 Glue = Chain.getValue(1);
2605 }
2606
2607 // The first call operand is the chain and the second is the target address.
2609 Ops.push_back(Chain);
2610 Ops.push_back(Callee);
2611
2612 // Add argument registers to the end of the list so that they are
2613 // known live into the call.
2614 for (const auto &[Reg, N] : RegsToPass)
2615 Ops.push_back(DAG.getRegister(Reg, N.getValueType()));
2616
2617 // Add a register mask operand representing the call-preserved registers.
2618 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2619 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2620 assert(Mask && "Missing call preserved mask for calling convention");
2621 Ops.push_back(DAG.getRegisterMask(Mask));
2622
2623 // Glue the call to the argument copies, if any.
2624 if (Glue.getNode())
2625 Ops.push_back(Glue);
2626
2627 // Emit the call.
2628 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2629 if (IsTailCall) {
2630 SDValue Ret = DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
2631 DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge);
2632 return Ret;
2633 }
2634 Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
2635 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2636 Glue = Chain.getValue(1);
2637
2638 // Mark the end of the call, which is glued to the call itself.
2639 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, Glue, DL);
2640 Glue = Chain.getValue(1);
2641
2642 // Assign locations to each value returned by this call.
2644 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, Ctx);
2645 RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
2646
2647 // Copy all of the result registers out of their specified physreg.
2648 for (CCValAssign &VA : RetLocs) {
2649 // Copy the value out, gluing the copy to the end of the call sequence.
2650 SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
2651 VA.getLocVT(), Glue);
2652 Chain = RetValue.getValue(1);
2653 Glue = RetValue.getValue(2);
2654
2655 // Convert the value of the return register into the value that's
2656 // being returned.
2657 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
2658 }
2659
2660 return Chain;
2661}
2662
2663// Generate a call taking the given operands as arguments and returning a
2664// result of type RetVT.
2666 SDValue Chain, SelectionDAG &DAG, const char *CalleeName, EVT RetVT,
2667 ArrayRef<SDValue> Ops, CallingConv::ID CallConv, bool IsSigned, SDLoc DL,
2668 bool DoesNotReturn, bool IsReturnValueUsed) const {
2670 Args.reserve(Ops.size());
2671
2672 for (SDValue Op : Ops) {
2674 Op, Op.getValueType().getTypeForEVT(*DAG.getContext()));
2675 Entry.IsSExt = shouldSignExtendTypeInLibCall(Entry.Ty, IsSigned);
2676 Entry.IsZExt = !Entry.IsSExt;
2677 Args.push_back(Entry);
2678 }
2679
2680 SDValue Callee =
2681 DAG.getExternalSymbol(CalleeName, getPointerTy(DAG.getDataLayout()));
2682
2683 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2685 bool SignExtend = shouldSignExtendTypeInLibCall(RetTy, IsSigned);
2686 CLI.setDebugLoc(DL)
2687 .setChain(Chain)
2688 .setCallee(CallConv, RetTy, Callee, std::move(Args))
2689 .setNoReturn(DoesNotReturn)
2690 .setDiscardResult(!IsReturnValueUsed)
2691 .setSExtResult(SignExtend)
2692 .setZExtResult(!SignExtend);
2693 return LowerCallTo(CLI);
2694}
2695
2697 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
2698 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context,
2699 const Type *RetTy) const {
2700 // Special case that we cannot easily detect in RetCC_SystemZ since
2701 // i128 may not be a legal type.
2702 for (auto &Out : Outs)
2703 if (Out.ArgVT.isScalarInteger() && Out.ArgVT.getSizeInBits() > 64)
2704 return false;
2705
2707 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, Context);
2708 return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ);
2709}
2710
2711SDValue
2713 bool IsVarArg,
2715 const SmallVectorImpl<SDValue> &OutVals,
2716 const SDLoc &DL, SelectionDAG &DAG) const {
2718
2719 // Integer args <=32 bits should have an extension attribute.
2720 verifyNarrowIntegerArgs_Ret(CallConv, Outs, &MF.getFunction());
2721
2722 // Assign locations to each returned value.
2724 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
2725 RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
2726
2727 // Quick exit for void returns
2728 if (RetLocs.empty())
2729 return DAG.getNode(SystemZISD::RET_GLUE, DL, MVT::Other, Chain);
2730
2731 if (CallConv == CallingConv::GHC)
2732 report_fatal_error("GHC functions return void only");
2733
2734 // Copy the result values into the output registers.
2735 SDValue Glue;
2737 RetOps.push_back(Chain);
2738 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
2739 CCValAssign &VA = RetLocs[I];
2740 SDValue RetValue = OutVals[I];
2741
2742 // Make the return register live on exit.
2743 assert(VA.isRegLoc() && "Can only return in registers!");
2744
2745 // Promote the value as required.
2746 RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
2747
2748 // Chain and glue the copies together.
2749 Register Reg = VA.getLocReg();
2750 Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
2751 Glue = Chain.getValue(1);
2752 RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
2753 }
2754
2755 // Update chain and glue.
2756 RetOps[0] = Chain;
2757 if (Glue.getNode())
2758 RetOps.push_back(Glue);
2759
2760 return DAG.getNode(SystemZISD::RET_GLUE, DL, MVT::Other, RetOps);
2761}
2762
2763// Return true if Op is an intrinsic node with chain that returns the CC value
2764// as its only (other) argument. Provide the associated SystemZISD opcode and
2765// the mask of valid CC values if so.
2766static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
2767 unsigned &CCValid) {
2768 unsigned Id = Op.getConstantOperandVal(1);
2769 switch (Id) {
2770 case Intrinsic::s390_tbegin:
2771 Opcode = SystemZISD::TBEGIN;
2772 CCValid = SystemZ::CCMASK_TBEGIN;
2773 return true;
2774
2775 case Intrinsic::s390_tbegin_nofloat:
2776 Opcode = SystemZISD::TBEGIN_NOFLOAT;
2777 CCValid = SystemZ::CCMASK_TBEGIN;
2778 return true;
2779
2780 case Intrinsic::s390_tend:
2781 Opcode = SystemZISD::TEND;
2782 CCValid = SystemZ::CCMASK_TEND;
2783 return true;
2784
2785 default:
2786 return false;
2787 }
2788}
2789
2790// Return true if Op is an intrinsic node without chain that returns the
2791// CC value as its final argument. Provide the associated SystemZISD
2792// opcode and the mask of valid CC values if so.
2793static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) {
2794 unsigned Id = Op.getConstantOperandVal(0);
2795 switch (Id) {
2796 case Intrinsic::s390_vpkshs:
2797 case Intrinsic::s390_vpksfs:
2798 case Intrinsic::s390_vpksgs:
2799 Opcode = SystemZISD::PACKS_CC;
2800 CCValid = SystemZ::CCMASK_VCMP;
2801 return true;
2802
2803 case Intrinsic::s390_vpklshs:
2804 case Intrinsic::s390_vpklsfs:
2805 case Intrinsic::s390_vpklsgs:
2806 Opcode = SystemZISD::PACKLS_CC;
2807 CCValid = SystemZ::CCMASK_VCMP;
2808 return true;
2809
2810 case Intrinsic::s390_vceqbs:
2811 case Intrinsic::s390_vceqhs:
2812 case Intrinsic::s390_vceqfs:
2813 case Intrinsic::s390_vceqgs:
2814 case Intrinsic::s390_vceqqs:
2815 Opcode = SystemZISD::VICMPES;
2816 CCValid = SystemZ::CCMASK_VCMP;
2817 return true;
2818
2819 case Intrinsic::s390_vchbs:
2820 case Intrinsic::s390_vchhs:
2821 case Intrinsic::s390_vchfs:
2822 case Intrinsic::s390_vchgs:
2823 case Intrinsic::s390_vchqs:
2824 Opcode = SystemZISD::VICMPHS;
2825 CCValid = SystemZ::CCMASK_VCMP;
2826 return true;
2827
2828 case Intrinsic::s390_vchlbs:
2829 case Intrinsic::s390_vchlhs:
2830 case Intrinsic::s390_vchlfs:
2831 case Intrinsic::s390_vchlgs:
2832 case Intrinsic::s390_vchlqs:
2833 Opcode = SystemZISD::VICMPHLS;
2834 CCValid = SystemZ::CCMASK_VCMP;
2835 return true;
2836
2837 case Intrinsic::s390_vtm:
2838 Opcode = SystemZISD::VTM;
2839 CCValid = SystemZ::CCMASK_VCMP;
2840 return true;
2841
2842 case Intrinsic::s390_vfaebs:
2843 case Intrinsic::s390_vfaehs:
2844 case Intrinsic::s390_vfaefs:
2845 Opcode = SystemZISD::VFAE_CC;
2846 CCValid = SystemZ::CCMASK_ANY;
2847 return true;
2848
2849 case Intrinsic::s390_vfaezbs:
2850 case Intrinsic::s390_vfaezhs:
2851 case Intrinsic::s390_vfaezfs:
2852 Opcode = SystemZISD::VFAEZ_CC;
2853 CCValid = SystemZ::CCMASK_ANY;
2854 return true;
2855
2856 case Intrinsic::s390_vfeebs:
2857 case Intrinsic::s390_vfeehs:
2858 case Intrinsic::s390_vfeefs:
2859 Opcode = SystemZISD::VFEE_CC;
2860 CCValid = SystemZ::CCMASK_ANY;
2861 return true;
2862
2863 case Intrinsic::s390_vfeezbs:
2864 case Intrinsic::s390_vfeezhs:
2865 case Intrinsic::s390_vfeezfs:
2866 Opcode = SystemZISD::VFEEZ_CC;
2867 CCValid = SystemZ::CCMASK_ANY;
2868 return true;
2869
2870 case Intrinsic::s390_vfenebs:
2871 case Intrinsic::s390_vfenehs:
2872 case Intrinsic::s390_vfenefs:
2873 Opcode = SystemZISD::VFENE_CC;
2874 CCValid = SystemZ::CCMASK_ANY;
2875 return true;
2876
2877 case Intrinsic::s390_vfenezbs:
2878 case Intrinsic::s390_vfenezhs:
2879 case Intrinsic::s390_vfenezfs:
2880 Opcode = SystemZISD::VFENEZ_CC;
2881 CCValid = SystemZ::CCMASK_ANY;
2882 return true;
2883
2884 case Intrinsic::s390_vistrbs:
2885 case Intrinsic::s390_vistrhs:
2886 case Intrinsic::s390_vistrfs:
2887 Opcode = SystemZISD::VISTR_CC;
2889 return true;
2890
2891 case Intrinsic::s390_vstrcbs:
2892 case Intrinsic::s390_vstrchs:
2893 case Intrinsic::s390_vstrcfs:
2894 Opcode = SystemZISD::VSTRC_CC;
2895 CCValid = SystemZ::CCMASK_ANY;
2896 return true;
2897
2898 case Intrinsic::s390_vstrczbs:
2899 case Intrinsic::s390_vstrczhs:
2900 case Intrinsic::s390_vstrczfs:
2901 Opcode = SystemZISD::VSTRCZ_CC;
2902 CCValid = SystemZ::CCMASK_ANY;
2903 return true;
2904
2905 case Intrinsic::s390_vstrsb:
2906 case Intrinsic::s390_vstrsh:
2907 case Intrinsic::s390_vstrsf:
2908 Opcode = SystemZISD::VSTRS_CC;
2909 CCValid = SystemZ::CCMASK_ANY;
2910 return true;
2911
2912 case Intrinsic::s390_vstrszb:
2913 case Intrinsic::s390_vstrszh:
2914 case Intrinsic::s390_vstrszf:
2915 Opcode = SystemZISD::VSTRSZ_CC;
2916 CCValid = SystemZ::CCMASK_ANY;
2917 return true;
2918
2919 case Intrinsic::s390_vfcedbs:
2920 case Intrinsic::s390_vfcesbs:
2921 Opcode = SystemZISD::VFCMPES;
2922 CCValid = SystemZ::CCMASK_VCMP;
2923 return true;
2924
2925 case Intrinsic::s390_vfchdbs:
2926 case Intrinsic::s390_vfchsbs:
2927 Opcode = SystemZISD::VFCMPHS;
2928 CCValid = SystemZ::CCMASK_VCMP;
2929 return true;
2930
2931 case Intrinsic::s390_vfchedbs:
2932 case Intrinsic::s390_vfchesbs:
2933 Opcode = SystemZISD::VFCMPHES;
2934 CCValid = SystemZ::CCMASK_VCMP;
2935 return true;
2936
2937 case Intrinsic::s390_vftcidb:
2938 case Intrinsic::s390_vftcisb:
2939 Opcode = SystemZISD::VFTCI;
2940 CCValid = SystemZ::CCMASK_VCMP;
2941 return true;
2942
2943 case Intrinsic::s390_tdc:
2944 Opcode = SystemZISD::TDC;
2945 CCValid = SystemZ::CCMASK_TDC;
2946 return true;
2947
2948 default:
2949 return false;
2950 }
2951}
2952
2953// Emit an intrinsic with chain and an explicit CC register result.
2955 unsigned Opcode) {
2956 // Copy all operands except the intrinsic ID.
2957 unsigned NumOps = Op.getNumOperands();
2959 Ops.reserve(NumOps - 1);
2960 Ops.push_back(Op.getOperand(0));
2961 for (unsigned I = 2; I < NumOps; ++I)
2962 Ops.push_back(Op.getOperand(I));
2963
2964 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
2965 SDVTList RawVTs = DAG.getVTList(MVT::i32, MVT::Other);
2966 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
2967 SDValue OldChain = SDValue(Op.getNode(), 1);
2968 SDValue NewChain = SDValue(Intr.getNode(), 1);
2969 DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
2970 return Intr.getNode();
2971}
2972
2973// Emit an intrinsic with an explicit CC register result.
2975 unsigned Opcode) {
2976 // Copy all operands except the intrinsic ID.
2977 SDLoc DL(Op);
2978 unsigned NumOps = Op.getNumOperands();
2980 Ops.reserve(NumOps - 1);
2981 for (unsigned I = 1; I < NumOps; ++I) {
2982 SDValue CurrOper = Op.getOperand(I);
2983 if (CurrOper.getValueType() == MVT::f16) {
2984 assert((Op.getConstantOperandVal(0) == Intrinsic::s390_tdc && I == 1) &&
2985 "Unhandled intrinsic with f16 operand.");
2986 CurrOper = DAG.getFPExtendOrRound(CurrOper, DL, MVT::f32);
2987 }
2988 Ops.push_back(CurrOper);
2989 }
2990
2991 SDValue Intr = DAG.getNode(Opcode, DL, Op->getVTList(), Ops);
2992 return Intr.getNode();
2993}
2994
2995// CC is a comparison that will be implemented using an integer or
2996// floating-point comparison. Return the condition code mask for
2997// a branch on true. In the integer case, CCMASK_CMP_UO is set for
2998// unsigned comparisons and clear for signed ones. In the floating-point
2999// case, CCMASK_CMP_UO has its normal mask meaning (unordered).
3001#define CONV(X) \
3002 case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
3003 case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
3004 case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
3005
3006 switch (CC) {
3007 default:
3008 llvm_unreachable("Invalid integer condition!");
3009
3010 CONV(EQ);
3011 CONV(NE);
3012 CONV(GT);
3013 CONV(GE);
3014 CONV(LT);
3015 CONV(LE);
3016
3017 case ISD::SETO: return SystemZ::CCMASK_CMP_O;
3019 }
3020#undef CONV
3021}
3022
3023// If C can be converted to a comparison against zero, adjust the operands
3024// as necessary.
3025static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
3026 if (C.ICmpType == SystemZICMP::UnsignedOnly)
3027 return;
3028
3029 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
3030 if (!ConstOp1 || ConstOp1->getValueSizeInBits(0) > 64)
3031 return;
3032
3033 int64_t Value = ConstOp1->getSExtValue();
3034 if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
3035 (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
3036 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
3037 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
3038 C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
3039 C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
3040 }
3041}
3042
3043// If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
3044// adjust the operands as necessary.
3045static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL,
3046 Comparison &C) {
3047 // For us to make any changes, it must a comparison between a single-use
3048 // load and a constant.
3049 if (!C.Op0.hasOneUse() ||
3050 C.Op0.getOpcode() != ISD::LOAD ||
3051 C.Op1.getOpcode() != ISD::Constant)
3052 return;
3053
3054 // We must have an 8- or 16-bit load.
3055 auto *Load = cast<LoadSDNode>(C.Op0);
3056 unsigned NumBits = Load->getMemoryVT().getSizeInBits();
3057 if ((NumBits != 8 && NumBits != 16) ||
3058 NumBits != Load->getMemoryVT().getStoreSizeInBits())
3059 return;
3060
3061 // The load must be an extending one and the constant must be within the
3062 // range of the unextended value.
3063 auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
3064 if (!ConstOp1 || ConstOp1->getValueSizeInBits(0) > 64)
3065 return;
3066 uint64_t Value = ConstOp1->getZExtValue();
3067 uint64_t Mask = (1 << NumBits) - 1;
3068 if (Load->getExtensionType() == ISD::SEXTLOAD) {
3069 // Make sure that ConstOp1 is in range of C.Op0.
3070 int64_t SignedValue = ConstOp1->getSExtValue();
3071 if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
3072 return;
3073 if (C.ICmpType != SystemZICMP::SignedOnly) {
3074 // Unsigned comparison between two sign-extended values is equivalent
3075 // to unsigned comparison between two zero-extended values.
3076 Value &= Mask;
3077 } else if (NumBits == 8) {
3078 // Try to treat the comparison as unsigned, so that we can use CLI.
3079 // Adjust CCMask and Value as necessary.
3080 if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
3081 // Test whether the high bit of the byte is set.
3082 Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
3083 else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
3084 // Test whether the high bit of the byte is clear.
3085 Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
3086 else
3087 // No instruction exists for this combination.
3088 return;
3089 C.ICmpType = SystemZICMP::UnsignedOnly;
3090 }
3091 } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
3092 if (Value > Mask)
3093 return;
3094 // If the constant is in range, we can use any comparison.
3095 C.ICmpType = SystemZICMP::Any;
3096 } else
3097 return;
3098
3099 // Make sure that the first operand is an i32 of the right extension type.
3100 ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
3103 if (C.Op0.getValueType() != MVT::i32 ||
3104 Load->getExtensionType() != ExtType) {
3105 C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32, Load->getChain(),
3106 Load->getBasePtr(), Load->getPointerInfo(),
3107 Load->getMemoryVT(), Load->getAlign(),
3108 Load->getMemOperand()->getFlags());
3109 // Update the chain uses.
3110 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), C.Op0.getValue(1));
3111 }
3112
3113 // Make sure that the second operand is an i32 with the right value.
3114 if (C.Op1.getValueType() != MVT::i32 ||
3115 Value != ConstOp1->getZExtValue())
3116 C.Op1 = DAG.getConstant((uint32_t)Value, DL, MVT::i32);
3117}
3118
3119// Return true if Op is either an unextended load, or a load suitable
3120// for integer register-memory comparisons of type ICmpType.
3121static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
3122 auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
3123 if (Load) {
3124 // There are no instructions to compare a register with a memory byte.
3125 if (Load->getMemoryVT() == MVT::i8)
3126 return false;
3127 // Otherwise decide on extension type.
3128 switch (Load->getExtensionType()) {
3129 case ISD::NON_EXTLOAD:
3130 return true;
3131 case ISD::SEXTLOAD:
3132 return ICmpType != SystemZICMP::UnsignedOnly;
3133 case ISD::ZEXTLOAD:
3134 return ICmpType != SystemZICMP::SignedOnly;
3135 default:
3136 break;
3137 }
3138 }
3139 return false;
3140}
3141
3142// Return true if it is better to swap the operands of C.
3143static bool shouldSwapCmpOperands(const Comparison &C) {
3144 // If one side of the compare is a load of the stackguard reference value,
3145 // then that load should be Op1.
3146 if (C.Op0.isMachineOpcode() &&
3147 (C.Op0.getMachineOpcode() == SystemZ::LOAD_STACK_GUARD))
3148 return true;
3149
3150 // Leave i128 and f128 comparisons alone, since they have no memory forms.
3151 if (C.Op0.getValueType() == MVT::i128)
3152 return false;
3153 if (C.Op0.getValueType() == MVT::f128)
3154 return false;
3155
3156 // Always keep a floating-point constant second, since comparisons with
3157 // zero can use LOAD TEST and comparisons with other constants make a
3158 // natural memory operand.
3159 if (isa<ConstantFPSDNode>(C.Op1))
3160 return false;
3161
3162 // Never swap comparisons with zero since there are many ways to optimize
3163 // those later.
3164 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
3165 if (ConstOp1 && ConstOp1->getZExtValue() == 0)
3166 return false;
3167
3168 // Also keep natural memory operands second if the loaded value is
3169 // only used here. Several comparisons have memory forms.
3170 if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
3171 return false;
3172
3173 // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
3174 // In that case we generally prefer the memory to be second.
3175 if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
3176 // The only exceptions are when the second operand is a constant and
3177 // we can use things like CHHSI.
3178 if (!ConstOp1)
3179 return true;
3180 // The unsigned memory-immediate instructions can handle 16-bit
3181 // unsigned integers.
3182 if (C.ICmpType != SystemZICMP::SignedOnly &&
3183 isUInt<16>(ConstOp1->getZExtValue()))
3184 return false;
3185 // The signed memory-immediate instructions can handle 16-bit
3186 // signed integers.
3187 if (C.ICmpType != SystemZICMP::UnsignedOnly &&
3188 isInt<16>(ConstOp1->getSExtValue()))
3189 return false;
3190 return true;
3191 }
3192
3193 // Try to promote the use of CGFR and CLGFR.
3194 unsigned Opcode0 = C.Op0.getOpcode();
3195 if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
3196 return true;
3197 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
3198 return true;
3199 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::AND &&
3200 C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
3201 C.Op0.getConstantOperandVal(1) == 0xffffffff)
3202 return true;
3203
3204 return false;
3205}
3206
3207// Check whether C tests for equality between X and Y and whether X - Y
3208// or Y - X is also computed. In that case it's better to compare the
3209// result of the subtraction against zero.
3211 Comparison &C) {
3212 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3213 C.CCMask == SystemZ::CCMASK_CMP_NE) {
3214 for (SDNode *N : C.Op0->users()) {
3215 if (N->getOpcode() == ISD::SUB &&
3216 ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
3217 (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
3218 // Disable the nsw and nuw flags: the backend needs to handle
3219 // overflow as well during comparison elimination.
3220 N->dropFlags(SDNodeFlags::NoWrap);
3221 C.Op0 = SDValue(N, 0);
3222 C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
3223 return;
3224 }
3225 }
3226 }
3227}
3228
3229// Check whether C compares a floating-point value with zero and if that
3230// floating-point value is also negated. In this case we can use the
3231// negation to set CC, so avoiding separate LOAD AND TEST and
3232// LOAD (NEGATIVE/COMPLEMENT) instructions.
3233static void adjustForFNeg(Comparison &C) {
3234 // This optimization is invalid for strict comparisons, since FNEG
3235 // does not raise any exceptions.
3236 if (C.Chain)
3237 return;
3238 auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
3239 if (C1 && C1->isZero()) {
3240 for (SDNode *N : C.Op0->users()) {
3241 if (N->getOpcode() == ISD::FNEG) {
3242 C.Op0 = SDValue(N, 0);
3243 C.CCMask = SystemZ::reverseCCMask(C.CCMask);
3244 return;
3245 }
3246 }
3247 }
3248}
3249
3250// Check whether C compares (shl X, 32) with 0 and whether X is
3251// also sign-extended. In that case it is better to test the result
3252// of the sign extension using LTGFR.
3253//
3254// This case is important because InstCombine transforms a comparison
3255// with (sext (trunc X)) into a comparison with (shl X, 32).
3256static void adjustForLTGFR(Comparison &C) {
3257 // Check for a comparison between (shl X, 32) and 0.
3258 if (C.Op0.getOpcode() == ISD::SHL && C.Op0.getValueType() == MVT::i64 &&
3259 C.Op1.getOpcode() == ISD::Constant && C.Op1->getAsZExtVal() == 0) {
3260 auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
3261 if (C1 && C1->getZExtValue() == 32) {
3262 SDValue ShlOp0 = C.Op0.getOperand(0);
3263 // See whether X has any SIGN_EXTEND_INREG uses.
3264 for (SDNode *N : ShlOp0->users()) {
3265 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
3266 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
3267 C.Op0 = SDValue(N, 0);
3268 return;
3269 }
3270 }
3271 }
3272 }
3273}
3274
3275// If C compares the truncation of an extending load, try to compare
3276// the untruncated value instead. This exposes more opportunities to
3277// reuse CC.
3278static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL,
3279 Comparison &C) {
3280 if (C.Op0.getOpcode() == ISD::TRUNCATE &&
3281 C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
3282 C.Op1.getOpcode() == ISD::Constant &&
3283 cast<ConstantSDNode>(C.Op1)->getValueSizeInBits(0) <= 64 &&
3284 C.Op1->getAsZExtVal() == 0) {
3285 auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
3286 if (L->getMemoryVT().getStoreSizeInBits().getFixedValue() <=
3287 C.Op0.getValueSizeInBits().getFixedValue()) {
3288 unsigned Type = L->getExtensionType();
3289 if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
3290 (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
3291 C.Op0 = C.Op0.getOperand(0);
3292 C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
3293 }
3294 }
3295 }
3296}
3297
3298// Adjust if a given Compare is a check of the stack guard against a stack
3299// guard instance on the stack. Specifically, this checks if:
3300// - The operands are a load of the stack guard, and a load from a stack slot
3301// - The original opcode is ICMP
3302// - ICMPType is compatible with unsigned comparison.
3304 Comparison &C) {
3305
3306 // Opcode must be ICMP.
3307 if (C.Opcode != SystemZISD::ICMP)
3308 return;
3309 // ICmpType must be Unsigned or Any.
3310 if (C.ICmpType == SystemZICMP::SignedOnly)
3311 return;
3312 // Op0 must be FrameIndex Load.
3313 if (!(ISD::isNormalLoad(C.Op0.getNode()) &&
3314 dyn_cast<FrameIndexSDNode>(C.Op0.getOperand(1))))
3315 return;
3316 // Op1 must be LOAD_STACK_GUARD.
3317 if (!C.Op1.isMachineOpcode() ||
3318 C.Op1.getMachineOpcode() != SystemZ::LOAD_STACK_GUARD)
3319 return;
3320
3321 // At this point we are sure that this is a proper CMP_STACKGUARD
3322 // case, update the opcode to reflect this.
3323 C.Opcode = SystemZISD::CMP_STACKGUARD;
3324 C.Op1 = SDValue();
3325}
3326
3327// Return true if shift operation N has an in-range constant shift value.
3328// Store it in ShiftVal if so.
3329static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
3330 auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
3331 if (!Shift)
3332 return false;
3333
3334 uint64_t Amount = Shift->getZExtValue();
3335 if (Amount >= N.getValueSizeInBits())
3336 return false;
3337
3338 ShiftVal = Amount;
3339 return true;
3340}
3341
3342// Check whether an AND with Mask is suitable for a TEST UNDER MASK
3343// instruction and whether the CC value is descriptive enough to handle
3344// a comparison of type Opcode between the AND result and CmpVal.
3345// CCMask says which comparison result is being tested and BitSize is
3346// the number of bits in the operands. If TEST UNDER MASK can be used,
3347// return the corresponding CC mask, otherwise return 0.
3348static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
3349 uint64_t Mask, uint64_t CmpVal,
3350 unsigned ICmpType) {
3351 assert(Mask != 0 && "ANDs with zero should have been removed by now");
3352
3353 // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
3354 if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
3355 !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
3356 return 0;
3357
3358 // Work out the masks for the lowest and highest bits.
3360 uint64_t Low = uint64_t(1) << llvm::countr_zero(Mask);
3361
3362 // Signed ordered comparisons are effectively unsigned if the sign
3363 // bit is dropped.
3364 bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
3365
3366 // Check for equality comparisons with 0, or the equivalent.
3367 if (CmpVal == 0) {
3368 if (CCMask == SystemZ::CCMASK_CMP_EQ)
3370 if (CCMask == SystemZ::CCMASK_CMP_NE)
3372 }
3373 if (EffectivelyUnsigned && CmpVal > 0 && CmpVal <= Low) {
3374 if (CCMask == SystemZ::CCMASK_CMP_LT)
3376 if (CCMask == SystemZ::CCMASK_CMP_GE)
3378 }
3379 if (EffectivelyUnsigned && CmpVal < Low) {
3380 if (CCMask == SystemZ::CCMASK_CMP_LE)
3382 if (CCMask == SystemZ::CCMASK_CMP_GT)
3384 }
3385
3386 // Check for equality comparisons with the mask, or the equivalent.
3387 if (CmpVal == Mask) {
3388 if (CCMask == SystemZ::CCMASK_CMP_EQ)
3390 if (CCMask == SystemZ::CCMASK_CMP_NE)
3392 }
3393 if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
3394 if (CCMask == SystemZ::CCMASK_CMP_GT)
3396 if (CCMask == SystemZ::CCMASK_CMP_LE)
3398 }
3399 if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
3400 if (CCMask == SystemZ::CCMASK_CMP_GE)
3402 if (CCMask == SystemZ::CCMASK_CMP_LT)
3404 }
3405
3406 // Check for ordered comparisons with the top bit.
3407 if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
3408 if (CCMask == SystemZ::CCMASK_CMP_LE)
3410 if (CCMask == SystemZ::CCMASK_CMP_GT)
3412 }
3413 if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
3414 if (CCMask == SystemZ::CCMASK_CMP_LT)
3416 if (CCMask == SystemZ::CCMASK_CMP_GE)
3418 }
3419
3420 // If there are just two bits, we can do equality checks for Low and High
3421 // as well.
3422 if (Mask == Low + High) {
3423 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
3425 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
3427 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
3429 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
3431 }
3432
3433 // Looks like we've exhausted our options.
3434 return 0;
3435}
3436
3437// See whether C can be implemented as a TEST UNDER MASK instruction.
3438// Update the arguments with the TM version if so.
3440 Comparison &C) {
3441 // Use VECTOR TEST UNDER MASK for i128 operations.
3442 if (C.Op0.getValueType() == MVT::i128) {
3443 // We can use VTM for EQ/NE comparisons of x & y against 0.
3444 if (C.Op0.getOpcode() == ISD::AND &&
3445 (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3446 C.CCMask == SystemZ::CCMASK_CMP_NE)) {
3447 auto *Mask = dyn_cast<ConstantSDNode>(C.Op1);
3448 if (Mask && Mask->getAPIntValue() == 0) {
3449 C.Opcode = SystemZISD::VTM;
3450 C.Op1 = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, C.Op0.getOperand(1));
3451 C.Op0 = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, C.Op0.getOperand(0));
3452 C.CCValid = SystemZ::CCMASK_VCMP;
3453 if (C.CCMask == SystemZ::CCMASK_CMP_EQ)
3454 C.CCMask = SystemZ::CCMASK_VCMP_ALL;
3455 else
3456 C.CCMask = SystemZ::CCMASK_VCMP_ALL ^ C.CCValid;
3457 }
3458 }
3459 return;
3460 }
3461
3462 // Check that we have a comparison with a constant.
3463 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
3464 if (!ConstOp1)
3465 return;
3466 uint64_t CmpVal = ConstOp1->getZExtValue();
3467
3468 // Check whether the nonconstant input is an AND with a constant mask.
3469 Comparison NewC(C);
3470 uint64_t MaskVal;
3471 ConstantSDNode *Mask = nullptr;
3472 if (C.Op0.getOpcode() == ISD::AND) {
3473 NewC.Op0 = C.Op0.getOperand(0);
3474 NewC.Op1 = C.Op0.getOperand(1);
3475 Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
3476 if (!Mask)
3477 return;
3478 MaskVal = Mask->getZExtValue();
3479 } else {
3480 // There is no instruction to compare with a 64-bit immediate
3481 // so use TMHH instead if possible. We need an unsigned ordered
3482 // comparison with an i64 immediate.
3483 if (NewC.Op0.getValueType() != MVT::i64 ||
3484 NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
3485 NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
3486 NewC.ICmpType == SystemZICMP::SignedOnly)
3487 return;
3488 // Convert LE and GT comparisons into LT and GE.
3489 if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
3490 NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
3491 if (CmpVal == uint64_t(-1))
3492 return;
3493 CmpVal += 1;
3494 NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
3495 }
3496 // If the low N bits of Op1 are zero than the low N bits of Op0 can
3497 // be masked off without changing the result.
3498 MaskVal = -(CmpVal & -CmpVal);
3499 NewC.ICmpType = SystemZICMP::UnsignedOnly;
3500 }
3501 if (!MaskVal)
3502 return;
3503
3504 // Check whether the combination of mask, comparison value and comparison
3505 // type are suitable.
3506 unsigned BitSize = NewC.Op0.getValueSizeInBits();
3507 unsigned NewCCMask, ShiftVal;
3508 if (NewC.ICmpType != SystemZICMP::SignedOnly &&
3509 NewC.Op0.getOpcode() == ISD::SHL &&
3510 isSimpleShift(NewC.Op0, ShiftVal) &&
3511 (MaskVal >> ShiftVal != 0) &&
3512 ((CmpVal >> ShiftVal) << ShiftVal) == CmpVal &&
3513 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
3514 MaskVal >> ShiftVal,
3515 CmpVal >> ShiftVal,
3516 SystemZICMP::Any))) {
3517 NewC.Op0 = NewC.Op0.getOperand(0);
3518 MaskVal >>= ShiftVal;
3519 } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
3520 NewC.Op0.getOpcode() == ISD::SRL &&
3521 isSimpleShift(NewC.Op0, ShiftVal) &&
3522 (MaskVal << ShiftVal != 0) &&
3523 ((CmpVal << ShiftVal) >> ShiftVal) == CmpVal &&
3524 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
3525 MaskVal << ShiftVal,
3526 CmpVal << ShiftVal,
3528 NewC.Op0 = NewC.Op0.getOperand(0);
3529 MaskVal <<= ShiftVal;
3530 } else {
3531 NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
3532 NewC.ICmpType);
3533 if (!NewCCMask)
3534 return;
3535 }
3536
3537 // Go ahead and make the change.
3538 C.Opcode = SystemZISD::TM;
3539 C.Op0 = NewC.Op0;
3540 if (Mask && Mask->getZExtValue() == MaskVal)
3541 C.Op1 = SDValue(Mask, 0);
3542 else
3543 C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
3544 C.CCValid = SystemZ::CCMASK_TM;
3545 C.CCMask = NewCCMask;
3546}
3547
3548// Implement i128 comparison in vector registers.
3549static void adjustICmp128(SelectionDAG &DAG, const SDLoc &DL,
3550 Comparison &C) {
3551 if (C.Opcode != SystemZISD::ICMP)
3552 return;
3553 if (C.Op0.getValueType() != MVT::i128)
3554 return;
3555
3556 // Recognize vector comparison reductions.
3557 if ((C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3558 C.CCMask == SystemZ::CCMASK_CMP_NE) &&
3559 (isNullConstant(C.Op1) || isAllOnesConstant(C.Op1))) {
3560 bool CmpEq = C.CCMask == SystemZ::CCMASK_CMP_EQ;
3561 bool CmpNull = isNullConstant(C.Op1);
3562 SDValue Src = peekThroughBitcasts(C.Op0);
3563 if (Src.hasOneUse() && isBitwiseNot(Src)) {
3564 Src = Src.getOperand(0);
3565 CmpNull = !CmpNull;
3566 }
3567 unsigned Opcode = 0;
3568 if (Src.hasOneUse()) {
3569 switch (Src.getOpcode()) {
3570 case SystemZISD::VICMPE: Opcode = SystemZISD::VICMPES; break;
3571 case SystemZISD::VICMPH: Opcode = SystemZISD::VICMPHS; break;
3572 case SystemZISD::VICMPHL: Opcode = SystemZISD::VICMPHLS; break;
3573 case SystemZISD::VFCMPE: Opcode = SystemZISD::VFCMPES; break;
3574 case SystemZISD::VFCMPH: Opcode = SystemZISD::VFCMPHS; break;
3575 case SystemZISD::VFCMPHE: Opcode = SystemZISD::VFCMPHES; break;
3576 default: break;
3577 }
3578 }
3579 if (Opcode) {
3580 C.Opcode = Opcode;
3581 C.Op0 = Src->getOperand(0);
3582 C.Op1 = Src->getOperand(1);
3583 C.CCValid = SystemZ::CCMASK_VCMP;
3585 if (!CmpEq)
3586 C.CCMask ^= C.CCValid;
3587 return;
3588 }
3589 }
3590
3591 // Everything below here is not useful if we have native i128 compares.
3592 if (DAG.getSubtarget<SystemZSubtarget>().hasVectorEnhancements3())
3593 return;
3594
3595 // (In-)Equality comparisons can be implemented via VCEQGS.
3596 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3597 C.CCMask == SystemZ::CCMASK_CMP_NE) {
3598 C.Opcode = SystemZISD::VICMPES;
3599 C.Op0 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, C.Op0);
3600 C.Op1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, C.Op1);
3601 C.CCValid = SystemZ::CCMASK_VCMP;
3602 if (C.CCMask == SystemZ::CCMASK_CMP_EQ)
3603 C.CCMask = SystemZ::CCMASK_VCMP_ALL;
3604 else
3605 C.CCMask = SystemZ::CCMASK_VCMP_ALL ^ C.CCValid;
3606 return;
3607 }
3608
3609 // Normalize other comparisons to GT.
3610 bool Swap = false, Invert = false;
3611 switch (C.CCMask) {
3612 case SystemZ::CCMASK_CMP_GT: break;
3613 case SystemZ::CCMASK_CMP_LT: Swap = true; break;
3614 case SystemZ::CCMASK_CMP_LE: Invert = true; break;
3615 case SystemZ::CCMASK_CMP_GE: Swap = Invert = true; break;
3616 default: llvm_unreachable("Invalid integer condition!");
3617 }
3618 if (Swap)
3619 std::swap(C.Op0, C.Op1);
3620
3621 if (C.ICmpType == SystemZICMP::UnsignedOnly)
3622 C.Opcode = SystemZISD::UCMP128HI;
3623 else
3624 C.Opcode = SystemZISD::SCMP128HI;
3625 C.CCValid = SystemZ::CCMASK_ANY;
3626 C.CCMask = SystemZ::CCMASK_1;
3627
3628 if (Invert)
3629 C.CCMask ^= C.CCValid;
3630}
3631
3632// See whether the comparison argument contains a redundant AND
3633// and remove it if so. This sometimes happens due to the generic
3634// BRCOND expansion.
3636 Comparison &C) {
3637 if (C.Op0.getOpcode() != ISD::AND)
3638 return;
3639 auto *Mask = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
3640 if (!Mask || Mask->getValueSizeInBits(0) > 64)
3641 return;
3642 KnownBits Known = DAG.computeKnownBits(C.Op0.getOperand(0));
3643 if ((~Known.Zero).getZExtValue() & ~Mask->getZExtValue())
3644 return;
3645
3646 C.Op0 = C.Op0.getOperand(0);
3647}
3648
3649// Return a Comparison that tests the condition-code result of intrinsic
3650// node Call against constant integer CC using comparison code Cond.
3651// Opcode is the opcode of the SystemZISD operation for the intrinsic
3652// and CCValid is the set of possible condition-code results.
3653static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
3654 SDValue Call, unsigned CCValid, uint64_t CC,
3656 Comparison C(Call, SDValue(), SDValue());
3657 C.Opcode = Opcode;
3658 C.CCValid = CCValid;
3659 if (Cond == ISD::SETEQ)
3660 // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
3661 C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
3662 else if (Cond == ISD::SETNE)
3663 // ...and the inverse of that.
3664 C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
3665 else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
3666 // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
3667 // always true for CC>3.
3668 C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1;
3669 else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
3670 // ...and the inverse of that.
3671 C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0;
3672 else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
3673 // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
3674 // always true for CC>3.
3675 C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1;
3676 else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
3677 // ...and the inverse of that.
3678 C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0;
3679 else
3680 llvm_unreachable("Unexpected integer comparison type");
3681 C.CCMask &= CCValid;
3682 return C;
3683}
3684
3685// Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
3686static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
3687 ISD::CondCode Cond, const SDLoc &DL,
3688 SDValue Chain = SDValue(),
3689 bool IsSignaling = false) {
3690 if (CmpOp1.getOpcode() == ISD::Constant) {
3691 assert(!Chain);
3692 unsigned Opcode, CCValid;
3693 if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
3694 CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
3695 isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
3696 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid,
3697 CmpOp1->getAsZExtVal(), Cond);
3698 if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
3699 CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 &&
3700 isIntrinsicWithCC(CmpOp0, Opcode, CCValid))
3701 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid,
3702 CmpOp1->getAsZExtVal(), Cond);
3703 }
3704 Comparison C(CmpOp0, CmpOp1, Chain);
3705 C.CCMask = CCMaskForCondCode(Cond);
3706 if (C.Op0.getValueType().isFloatingPoint()) {
3707 C.CCValid = SystemZ::CCMASK_FCMP;
3708 if (!C.Chain)
3709 C.Opcode = SystemZISD::FCMP;
3710 else if (!IsSignaling)
3711 C.Opcode = SystemZISD::STRICT_FCMP;
3712 else
3713 C.Opcode = SystemZISD::STRICT_FCMPS;
3715 } else {
3716 assert(!C.Chain);
3717 C.CCValid = SystemZ::CCMASK_ICMP;
3718 C.Opcode = SystemZISD::ICMP;
3719 // Choose the type of comparison. Equality and inequality tests can
3720 // use either signed or unsigned comparisons. The choice also doesn't
3721 // matter if both sign bits are known to be clear. In those cases we
3722 // want to give the main isel code the freedom to choose whichever
3723 // form fits best.
3724 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3725 C.CCMask == SystemZ::CCMASK_CMP_NE ||
3726 (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
3727 C.ICmpType = SystemZICMP::Any;
3728 else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
3729 C.ICmpType = SystemZICMP::UnsignedOnly;
3730 else
3731 C.ICmpType = SystemZICMP::SignedOnly;
3732 C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
3733 adjustForRedundantAnd(DAG, DL, C);
3734 adjustZeroCmp(DAG, DL, C);
3735 adjustSubwordCmp(DAG, DL, C);
3736 adjustForSubtraction(DAG, DL, C);
3738 adjustICmpTruncate(DAG, DL, C);
3739 }
3740
3741 if (shouldSwapCmpOperands(C)) {
3742 std::swap(C.Op0, C.Op1);
3743 C.CCMask = SystemZ::reverseCCMask(C.CCMask);
3744 }
3745
3747 adjustICmp128(DAG, DL, C);
3749 return C;
3750}
3751
3752// Emit the comparison instruction described by C.
3753static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
3754 if (!C.Op1.getNode()) {
3755 if (C.Opcode == SystemZISD::CMP_STACKGUARD)
3756 return DAG.getNode(SystemZISD::CMP_STACKGUARD, DL, MVT::i32, C.Op0);
3757 SDNode *Node;
3758 switch (C.Op0.getOpcode()) {
3760 Node = emitIntrinsicWithCCAndChain(DAG, C.Op0, C.Opcode);
3761 return SDValue(Node, 0);
3763 Node = emitIntrinsicWithCC(DAG, C.Op0, C.Opcode);
3764 return SDValue(Node, Node->getNumValues() - 1);
3765 default:
3766 llvm_unreachable("Invalid comparison operands");
3767 }
3768 }
3769 if (C.Opcode == SystemZISD::ICMP)
3770 return DAG.getNode(SystemZISD::ICMP, DL, MVT::i32, C.Op0, C.Op1,
3771 DAG.getTargetConstant(C.ICmpType, DL, MVT::i32));
3772 if (C.Opcode == SystemZISD::TM) {
3773 bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
3775 return DAG.getNode(SystemZISD::TM, DL, MVT::i32, C.Op0, C.Op1,
3776 DAG.getTargetConstant(RegisterOnly, DL, MVT::i32));
3777 }
3778 if (C.Opcode == SystemZISD::VICMPES ||
3779 C.Opcode == SystemZISD::VICMPHS ||
3780 C.Opcode == SystemZISD::VICMPHLS ||
3781 C.Opcode == SystemZISD::VFCMPES ||
3782 C.Opcode == SystemZISD::VFCMPHS ||
3783 C.Opcode == SystemZISD::VFCMPHES) {
3784 EVT IntVT = C.Op0.getValueType().changeVectorElementTypeToInteger();
3785 SDVTList VTs = DAG.getVTList(IntVT, MVT::i32);
3786 SDValue Val = DAG.getNode(C.Opcode, DL, VTs, C.Op0, C.Op1);
3787 return SDValue(Val.getNode(), 1);
3788 }
3789 if (C.Chain) {
3790 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
3791 return DAG.getNode(C.Opcode, DL, VTs, C.Chain, C.Op0, C.Op1);
3792 }
3793 return DAG.getNode(C.Opcode, DL, MVT::i32, C.Op0, C.Op1);
3794}
3795
3796// Implement a 32-bit *MUL_LOHI operation by extending both operands to
3797// 64 bits. Extend is the extension type to use. Store the high part
3798// in Hi and the low part in Lo.
3799static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend,
3800 SDValue Op0, SDValue Op1, SDValue &Hi,
3801 SDValue &Lo) {
3802 Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
3803 Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
3804 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
3805 Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
3806 DAG.getConstant(32, DL, MVT::i64));
3807 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
3808 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
3809}
3810
3811// Lower a binary operation that produces two VT results, one in each
3812// half of a GR128 pair. Op0 and Op1 are the VT operands to the operation,
3813// and Opcode performs the GR128 operation. Store the even register result
3814// in Even and the odd register result in Odd.
3815static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
3816 unsigned Opcode, SDValue Op0, SDValue Op1,
3817 SDValue &Even, SDValue &Odd) {
3818 SDValue Result = DAG.getNode(Opcode, DL, MVT::v2i64, Op0, Op1);
3819 bool Is32Bit = is32Bit(VT);
3820 Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
3821 Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
3822}
3823
3824// Return an i32 value that is 1 if the CC value produced by CCReg is
3825// in the mask CCMask and 0 otherwise. CC is known to have a value
3826// in CCValid, so other values can be ignored.
3827static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue CCReg,
3828 unsigned CCValid, unsigned CCMask) {
3829 SDValue Ops[] = {DAG.getConstant(1, DL, MVT::i32),
3830 DAG.getConstant(0, DL, MVT::i32),
3831 DAG.getTargetConstant(CCValid, DL, MVT::i32),
3832 DAG.getTargetConstant(CCMask, DL, MVT::i32), CCReg};
3833 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, MVT::i32, Ops);
3834}
3835
3836// Return the SystemISD vector comparison operation for CC, or 0 if it cannot
3837// be done directly. Mode is CmpMode::Int for integer comparisons, CmpMode::FP
3838// for regular floating-point comparisons, CmpMode::StrictFP for strict (quiet)
3839// floating-point comparisons, and CmpMode::SignalingFP for strict signaling
3840// floating-point comparisons.
3843 switch (CC) {
3844 case ISD::SETOEQ:
3845 case ISD::SETEQ:
3846 switch (Mode) {
3847 case CmpMode::Int: return SystemZISD::VICMPE;
3848 case CmpMode::FP: return SystemZISD::VFCMPE;
3849 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPE;
3850 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPES;
3851 }
3852 llvm_unreachable("Bad mode");
3853
3854 case ISD::SETOGE:
3855 case ISD::SETGE:
3856 switch (Mode) {
3857 case CmpMode::Int: return 0;
3858 case CmpMode::FP: return SystemZISD::VFCMPHE;
3859 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPHE;
3860 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHES;
3861 }
3862 llvm_unreachable("Bad mode");
3863
3864 case ISD::SETOGT:
3865 case ISD::SETGT:
3866 switch (Mode) {
3867 case CmpMode::Int: return SystemZISD::VICMPH;
3868 case CmpMode::FP: return SystemZISD::VFCMPH;
3869 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPH;
3870 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHS;
3871 }
3872 llvm_unreachable("Bad mode");
3873
3874 case ISD::SETUGT:
3875 switch (Mode) {
3876 case CmpMode::Int: return SystemZISD::VICMPHL;
3877 case CmpMode::FP: return 0;
3878 case CmpMode::StrictFP: return 0;
3879 case CmpMode::SignalingFP: return 0;
3880 }
3881 llvm_unreachable("Bad mode");
3882
3883 default:
3884 return 0;
3885 }
3886}
3887
3888// Return the SystemZISD vector comparison operation for CC or its inverse,
3889// or 0 if neither can be done directly. Indicate in Invert whether the
3890// result is for the inverse of CC. Mode is as above.
3892 bool &Invert) {
3893 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
3894 Invert = false;
3895 return Opcode;
3896 }
3897
3898 CC = ISD::getSetCCInverse(CC, Mode == CmpMode::Int ? MVT::i32 : MVT::f32);
3899 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
3900 Invert = true;
3901 return Opcode;
3902 }
3903
3904 return 0;
3905}
3906
3907// Return a v2f64 that contains the extended form of elements Start and Start+1
3908// of v4f32 value Op. If Chain is nonnull, return the strict form.
3909static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL,
3910 SDValue Op, SDValue Chain) {
3911 int Mask[] = { Start, -1, Start + 1, -1 };
3912 Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
3913 if (Chain) {
3914 SDVTList VTs = DAG.getVTList(MVT::v2f64, MVT::Other);
3915 return DAG.getNode(SystemZISD::STRICT_VEXTEND, DL, VTs, Chain, Op);
3916 }
3917 return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
3918}
3919
3920// Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
3921// producing a result of type VT. If Chain is nonnull, return the strict form.
3922SDValue SystemZTargetLowering::getVectorCmp(SelectionDAG &DAG, unsigned Opcode,
3923 const SDLoc &DL, EVT VT,
3924 SDValue CmpOp0,
3925 SDValue CmpOp1,
3926 SDValue Chain) const {
3927 // There is no hardware support for v4f32 (unless we have the vector
3928 // enhancements facility 1), so extend the vector into two v2f64s
3929 // and compare those.
3930 if (CmpOp0.getValueType() == MVT::v4f32 &&
3931 !Subtarget.hasVectorEnhancements1()) {
3932 SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0, Chain);
3933 SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0, Chain);
3934 SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1, Chain);
3935 SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1, Chain);
3936 if (Chain) {
3937 SDVTList VTs = DAG.getVTList(MVT::v2i64, MVT::Other);
3938 SDValue HRes = DAG.getNode(Opcode, DL, VTs, Chain, H0, H1);
3939 SDValue LRes = DAG.getNode(Opcode, DL, VTs, Chain, L0, L1);
3940 SDValue Res = DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
3941 SDValue Chains[6] = { H0.getValue(1), L0.getValue(1),
3942 H1.getValue(1), L1.getValue(1),
3943 HRes.getValue(1), LRes.getValue(1) };
3944 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
3945 SDValue Ops[2] = { Res, NewChain };
3946 return DAG.getMergeValues(Ops, DL);
3947 }
3948 SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
3949 SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
3950 return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
3951 }
3952 if (Chain) {
3953 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3954 return DAG.getNode(Opcode, DL, VTs, Chain, CmpOp0, CmpOp1);
3955 }
3956 return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
3957}
3958
3959// Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
3960// an integer mask of type VT. If Chain is nonnull, we have a strict
3961// floating-point comparison. If in addition IsSignaling is true, we have
3962// a strict signaling floating-point comparison.
3963SDValue SystemZTargetLowering::lowerVectorSETCC(SelectionDAG &DAG,
3964 const SDLoc &DL, EVT VT,
3966 SDValue CmpOp0,
3967 SDValue CmpOp1,
3968 SDValue Chain,
3969 bool IsSignaling) const {
3970 bool IsFP = CmpOp0.getValueType().isFloatingPoint();
3971 assert (!Chain || IsFP);
3972 assert (!IsSignaling || Chain);
3973 CmpMode Mode = IsSignaling ? CmpMode::SignalingFP :
3974 Chain ? CmpMode::StrictFP : IsFP ? CmpMode::FP : CmpMode::Int;
3975 bool Invert = false;
3976 SDValue Cmp;
3977 switch (CC) {
3978 // Handle tests for order using (or (ogt y x) (oge x y)).
3979 case ISD::SETUO:
3980 Invert = true;
3981 [[fallthrough]];
3982 case ISD::SETO: {
3983 assert(IsFP && "Unexpected integer comparison");
3984 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
3985 DL, VT, CmpOp1, CmpOp0, Chain);
3986 SDValue GE = getVectorCmp(DAG, getVectorComparison(ISD::SETOGE, Mode),
3987 DL, VT, CmpOp0, CmpOp1, Chain);
3988 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
3989 if (Chain)
3990 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
3991 LT.getValue(1), GE.getValue(1));
3992 break;
3993 }
3994
3995 // Handle <> tests using (or (ogt y x) (ogt x y)).
3996 case ISD::SETUEQ:
3997 Invert = true;
3998 [[fallthrough]];
3999 case ISD::SETONE: {
4000 assert(IsFP && "Unexpected integer comparison");
4001 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
4002 DL, VT, CmpOp1, CmpOp0, Chain);
4003 SDValue GT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
4004 DL, VT, CmpOp0, CmpOp1, Chain);
4005 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
4006 if (Chain)
4007 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4008 LT.getValue(1), GT.getValue(1));
4009 break;
4010 }
4011
4012 // Otherwise a single comparison is enough. It doesn't really
4013 // matter whether we try the inversion or the swap first, since
4014 // there are no cases where both work.
4015 default:
4016 // Optimize sign-bit comparisons to signed compares.
4017 if (Mode == CmpMode::Int && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
4019 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4020 APInt Mask;
4021 if (CmpOp0.getOpcode() == ISD::AND &&
4022 ISD::isConstantSplatVector(CmpOp0.getOperand(1), Mask) &&
4023 Mask == APInt::getSignMask(EltSize)) {
4025 CmpOp0 = CmpOp0.getOperand(0);
4026 }
4027 }
4028 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
4029 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1, Chain);
4030 else {
4032 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
4033 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0, Chain);
4034 else
4035 llvm_unreachable("Unhandled comparison");
4036 }
4037 if (Chain)
4038 Chain = Cmp.getValue(1);
4039 break;
4040 }
4041 if (Invert) {
4042 SDValue Mask =
4043 DAG.getSplatBuildVector(VT, DL, DAG.getAllOnesConstant(DL, MVT::i64));
4044 Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
4045 }
4046 if (Chain && Chain.getNode() != Cmp.getNode()) {
4047 SDValue Ops[2] = { Cmp, Chain };
4048 Cmp = DAG.getMergeValues(Ops, DL);
4049 }
4050 return Cmp;
4051}
4052
4053SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
4054 SelectionDAG &DAG) const {
4055 SDValue CmpOp0 = Op.getOperand(0);
4056 SDValue CmpOp1 = Op.getOperand(1);
4057 ISD::CondCode CC = Op.getOperandCondCode(2);
4058 SDLoc DL(Op);
4059 EVT VT = Op.getValueType();
4060 if (VT.isVector())
4061 return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
4062
4063 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
4064 SDValue CCReg = emitCmp(DAG, DL, C);
4065 return emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
4066}
4067
4068SDValue SystemZTargetLowering::lowerSTRICT_FSETCC(SDValue Op,
4069 SelectionDAG &DAG,
4070 bool IsSignaling) const {
4071 SDValue Chain = Op.getOperand(0);
4072 SDValue CmpOp0 = Op.getOperand(1);
4073 SDValue CmpOp1 = Op.getOperand(2);
4074 ISD::CondCode CC = Op.getOperandCondCode(3);
4075 SDLoc DL(Op);
4076 EVT VT = Op.getNode()->getValueType(0);
4077 if (VT.isVector()) {
4078 SDValue Res = lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1,
4079 Chain, IsSignaling);
4080 return Res.getValue(Op.getResNo());
4081 }
4082
4083 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL, Chain, IsSignaling));
4084 SDValue CCReg = emitCmp(DAG, DL, C);
4085 CCReg->setFlags(Op->getFlags());
4086 SDValue Result = emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
4087 SDValue Ops[2] = { Result, CCReg.getValue(1) };
4088 return DAG.getMergeValues(Ops, DL);
4089}
4090
4091SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4092 ISD::CondCode CC = Op.getOperandCondCode(1);
4093 SDValue CmpOp0 = Op.getOperand(2);
4094 SDValue CmpOp1 = Op.getOperand(3);
4095 SDValue Dest = Op.getOperand(4);
4096 SDLoc DL(Op);
4097
4098 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
4099 SDValue CCReg = emitCmp(DAG, DL, C);
4100 return DAG.getNode(
4101 SystemZISD::BR_CCMASK, DL, Op.getValueType(), Op.getOperand(0),
4102 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
4103 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), Dest, CCReg);
4104}
4105
4106// Return true if Pos is CmpOp and Neg is the negative of CmpOp,
4107// allowing Pos and Neg to be wider than CmpOp.
4108static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
4109 return (Neg.getOpcode() == ISD::SUB &&
4110 Neg.getOperand(0).getOpcode() == ISD::Constant &&
4111 Neg.getConstantOperandVal(0) == 0 && Neg.getOperand(1) == Pos &&
4112 (Pos == CmpOp || (Pos.getOpcode() == ISD::SIGN_EXTEND &&
4113 Pos.getOperand(0) == CmpOp)));
4114}
4115
4116// Return the absolute or negative absolute of Op; IsNegative decides which.
4118 bool IsNegative) {
4119 Op = DAG.getNode(ISD::ABS, DL, Op.getValueType(), Op);
4120 if (IsNegative)
4121 Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
4122 DAG.getConstant(0, DL, Op.getValueType()), Op);
4123 return Op;
4124}
4125
4127 Comparison C, SDValue TrueOp, SDValue FalseOp) {
4128 EVT VT = MVT::i128;
4129 unsigned Op;
4130
4131 if (C.CCMask == SystemZ::CCMASK_CMP_NE ||
4132 C.CCMask == SystemZ::CCMASK_CMP_GE ||
4133 C.CCMask == SystemZ::CCMASK_CMP_LE) {
4134 std::swap(TrueOp, FalseOp);
4135 C.CCMask ^= C.CCValid;
4136 }
4137 if (C.CCMask == SystemZ::CCMASK_CMP_LT) {
4138 std::swap(C.Op0, C.Op1);
4139 C.CCMask = SystemZ::CCMASK_CMP_GT;
4140 }
4141 switch (C.CCMask) {
4143 Op = SystemZISD::VICMPE;
4144 break;
4146 if (C.ICmpType == SystemZICMP::UnsignedOnly)
4147 Op = SystemZISD::VICMPHL;
4148 else
4149 Op = SystemZISD::VICMPH;
4150 break;
4151 default:
4152 llvm_unreachable("Unhandled comparison");
4153 break;
4154 }
4155
4156 SDValue Mask = DAG.getNode(Op, DL, VT, C.Op0, C.Op1);
4157 TrueOp = DAG.getNode(ISD::AND, DL, VT, TrueOp, Mask);
4158 FalseOp = DAG.getNode(ISD::AND, DL, VT, FalseOp, DAG.getNOT(DL, Mask, VT));
4159 return DAG.getNode(ISD::OR, DL, VT, TrueOp, FalseOp);
4160}
4161
4162SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
4163 SelectionDAG &DAG) const {
4164 SDValue CmpOp0 = Op.getOperand(0);
4165 SDValue CmpOp1 = Op.getOperand(1);
4166 SDValue TrueOp = Op.getOperand(2);
4167 SDValue FalseOp = Op.getOperand(3);
4168 ISD::CondCode CC = Op.getOperandCondCode(4);
4169 SDLoc DL(Op);
4170
4171 // SELECT_CC involving f16 will not have the cmp-ops promoted by the
4172 // legalizer, as it will be handled according to the type of the resulting
4173 // value. Extend them here if needed.
4174 if (CmpOp0.getSimpleValueType() == MVT::f16) {
4175 CmpOp0 = DAG.getFPExtendOrRound(CmpOp0, SDLoc(CmpOp0), MVT::f32);
4176 CmpOp1 = DAG.getFPExtendOrRound(CmpOp1, SDLoc(CmpOp1), MVT::f32);
4177 }
4178
4179 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
4180
4181 // Check for absolute and negative-absolute selections, including those
4182 // where the comparison value is sign-extended (for LPGFR and LNGFR).
4183 // This check supplements the one in DAGCombiner.
4184 if (C.Opcode == SystemZISD::ICMP && C.CCMask != SystemZ::CCMASK_CMP_EQ &&
4185 C.CCMask != SystemZ::CCMASK_CMP_NE &&
4186 C.Op1.getOpcode() == ISD::Constant &&
4187 cast<ConstantSDNode>(C.Op1)->getValueSizeInBits(0) <= 64 &&
4188 C.Op1->getAsZExtVal() == 0) {
4189 if (isAbsolute(C.Op0, TrueOp, FalseOp))
4190 return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
4191 if (isAbsolute(C.Op0, FalseOp, TrueOp))
4192 return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
4193 }
4194
4195 if (Subtarget.hasVectorEnhancements3() &&
4196 C.Opcode == SystemZISD::ICMP &&
4197 C.Op0.getValueType() == MVT::i128 &&
4198 TrueOp.getValueType() == MVT::i128) {
4199 return getI128Select(DAG, DL, C, TrueOp, FalseOp);
4200 }
4201
4202 SDValue CCReg = emitCmp(DAG, DL, C);
4203 SDValue Ops[] = {TrueOp, FalseOp,
4204 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
4205 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), CCReg};
4206
4207 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, Op.getValueType(), Ops);
4208}
4209
4210SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
4211 SelectionDAG &DAG) const {
4212 SDLoc DL(Node);
4213 const GlobalValue *GV = Node->getGlobal();
4214 int64_t Offset = Node->getOffset();
4215 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4217
4219 if (Subtarget.isPC32DBLSymbol(GV, CM)) {
4220 if (isInt<32>(Offset)) {
4221 // Assign anchors at 1<<12 byte boundaries.
4222 uint64_t Anchor = Offset & ~uint64_t(0xfff);
4223 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
4224 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4225
4226 // The offset can be folded into the address if it is aligned to a
4227 // halfword.
4228 Offset -= Anchor;
4229 if (Offset != 0 && (Offset & 1) == 0) {
4230 SDValue Full =
4231 DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
4232 Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
4233 Offset = 0;
4234 }
4235 } else {
4236 // Conservatively load a constant offset greater than 32 bits into a
4237 // register below.
4238 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT);
4239 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4240 }
4241 } else if (Subtarget.isTargetELF()) {
4242 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
4243 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4244 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4246 } else if (Subtarget.isTargetzOS()) {
4247 Result = getADAEntry(DAG, GV, DL, PtrVT);
4248 } else
4249 llvm_unreachable("Unexpected Subtarget");
4250
4251 // If there was a non-zero offset that we didn't fold, create an explicit
4252 // addition for it.
4253 if (Offset != 0)
4254 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
4255 DAG.getSignedConstant(Offset, DL, PtrVT));
4256
4257 return Result;
4258}
4259
4260SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
4261 SelectionDAG &DAG,
4262 unsigned Opcode,
4263 SDValue GOTOffset) const {
4264 SDLoc DL(Node);
4265 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4266 SDValue Chain = DAG.getEntryNode();
4267 SDValue Glue;
4268
4271 report_fatal_error("In GHC calling convention TLS is not supported");
4272
4273 // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
4274 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
4275 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
4276 Glue = Chain.getValue(1);
4277 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
4278 Glue = Chain.getValue(1);
4279
4280 // The first call operand is the chain and the second is the TLS symbol.
4282 Ops.push_back(Chain);
4283 Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
4284 Node->getValueType(0),
4285 0, 0));
4286
4287 // Add argument registers to the end of the list so that they are
4288 // known live into the call.
4289 Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
4290 Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
4291
4292 // Add a register mask operand representing the call-preserved registers.
4293 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4294 const uint32_t *Mask =
4295 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
4296 assert(Mask && "Missing call preserved mask for calling convention");
4297 Ops.push_back(DAG.getRegisterMask(Mask));
4298
4299 // Glue the call to the argument copies.
4300 Ops.push_back(Glue);
4301
4302 // Emit the call.
4303 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4304 Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
4305 Glue = Chain.getValue(1);
4306
4307 // Copy the return value from %r2.
4308 return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
4309}
4310
4311SDValue SystemZTargetLowering::lowerThreadPointer(const SDLoc &DL,
4312 SelectionDAG &DAG) const {
4313 SDValue Chain = DAG.getEntryNode();
4314 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4315
4316 // The high part of the thread pointer is in access register 0.
4317 SDValue TPHi = DAG.getCopyFromReg(Chain, DL, SystemZ::A0, MVT::i32);
4318 TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
4319
4320 // The low part of the thread pointer is in access register 1.
4321 SDValue TPLo = DAG.getCopyFromReg(Chain, DL, SystemZ::A1, MVT::i32);
4322 TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
4323
4324 // Merge them into a single 64-bit address.
4325 SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
4326 DAG.getConstant(32, DL, PtrVT));
4327 return DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
4328}
4329
4330SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
4331 SelectionDAG &DAG) const {
4332 if (DAG.getTarget().useEmulatedTLS())
4333 return LowerToTLSEmulatedModel(Node, DAG);
4334 SDLoc DL(Node);
4335 const GlobalValue *GV = Node->getGlobal();
4336 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4337 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
4338
4341 report_fatal_error("In GHC calling convention TLS is not supported");
4342
4343 SDValue TP = lowerThreadPointer(DL, DAG);
4344
4345 // Get the offset of GA from the thread pointer, based on the TLS model.
4347 switch (model) {
4349 // Load the GOT offset of the tls_index (module ID / per-symbol offset).
4350 SystemZConstantPoolValue *CPV =
4352
4353 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4354 Offset = DAG.getLoad(
4355 PtrVT, DL, DAG.getEntryNode(), Offset,
4357
4358 // Call __tls_get_offset to retrieve the offset.
4359 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
4360 break;
4361 }
4362
4364 // Load the GOT offset of the module ID.
4365 SystemZConstantPoolValue *CPV =
4367
4368 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4369 Offset = DAG.getLoad(
4370 PtrVT, DL, DAG.getEntryNode(), Offset,
4372
4373 // Call __tls_get_offset to retrieve the module base offset.
4374 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
4375
4376 // Note: The SystemZLDCleanupPass will remove redundant computations
4377 // of the module base offset. Count total number of local-dynamic
4378 // accesses to trigger execution of that pass.
4379 SystemZMachineFunctionInfo* MFI =
4380 DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>();
4382
4383 // Add the per-symbol offset.
4385
4386 SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4387 DTPOffset = DAG.getLoad(
4388 PtrVT, DL, DAG.getEntryNode(), DTPOffset,
4390
4391 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
4392 break;
4393 }
4394
4395 case TLSModel::InitialExec: {
4396 // Load the offset from the GOT.
4397 Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
4399 Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
4400 Offset =
4401 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset,
4403 break;
4404 }
4405
4406 case TLSModel::LocalExec: {
4407 // Force the offset into the constant pool and load it from there.
4408 SystemZConstantPoolValue *CPV =
4410
4411 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
4412 Offset = DAG.getLoad(
4413 PtrVT, DL, DAG.getEntryNode(), Offset,
4415 break;
4416 }
4417 }
4418
4419 // Add the base and offset together.
4420 return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
4421}
4422
4423SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
4424 SelectionDAG &DAG) const {
4425 SDLoc DL(Node);
4426 const BlockAddress *BA = Node->getBlockAddress();
4427 int64_t Offset = Node->getOffset();
4428 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4429
4430 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
4431 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4432 return Result;
4433}
4434
4435SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
4436 SelectionDAG &DAG) const {
4437 SDLoc DL(JT);
4438 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4439 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
4440
4441 // Use LARL to load the address of the table.
4442 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4443}
4444
4445SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
4446 SelectionDAG &DAG) const {
4447 SDLoc DL(CP);
4448 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4449
4452 Result =
4453 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign());
4454 else
4455 Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign(),
4456 CP->getOffset());
4457
4458 // Use LARL to load the address of the constant pool entry.
4459 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
4460}
4461
4462SDValue SystemZTargetLowering::lowerFRAMEADDR(SDValue Op,
4463 SelectionDAG &DAG) const {
4464 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
4466 MachineFrameInfo &MFI = MF.getFrameInfo();
4467 MFI.setFrameAddressIsTaken(true);
4468
4469 SDLoc DL(Op);
4470 unsigned Depth = Op.getConstantOperandVal(0);
4471 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4472
4473 // By definition, the frame address is the address of the back chain. (In
4474 // the case of packed stack without backchain, return the address where the
4475 // backchain would have been stored. This will either be an unused space or
4476 // contain a saved register).
4477 int BackChainIdx = TFL->getOrCreateFramePointerSaveIndex(MF);
4478 SDValue BackChain = DAG.getFrameIndex(BackChainIdx, PtrVT);
4479
4480 if (Depth > 0) {
4481 // FIXME The frontend should detect this case.
4482 if (!MF.getSubtarget<SystemZSubtarget>().hasBackChain())
4483 report_fatal_error("Unsupported stack frame traversal count");
4484
4485 SDValue Offset = DAG.getConstant(TFL->getBackchainOffset(MF), DL, PtrVT);
4486 while (Depth--) {
4487 BackChain = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), BackChain,
4488 MachinePointerInfo());
4489 BackChain = DAG.getNode(ISD::ADD, DL, PtrVT, BackChain, Offset);
4490 }
4491 }
4492
4493 return BackChain;
4494}
4495
4496SDValue SystemZTargetLowering::lowerRETURNADDR(SDValue Op,
4497 SelectionDAG &DAG) const {
4499 MachineFrameInfo &MFI = MF.getFrameInfo();
4500 MFI.setReturnAddressIsTaken(true);
4501
4502 SDLoc DL(Op);
4503 unsigned Depth = Op.getConstantOperandVal(0);
4504 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4505
4506 if (Depth > 0) {
4507 // FIXME The frontend should detect this case.
4508 if (!MF.getSubtarget<SystemZSubtarget>().hasBackChain())
4509 report_fatal_error("Unsupported stack frame traversal count");
4510
4511 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
4512 const auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
4513 int Offset = TFL->getReturnAddressOffset(MF);
4514 SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, FrameAddr,
4515 DAG.getSignedConstant(Offset, DL, PtrVT));
4516 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr,
4517 MachinePointerInfo());
4518 }
4519
4520 // Return R14D (Elf) / R7D (XPLINK), which has the return address. Mark it an
4521 // implicit live-in.
4522 SystemZCallingConventionRegisters *CCR = Subtarget.getSpecialRegisters();
4524 &SystemZ::GR64BitRegClass);
4525 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, LinkReg, PtrVT);
4526}
4527
4528SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
4529 SelectionDAG &DAG) const {
4530 SDLoc DL(Op);
4531 SDValue In = Op.getOperand(0);
4532 EVT InVT = In.getValueType();
4533 EVT ResVT = Op.getValueType();
4534
4535 // Convert loads directly. This is normally done by DAGCombiner,
4536 // but we need this case for bitcasts that are created during lowering
4537 // and which are then lowered themselves.
4538 if (auto *LoadN = dyn_cast<LoadSDNode>(In))
4539 if (ISD::isNormalLoad(LoadN)) {
4540 SDValue NewLoad = DAG.getLoad(ResVT, DL, LoadN->getChain(),
4541 LoadN->getBasePtr(), LoadN->getMemOperand());
4542 // Update the chain uses.
4543 DAG.ReplaceAllUsesOfValueWith(SDValue(LoadN, 1), NewLoad.getValue(1));
4544 return NewLoad;
4545 }
4546
4547 if (InVT == MVT::i32 && ResVT == MVT::f32) {
4548 SDValue In64;
4549 if (Subtarget.hasHighWord()) {
4550 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
4551 MVT::i64);
4552 In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
4553 MVT::i64, SDValue(U64, 0), In);
4554 } else {
4555 In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
4556 In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
4557 DAG.getConstant(32, DL, MVT::i64));
4558 }
4559 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
4560 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32,
4561 DL, MVT::f32, Out64);
4562 }
4563 if (InVT == MVT::f32 && ResVT == MVT::i32) {
4564 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
4565 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
4566 MVT::f64, SDValue(U64, 0), In);
4567 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
4568 if (Subtarget.hasHighWord())
4569 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
4570 MVT::i32, Out64);
4571 SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
4572 DAG.getConstant(32, DL, MVT::i64));
4573 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
4574 }
4575 llvm_unreachable("Unexpected bitcast combination");
4576}
4577
4578SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
4579 SelectionDAG &DAG) const {
4580
4581 if (Subtarget.isTargetXPLINK64())
4582 return lowerVASTART_XPLINK(Op, DAG);
4583 else
4584 return lowerVASTART_ELF(Op, DAG);
4585}
4586
4587SDValue SystemZTargetLowering::lowerVASTART_XPLINK(SDValue Op,
4588 SelectionDAG &DAG) const {
4590 SystemZMachineFunctionInfo *FuncInfo =
4591 MF.getInfo<SystemZMachineFunctionInfo>();
4592
4593 SDLoc DL(Op);
4594
4595 // vastart just stores the address of the VarArgsFrameIndex slot into the
4596 // memory location argument.
4597 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4598 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4599 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4600 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4601 MachinePointerInfo(SV));
4602}
4603
4604SDValue SystemZTargetLowering::lowerVASTART_ELF(SDValue Op,
4605 SelectionDAG &DAG) const {
4607 SystemZMachineFunctionInfo *FuncInfo =
4608 MF.getInfo<SystemZMachineFunctionInfo>();
4609 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4610
4611 SDValue Chain = Op.getOperand(0);
4612 SDValue Addr = Op.getOperand(1);
4613 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4614 SDLoc DL(Op);
4615
4616 // The initial values of each field.
4617 const unsigned NumFields = 4;
4618 SDValue Fields[NumFields] = {
4619 DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
4620 DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
4621 DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
4622 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
4623 };
4624
4625 // Store each field into its respective slot.
4626 SDValue MemOps[NumFields];
4627 unsigned Offset = 0;
4628 for (unsigned I = 0; I < NumFields; ++I) {
4629 SDValue FieldAddr = Addr;
4630 if (Offset != 0)
4631 FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
4633 MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
4634 MachinePointerInfo(SV, Offset));
4635 Offset += 8;
4636 }
4637 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4638}
4639
4640SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
4641 SelectionDAG &DAG) const {
4642 SDValue Chain = Op.getOperand(0);
4643 SDValue DstPtr = Op.getOperand(1);
4644 SDValue SrcPtr = Op.getOperand(2);
4645 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4646 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4647 SDLoc DL(Op);
4648
4649 uint32_t Sz =
4650 Subtarget.isTargetXPLINK64() ? DAG.getDataLayout().getPointerSize(0) : 32;
4651 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(Sz, DL),
4652 Align(8), Align(8), /*isVolatile*/ false,
4653 /*AlwaysInline*/ false,
4654 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(DstSV),
4655 MachinePointerInfo(SrcSV));
4656}
4657
4658SDValue
4659SystemZTargetLowering::lowerDYNAMIC_STACKALLOC(SDValue Op,
4660 SelectionDAG &DAG) const {
4661 if (Subtarget.isTargetXPLINK64())
4662 return lowerDYNAMIC_STACKALLOC_XPLINK(Op, DAG);
4663 else
4664 return lowerDYNAMIC_STACKALLOC_ELF(Op, DAG);
4665}
4666
4667SDValue
4668SystemZTargetLowering::lowerDYNAMIC_STACKALLOC_XPLINK(SDValue Op,
4669 SelectionDAG &DAG) const {
4670 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
4672 bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack");
4673 SDValue Chain = Op.getOperand(0);
4674 SDValue Size = Op.getOperand(1);
4675 SDValue Align = Op.getOperand(2);
4676 SDLoc DL(Op);
4677
4678 // If user has set the no alignment function attribute, ignore
4679 // alloca alignments.
4680 uint64_t AlignVal = (RealignOpt ? Align->getAsZExtVal() : 0);
4681
4682 uint64_t StackAlign = TFI->getStackAlignment();
4683 uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
4684 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
4685
4686 SDValue NeededSpace = Size;
4687
4688 // Add extra space for alignment if needed.
4689 EVT PtrVT = getPointerTy(MF.getDataLayout());
4690 if (ExtraAlignSpace)
4691 NeededSpace = DAG.getNode(ISD::ADD, DL, PtrVT, NeededSpace,
4692 DAG.getConstant(ExtraAlignSpace, DL, PtrVT));
4693
4694 bool IsSigned = false;
4695 bool DoesNotReturn = false;
4696 bool IsReturnValueUsed = false;
4697 EVT VT = Op.getValueType();
4698 SDValue AllocaCall =
4699 makeExternalCall(Chain, DAG, "@@ALCAXP", VT, ArrayRef(NeededSpace),
4700 CallingConv::C, IsSigned, DL, DoesNotReturn,
4701 IsReturnValueUsed)
4702 .first;
4703
4704 // Perform a CopyFromReg from %GPR4 (stack pointer register). Chain and Glue
4705 // to end of call in order to ensure it isn't broken up from the call
4706 // sequence.
4707 auto &Regs = Subtarget.getSpecialRegisters<SystemZXPLINK64Registers>();
4708 Register SPReg = Regs.getStackPointerRegister();
4709 Chain = AllocaCall.getValue(1);
4710 SDValue Glue = AllocaCall.getValue(2);
4711 SDValue NewSPRegNode = DAG.getCopyFromReg(Chain, DL, SPReg, PtrVT, Glue);
4712 Chain = NewSPRegNode.getValue(1);
4713
4714 MVT PtrMVT = getPointerMemTy(MF.getDataLayout());
4715 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, PtrMVT);
4716 SDValue Result = DAG.getNode(ISD::ADD, DL, PtrMVT, NewSPRegNode, ArgAdjust);
4717
4718 // Dynamically realign if needed.
4719 if (ExtraAlignSpace) {
4720 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
4721 DAG.getConstant(ExtraAlignSpace, DL, PtrVT));
4722 Result = DAG.getNode(ISD::AND, DL, PtrVT, Result,
4723 DAG.getConstant(~(RequiredAlign - 1), DL, PtrVT));
4724 }
4725
4726 SDValue Ops[2] = {Result, Chain};
4727 return DAG.getMergeValues(Ops, DL);
4728}
4729
4730SDValue
4731SystemZTargetLowering::lowerDYNAMIC_STACKALLOC_ELF(SDValue Op,
4732 SelectionDAG &DAG) const {
4733 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
4735 bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack");
4736 bool StoreBackchain = MF.getSubtarget<SystemZSubtarget>().hasBackChain();
4737
4738 SDValue Chain = Op.getOperand(0);
4739 SDValue Size = Op.getOperand(1);
4740 SDValue Align = Op.getOperand(2);
4741 SDLoc DL(Op);
4742
4743 // If user has set the no alignment function attribute, ignore
4744 // alloca alignments.
4745 uint64_t AlignVal = (RealignOpt ? Align->getAsZExtVal() : 0);
4746
4747 uint64_t StackAlign = TFI->getStackAlignment();
4748 uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
4749 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
4750
4752 SDValue NeededSpace = Size;
4753
4754 // Get a reference to the stack pointer.
4755 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
4756
4757 // If we need a backchain, save it now.
4758 SDValue Backchain;
4759 if (StoreBackchain)
4760 Backchain = DAG.getLoad(MVT::i64, DL, Chain, getBackchainAddress(OldSP, DAG),
4761 MachinePointerInfo());
4762
4763 // Add extra space for alignment if needed.
4764 if (ExtraAlignSpace)
4765 NeededSpace = DAG.getNode(ISD::ADD, DL, MVT::i64, NeededSpace,
4766 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
4767
4768 // Get the new stack pointer value.
4769 SDValue NewSP;
4770 if (hasInlineStackProbe(MF)) {
4771 NewSP = DAG.getNode(SystemZISD::PROBED_ALLOCA, DL,
4772 DAG.getVTList(MVT::i64, MVT::Other), Chain, OldSP, NeededSpace);
4773 Chain = NewSP.getValue(1);
4774 }
4775 else {
4776 NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, NeededSpace);
4777 // Copy the new stack pointer back.
4778 Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
4779 }
4780
4781 // The allocated data lives above the 160 bytes allocated for the standard
4782 // frame, plus any outgoing stack arguments. We don't know how much that
4783 // amounts to yet, so emit a special ADJDYNALLOC placeholder.
4784 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
4785 SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
4786
4787 // Dynamically realign if needed.
4788 if (RequiredAlign > StackAlign) {
4789 Result =
4790 DAG.getNode(ISD::ADD, DL, MVT::i64, Result,
4791 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
4792 Result =
4793 DAG.getNode(ISD::AND, DL, MVT::i64, Result,
4794 DAG.getConstant(~(RequiredAlign - 1), DL, MVT::i64));
4795 }
4796
4797 if (StoreBackchain)
4798 Chain = DAG.getStore(Chain, DL, Backchain, getBackchainAddress(NewSP, DAG),
4799 MachinePointerInfo());
4800
4801 SDValue Ops[2] = { Result, Chain };
4802 return DAG.getMergeValues(Ops, DL);
4803}
4804
4805SDValue SystemZTargetLowering::lowerGET_DYNAMIC_AREA_OFFSET(
4806 SDValue Op, SelectionDAG &DAG) const {
4807 SDLoc DL(Op);
4808
4809 return DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
4810}
4811
4812SDValue SystemZTargetLowering::lowerMULH(SDValue Op,
4813 SelectionDAG &DAG,
4814 unsigned Opcode) const {
4815 EVT VT = Op.getValueType();
4816 SDLoc DL(Op);
4817 SDValue Even, Odd;
4818
4819 // This custom expander is only used on z17 and later for 64-bit types.
4820 assert(!is32Bit(VT));
4821 assert(Subtarget.hasMiscellaneousExtensions2());
4822
4823 // SystemZISD::xMUL_LOHI returns the low result in the odd register and
4824 // the high result in the even register. Return the latter.
4825 lowerGR128Binary(DAG, DL, VT, Opcode,
4826 Op.getOperand(0), Op.getOperand(1), Even, Odd);
4827 return Even;
4828}
4829
4830SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
4831 SelectionDAG &DAG) const {
4832 EVT VT = Op.getValueType();
4833 SDLoc DL(Op);
4834 SDValue Ops[2];
4835 if (is32Bit(VT))
4836 // Just do a normal 64-bit multiplication and extract the results.
4837 // We define this so that it can be used for constant division.
4838 lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
4839 Op.getOperand(1), Ops[1], Ops[0]);
4840 else if (Subtarget.hasMiscellaneousExtensions2())
4841 // SystemZISD::SMUL_LOHI returns the low result in the odd register and
4842 // the high result in the even register. ISD::SMUL_LOHI is defined to
4843 // return the low half first, so the results are in reverse order.
4844 lowerGR128Binary(DAG, DL, VT, SystemZISD::SMUL_LOHI,
4845 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
4846 else {
4847 // Do a full 128-bit multiplication based on SystemZISD::UMUL_LOHI:
4848 //
4849 // (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
4850 //
4851 // but using the fact that the upper halves are either all zeros
4852 // or all ones:
4853 //
4854 // (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
4855 //
4856 // and grouping the right terms together since they are quicker than the
4857 // multiplication:
4858 //
4859 // (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
4860 SDValue C63 = DAG.getConstant(63, DL, MVT::i64);
4861 SDValue LL = Op.getOperand(0);
4862 SDValue RL = Op.getOperand(1);
4863 SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
4864 SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
4865 // SystemZISD::UMUL_LOHI returns the low result in the odd register and
4866 // the high result in the even register. ISD::SMUL_LOHI is defined to
4867 // return the low half first, so the results are in reverse order.
4868 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
4869 LL, RL, Ops[1], Ops[0]);
4870 SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
4871 SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
4872 SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
4873 Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
4874 }
4875 return DAG.getMergeValues(Ops, DL);
4876}
4877
4878SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
4879 SelectionDAG &DAG) const {
4880 EVT VT = Op.getValueType();
4881 SDLoc DL(Op);
4882 SDValue Ops[2];
4883 if (is32Bit(VT))
4884 // Just do a normal 64-bit multiplication and extract the results.
4885 // We define this so that it can be used for constant division.
4886 lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
4887 Op.getOperand(1), Ops[1], Ops[0]);
4888 else
4889 // SystemZISD::UMUL_LOHI returns the low result in the odd register and
4890 // the high result in the even register. ISD::UMUL_LOHI is defined to
4891 // return the low half first, so the results are in reverse order.
4892 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
4893 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
4894 return DAG.getMergeValues(Ops, DL);
4895}
4896
4897SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
4898 SelectionDAG &DAG) const {
4899 SDValue Op0 = Op.getOperand(0);
4900 SDValue Op1 = Op.getOperand(1);
4901 EVT VT = Op.getValueType();
4902 SDLoc DL(Op);
4903
4904 // We use DSGF for 32-bit division. This means the first operand must
4905 // always be 64-bit, and the second operand should be 32-bit whenever
4906 // that is possible, to improve performance.
4907 if (is32Bit(VT))
4908 Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
4909 else if (DAG.ComputeNumSignBits(Op1) > 32)
4910 Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
4911
4912 // DSG(F) returns the remainder in the even register and the
4913 // quotient in the odd register.
4914 SDValue Ops[2];
4915 lowerGR128Binary(DAG, DL, VT, SystemZISD::SDIVREM, Op0, Op1, Ops[1], Ops[0]);
4916 return DAG.getMergeValues(Ops, DL);
4917}
4918
4919SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
4920 SelectionDAG &DAG) const {
4921 EVT VT = Op.getValueType();
4922 SDLoc DL(Op);
4923
4924 // DL(G) returns the remainder in the even register and the
4925 // quotient in the odd register.
4926 SDValue Ops[2];
4927 lowerGR128Binary(DAG, DL, VT, SystemZISD::UDIVREM,
4928 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
4929 return DAG.getMergeValues(Ops, DL);
4930}
4931
4932SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
4933 assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
4934
4935 // Get the known-zero masks for each operand.
4936 SDValue Ops[] = {Op.getOperand(0), Op.getOperand(1)};
4937 KnownBits Known[2] = {DAG.computeKnownBits(Ops[0]),
4938 DAG.computeKnownBits(Ops[1])};
4939
4940 // See if the upper 32 bits of one operand and the lower 32 bits of the
4941 // other are known zero. They are the low and high operands respectively.
4942 uint64_t Masks[] = { Known[0].Zero.getZExtValue(),
4943 Known[1].Zero.getZExtValue() };
4944 unsigned High, Low;
4945 if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
4946 High = 1, Low = 0;
4947 else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
4948 High = 0, Low = 1;
4949 else
4950 return Op;
4951
4952 SDValue LowOp = Ops[Low];
4953 SDValue HighOp = Ops[High];
4954
4955 // If the high part is a constant, we're better off using IILH.
4956 if (HighOp.getOpcode() == ISD::Constant)
4957 return Op;
4958
4959 // If the low part is a constant that is outside the range of LHI,
4960 // then we're better off using IILF.
4961 if (LowOp.getOpcode() == ISD::Constant) {
4962 int64_t Value = int32_t(LowOp->getAsZExtVal());
4963 if (!isInt<16>(Value))
4964 return Op;
4965 }
4966
4967 // Check whether the high part is an AND that doesn't change the
4968 // high 32 bits and just masks out low bits. We can skip it if so.
4969 if (HighOp.getOpcode() == ISD::AND &&
4970 HighOp.getOperand(1).getOpcode() == ISD::Constant) {
4971 SDValue HighOp0 = HighOp.getOperand(0);
4973 if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
4974 HighOp = HighOp0;
4975 }
4976
4977 // Take advantage of the fact that all GR32 operations only change the
4978 // low 32 bits by truncating Low to an i32 and inserting it directly
4979 // using a subreg. The interesting cases are those where the truncation
4980 // can be folded.
4981 SDLoc DL(Op);
4982 SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
4983 return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
4984 MVT::i64, HighOp, Low32);
4985}
4986
4987// Lower SADDO/SSUBO/UADDO/USUBO nodes.
4988SDValue SystemZTargetLowering::lowerXALUO(SDValue Op,
4989 SelectionDAG &DAG) const {
4990 SDNode *N = Op.getNode();
4991 SDValue LHS = N->getOperand(0);
4992 SDValue RHS = N->getOperand(1);
4993 SDLoc DL(N);
4994
4995 if (N->getValueType(0) == MVT::i128) {
4996 unsigned BaseOp = 0;
4997 unsigned FlagOp = 0;
4998 bool IsBorrow = false;
4999 switch (Op.getOpcode()) {
5000 default: llvm_unreachable("Unknown instruction!");
5001 case ISD::UADDO:
5002 BaseOp = ISD::ADD;
5003 FlagOp = SystemZISD::VACC;
5004 break;
5005 case ISD::USUBO:
5006 BaseOp = ISD::SUB;
5007 FlagOp = SystemZISD::VSCBI;
5008 IsBorrow = true;
5009 break;
5010 }
5011 SDValue Result = DAG.getNode(BaseOp, DL, MVT::i128, LHS, RHS);
5012 SDValue Flag = DAG.getNode(FlagOp, DL, MVT::i128, LHS, RHS);
5013 Flag = DAG.getNode(ISD::AssertZext, DL, MVT::i128, Flag,
5014 DAG.getValueType(MVT::i1));
5015 Flag = DAG.getZExtOrTrunc(Flag, DL, N->getValueType(1));
5016 if (IsBorrow)
5017 Flag = DAG.getNode(ISD::XOR, DL, Flag.getValueType(),
5018 Flag, DAG.getConstant(1, DL, Flag.getValueType()));
5019 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Flag);
5020 }
5021
5022 unsigned BaseOp = 0;
5023 unsigned CCValid = 0;
5024 unsigned CCMask = 0;
5025
5026 switch (Op.getOpcode()) {
5027 default: llvm_unreachable("Unknown instruction!");
5028 case ISD::SADDO:
5029 BaseOp = SystemZISD::SADDO;
5030 CCValid = SystemZ::CCMASK_ARITH;
5032 break;
5033 case ISD::SSUBO:
5034 BaseOp = SystemZISD::SSUBO;
5035 CCValid = SystemZ::CCMASK_ARITH;
5037 break;
5038 case ISD::UADDO:
5039 BaseOp = SystemZISD::UADDO;
5040 CCValid = SystemZ::CCMASK_LOGICAL;
5042 break;
5043 case ISD::USUBO:
5044 BaseOp = SystemZISD::USUBO;
5045 CCValid = SystemZ::CCMASK_LOGICAL;
5047 break;
5048 }
5049
5050 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
5051 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
5052
5053 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
5054 if (N->getValueType(1) == MVT::i1)
5055 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
5056
5057 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
5058}
5059
5060static bool isAddCarryChain(SDValue Carry) {
5061 while (Carry.getOpcode() == ISD::UADDO_CARRY &&
5062 Carry->getValueType(0) != MVT::i128)
5063 Carry = Carry.getOperand(2);
5064 return Carry.getOpcode() == ISD::UADDO &&
5065 Carry->getValueType(0) != MVT::i128;
5066}
5067
5068static bool isSubBorrowChain(SDValue Carry) {
5069 while (Carry.getOpcode() == ISD::USUBO_CARRY &&
5070 Carry->getValueType(0) != MVT::i128)
5071 Carry = Carry.getOperand(2);
5072 return Carry.getOpcode() == ISD::USUBO &&
5073 Carry->getValueType(0) != MVT::i128;
5074}
5075
5076// Lower UADDO_CARRY/USUBO_CARRY nodes.
5077SDValue SystemZTargetLowering::lowerUADDSUBO_CARRY(SDValue Op,
5078 SelectionDAG &DAG) const {
5079
5080 SDNode *N = Op.getNode();
5081 MVT VT = N->getSimpleValueType(0);
5082
5083 // Let legalize expand this if it isn't a legal type yet.
5084 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
5085 return SDValue();
5086
5087 SDValue LHS = N->getOperand(0);
5088 SDValue RHS = N->getOperand(1);
5089 SDValue Carry = Op.getOperand(2);
5090 SDLoc DL(N);
5091
5092 if (VT == MVT::i128) {
5093 unsigned BaseOp = 0;
5094 unsigned FlagOp = 0;
5095 bool IsBorrow = false;
5096 switch (Op.getOpcode()) {
5097 default: llvm_unreachable("Unknown instruction!");
5098 case ISD::UADDO_CARRY:
5099 BaseOp = SystemZISD::VAC;
5100 FlagOp = SystemZISD::VACCC;
5101 break;
5102 case ISD::USUBO_CARRY:
5103 BaseOp = SystemZISD::VSBI;
5104 FlagOp = SystemZISD::VSBCBI;
5105 IsBorrow = true;
5106 break;
5107 }
5108 if (IsBorrow)
5109 Carry = DAG.getNode(ISD::XOR, DL, Carry.getValueType(),
5110 Carry, DAG.getConstant(1, DL, Carry.getValueType()));
5111 Carry = DAG.getZExtOrTrunc(Carry, DL, MVT::i128);
5112 SDValue Result = DAG.getNode(BaseOp, DL, MVT::i128, LHS, RHS, Carry);
5113 SDValue Flag = DAG.getNode(FlagOp, DL, MVT::i128, LHS, RHS, Carry);
5114 Flag = DAG.getNode(ISD::AssertZext, DL, MVT::i128, Flag,
5115 DAG.getValueType(MVT::i1));
5116 Flag = DAG.getZExtOrTrunc(Flag, DL, N->getValueType(1));
5117 if (IsBorrow)
5118 Flag = DAG.getNode(ISD::XOR, DL, Flag.getValueType(),
5119 Flag, DAG.getConstant(1, DL, Flag.getValueType()));
5120 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Flag);
5121 }
5122
5123 unsigned BaseOp = 0;
5124 unsigned CCValid = 0;
5125 unsigned CCMask = 0;
5126
5127 switch (Op.getOpcode()) {
5128 default: llvm_unreachable("Unknown instruction!");
5129 case ISD::UADDO_CARRY:
5130 if (!isAddCarryChain(Carry))
5131 return SDValue();
5132
5133 BaseOp = SystemZISD::ADDCARRY;
5134 CCValid = SystemZ::CCMASK_LOGICAL;
5136 break;
5137 case ISD::USUBO_CARRY:
5138 if (!isSubBorrowChain(Carry))
5139 return SDValue();
5140
5141 BaseOp = SystemZISD::SUBCARRY;
5142 CCValid = SystemZ::CCMASK_LOGICAL;
5144 break;
5145 }
5146
5147 // Set the condition code from the carry flag.
5148 Carry = DAG.getNode(SystemZISD::GET_CCMASK, DL, MVT::i32, Carry,
5149 DAG.getConstant(CCValid, DL, MVT::i32),
5150 DAG.getConstant(CCMask, DL, MVT::i32));
5151
5152 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5153 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS, Carry);
5154
5155 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
5156 if (N->getValueType(1) == MVT::i1)
5157 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
5158
5159 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
5160}
5161
5162SDValue SystemZTargetLowering::lowerPDEP(SDValue Op, SelectionDAG &DAG) const {
5163 SDLoc DL(Op);
5164 assert(Op.getValueType() == MVT::i64 && "Expected i64 PDEP");
5165 SDValue Val = Op.getOperand(0);
5166 SDValue Mask = Op.getOperand(1);
5167
5168 if (auto *MaskC = dyn_cast<ConstantSDNode>(Mask)) {
5169 unsigned PopCount = MaskC->getAPIntValue().popcount();
5170 if (PopCount == 0)
5171 return DAG.getConstant(0, DL, MVT::i64);
5172 if (PopCount == 64)
5173 return Val;
5174 SDValue ShiftedVal =
5175 DAG.getNode(ISD::SHL, DL, MVT::i64, Val,
5176 DAG.getConstant(64 - PopCount, DL, MVT::i64));
5177 return DAG.getNode(
5178 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64,
5179 DAG.getTargetConstant(Intrinsic::s390_bdepg, DL, MVT::i32), ShiftedVal,
5180 Mask);
5181 }
5182
5183 SDValue PopCount = DAG.getNode(ISD::CTPOP, DL, MVT::i64, Mask);
5184 SDValue ShiftAmt = DAG.getNode(ISD::AND, DL, MVT::i64,
5185 DAG.getNegative(PopCount, DL, MVT::i64),
5186 DAG.getConstant(63, DL, MVT::i64));
5187 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, MVT::i64, Val, ShiftAmt);
5188 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64,
5189 DAG.getTargetConstant(Intrinsic::s390_bdepg, DL, MVT::i32),
5190 ShiftedVal, Mask);
5191}
5192
5193SDValue SystemZTargetLowering::lowerPEXT(SDValue Op, SelectionDAG &DAG) const {
5194 SDLoc DL(Op);
5195 assert(Op.getValueType() == MVT::i64 && "Expected i64 PEXT");
5196 SDValue Val = Op.getOperand(0);
5197 SDValue Mask = Op.getOperand(1);
5198
5199 SDValue Bext = DAG.getNode(
5200 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64,
5201 DAG.getTargetConstant(Intrinsic::s390_bextg, DL, MVT::i32), Val, Mask);
5202
5203 if (auto *MaskC = dyn_cast<ConstantSDNode>(Mask)) {
5204 unsigned PopCount = MaskC->getAPIntValue().popcount();
5205 if (PopCount == 0)
5206 return DAG.getConstant(0, DL, MVT::i64);
5207 if (PopCount == 64)
5208 return Val;
5209 return DAG.getNode(ISD::SRL, DL, MVT::i64, Bext,
5210 DAG.getConstant(64 - PopCount, DL, MVT::i64));
5211 }
5212
5213 SDValue PopCount = DAG.getNode(ISD::CTPOP, DL, MVT::i64, Mask);
5214 SDValue ShiftAmt = DAG.getNode(ISD::AND, DL, MVT::i64,
5215 DAG.getNegative(PopCount, DL, MVT::i64),
5216 DAG.getConstant(63, DL, MVT::i64));
5217 return DAG.getNode(ISD::SRL, DL, MVT::i64, Bext, ShiftAmt);
5218}
5219
5220SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op,
5221 SelectionDAG &DAG) const {
5222 EVT VT = Op.getValueType();
5223 SDLoc DL(Op);
5224 Op = Op.getOperand(0);
5225
5226 if (VT.getScalarSizeInBits() == 128) {
5227 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op);
5228 Op = DAG.getNode(ISD::CTPOP, DL, MVT::v2i64, Op);
5229 SDValue Tmp = DAG.getSplatBuildVector(MVT::v2i64, DL,
5230 DAG.getConstant(0, DL, MVT::i64));
5231 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
5232 return Op;
5233 }
5234
5235 // Handle vector types via VPOPCT.
5236 if (VT.isVector()) {
5237 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op);
5238 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op);
5239 switch (VT.getScalarSizeInBits()) {
5240 case 8:
5241 break;
5242 case 16: {
5243 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
5244 SDValue Shift = DAG.getConstant(8, DL, MVT::i32);
5245 SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift);
5246 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
5247 Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift);
5248 break;
5249 }
5250 case 32: {
5251 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
5252 DAG.getConstant(0, DL, MVT::i32));
5253 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
5254 break;
5255 }
5256 case 64: {
5257 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
5258 DAG.getConstant(0, DL, MVT::i32));
5259 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp);
5260 Tmp = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, Tmp);
5261 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
5262 break;
5263 }
5264 default:
5265 llvm_unreachable("Unexpected type");
5266 }
5267 return Op;
5268 }
5269
5270 // Get the known-zero mask for the operand.
5271 KnownBits Known = DAG.computeKnownBits(Op);
5272 unsigned NumSignificantBits = Known.getMaxValue().getActiveBits();
5273 if (NumSignificantBits == 0)
5274 return DAG.getConstant(0, DL, VT);
5275
5276 // Skip known-zero high parts of the operand.
5277 int64_t OrigBitSize = VT.getSizeInBits();
5278 int64_t BitSize = llvm::bit_ceil(NumSignificantBits);
5279 BitSize = std::min(BitSize, OrigBitSize);
5280
5281 // The POPCNT instruction counts the number of bits in each byte.
5282 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op);
5283 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op);
5284 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
5285
5286 // Add up per-byte counts in a binary tree. All bits of Op at
5287 // position larger than BitSize remain zero throughout.
5288 for (int64_t I = BitSize / 2; I >= 8; I = I / 2) {
5289 SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT));
5290 if (BitSize != OrigBitSize)
5291 Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp,
5292 DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT));
5293 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
5294 }
5295
5296 // Extract overall result from high byte.
5297 if (BitSize > 8)
5298 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
5299 DAG.getConstant(BitSize - 8, DL, VT));
5300
5301 return Op;
5302}
5303
5304SDValue SystemZTargetLowering::lowerATOMIC_FENCE(SDValue Op,
5305 SelectionDAG &DAG) const {
5306 SDLoc DL(Op);
5307 AtomicOrdering FenceOrdering =
5308 static_cast<AtomicOrdering>(Op.getConstantOperandVal(1));
5309 SyncScope::ID FenceSSID =
5310 static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
5311
5312 // The only fence that needs an instruction is a sequentially-consistent
5313 // cross-thread fence.
5314 if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
5315 FenceSSID == SyncScope::System) {
5316 return SDValue(DAG.getMachineNode(SystemZ::Serialize, DL, MVT::Other,
5317 Op.getOperand(0)),
5318 0);
5319 }
5320
5321 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
5322 return DAG.getNode(ISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
5323}
5324
5325SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
5326 SelectionDAG &DAG) const {
5327 EVT RegVT = Op.getValueType();
5328 if (RegVT.getSizeInBits() == 128)
5329 return lowerATOMIC_LDST_I128(Op, DAG);
5330 return lowerLoadF16(Op, DAG);
5331}
5332
5333SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
5334 SelectionDAG &DAG) const {
5335 auto *Node = cast<AtomicSDNode>(Op.getNode());
5336 if (Node->getMemoryVT().getSizeInBits() == 128)
5337 return lowerATOMIC_LDST_I128(Op, DAG);
5338 return lowerStoreF16(Op, DAG);
5339}
5340
5341SDValue SystemZTargetLowering::lowerATOMIC_LDST_I128(SDValue Op,
5342 SelectionDAG &DAG) const {
5343 auto *Node = cast<AtomicSDNode>(Op.getNode());
5344 assert(
5345 (Node->getMemoryVT() == MVT::i128 || Node->getMemoryVT() == MVT::f128) &&
5346 "Only custom lowering i128 or f128.");
5347 // Use same code to handle both legal and non-legal i128 types.
5349 LowerOperationWrapper(Node, Results, DAG);
5350 return DAG.getMergeValues(Results, SDLoc(Op));
5351}
5352
5353// Prepare for a Compare And Swap for a subword operation. This needs to be
5354// done in memory with 4 bytes at natural alignment.
5356 SDValue &AlignedAddr, SDValue &BitShift,
5357 SDValue &NegBitShift) {
5358 EVT PtrVT = Addr.getValueType();
5359 EVT WideVT = MVT::i32;
5360
5361 // Get the address of the containing word.
5362 AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
5363 DAG.getSignedConstant(-4, DL, PtrVT));
5364
5365 // Get the number of bits that the word must be rotated left in order
5366 // to bring the field to the top bits of a GR32.
5367 BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
5368 DAG.getConstant(3, DL, PtrVT));
5369 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
5370
5371 // Get the complementing shift amount, for rotating a field in the top
5372 // bits back to its proper position.
5373 NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
5374 DAG.getConstant(0, DL, WideVT), BitShift);
5375
5376}
5377
5378// N is an 8- or 16-bit ATOMIC_LOAD_* operation. Lower it into the fullword
5379// ATOMIC_LOADW_* operation.
5380void SystemZTargetLowering::lowerATOMIC_LOAD_OP(
5382 unsigned Opcode) const {
5383 auto *Node = cast<AtomicSDNode>(N);
5384
5385 EVT NarrowVT = Node->getMemoryVT();
5386 EVT WideVT = MVT::i32;
5387 int64_t BitSize = NarrowVT.getSizeInBits();
5388 SDValue ChainIn = Node->getChain();
5389 SDValue Addr = Node->getBasePtr();
5390 SDValue Src2 = Node->getVal();
5391 MachineMemOperand *MMO = Node->getMemOperand();
5392 SDLoc DL(Node);
5393
5394 // Convert atomic subtracts of constants into additions.
5395 if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
5396 if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
5397 Opcode = SystemZISD::ATOMIC_LOADW_ADD;
5398 Src2 = DAG.getConstant(-Const->getAPIntValue(), DL, Src2.getValueType());
5399 }
5400
5401 SDValue AlignedAddr, BitShift, NegBitShift;
5402 getCSAddressAndShifts(Addr, DAG, DL, AlignedAddr, BitShift, NegBitShift);
5403
5404 // Extend the source operand to 32 bits and prepare it for the inner loop.
5405 // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
5406 // operations require the source to be shifted in advance. (This shift
5407 // can be folded if the source is constant.) For AND and NAND, the lower
5408 // bits must be set, while for other opcodes they should be left clear.
5409 Src2 = DAG.getNode(ISD::ANY_EXTEND, DL, WideVT, Src2);
5410 if (Opcode != SystemZISD::ATOMIC_SWAPW)
5411 Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
5412 DAG.getConstant(32 - BitSize, DL, WideVT));
5413 if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
5414 Opcode == SystemZISD::ATOMIC_LOADW_NAND)
5415 Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
5416 DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT));
5417
5418 // Construct the ATOMIC_LOADW_* node.
5419 SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
5420 SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
5421 DAG.getConstant(BitSize, DL, WideVT) };
5422 SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
5423 NarrowVT, MMO);
5424
5425 // Rotate the result of the final CS so that the field is in the lower
5426 // bits of a GR32, then truncate it.
5427 SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
5428 DAG.getConstant(BitSize, DL, WideVT));
5429 SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
5430 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, NarrowVT, Result));
5431 Results.push_back(AtomicOp.getValue(1));
5432}
5433
5434// Op is a 32- or 64-bit ATOMIC_LOAD_SUB operation. Convert it into an
5435// addition.
5436SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
5437 SelectionDAG &DAG) const {
5438 auto *Node = cast<AtomicSDNode>(Op.getNode());
5439 EVT MemVT = Node->getMemoryVT();
5440 assert(Op.getValueType() == MemVT && "Mismatched VTs");
5441 assert(Subtarget.hasInterlockedAccess1() &&
5442 "Should have been expanded by AtomicExpand pass.");
5443 SDValue Src2 = Node->getVal();
5444 SDLoc DL(Src2);
5445 SDValue NegSrc2 =
5446 DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT), Src2);
5447 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT, Node->getChain(),
5448 Node->getBasePtr(), NegSrc2, Node->getMemOperand());
5449}
5450
5451// Lower 8/16/32/64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS node.
5452SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
5453 SelectionDAG &DAG) const {
5454 auto *Node = cast<AtomicSDNode>(Op.getNode());
5455 SDValue ChainIn = Node->getOperand(0);
5456 SDValue Addr = Node->getOperand(1);
5457 SDValue CmpVal = Node->getOperand(2);
5458 SDValue SwapVal = Node->getOperand(3);
5459 MachineMemOperand *MMO = Node->getMemOperand();
5460 SDLoc DL(Node);
5461
5462 if (Node->getMemoryVT() == MVT::i128) {
5463 // Use same code to handle both legal and non-legal i128 types.
5465 LowerOperationWrapper(Node, Results, DAG);
5466 return DAG.getMergeValues(Results, DL);
5467 }
5468
5469 // We have native support for 32-bit and 64-bit compare and swap, but we
5470 // still need to expand extracting the "success" result from the CC.
5471 EVT NarrowVT = Node->getMemoryVT();
5472 EVT WideVT = NarrowVT == MVT::i64 ? MVT::i64 : MVT::i32;
5473 if (NarrowVT == WideVT) {
5474 SDVTList Tys = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
5475 SDValue Ops[] = { ChainIn, Addr, CmpVal, SwapVal };
5476 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP,
5477 DL, Tys, Ops, NarrowVT, MMO);
5478 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
5480
5481 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), AtomicOp.getValue(0));
5482 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
5483 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
5484 return SDValue();
5485 }
5486
5487 // Convert 8-bit and 16-bit compare and swap to a loop, implemented
5488 // via a fullword ATOMIC_CMP_SWAPW operation.
5489 int64_t BitSize = NarrowVT.getSizeInBits();
5490
5491 SDValue AlignedAddr, BitShift, NegBitShift;
5492 getCSAddressAndShifts(Addr, DAG, DL, AlignedAddr, BitShift, NegBitShift);
5493
5494 // Construct the ATOMIC_CMP_SWAPW node.
5495 SDVTList VTList = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
5496 SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
5497 NegBitShift, DAG.getConstant(BitSize, DL, WideVT) };
5498 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
5499 VTList, Ops, NarrowVT, MMO);
5500 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
5502
5503 // emitAtomicCmpSwapW() will zero extend the result (original value).
5504 SDValue OrigVal = DAG.getNode(ISD::AssertZext, DL, WideVT, AtomicOp.getValue(0),
5505 DAG.getValueType(NarrowVT));
5506 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), OrigVal);
5507 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
5508 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
5509 return SDValue();
5510}
5511
5513SystemZTargetLowering::getTargetMMOFlags(const Instruction &I) const {
5514 // Because of how we convert atomic_load and atomic_store to normal loads and
5515 // stores in the DAG, we need to ensure that the MMOs are marked volatile
5516 // since DAGCombine hasn't been updated to account for atomic, but non
5517 // volatile loads. (See D57601)
5518 if (auto *SI = dyn_cast<StoreInst>(&I))
5519 if (SI->isAtomic())
5521 if (auto *LI = dyn_cast<LoadInst>(&I))
5522 if (LI->isAtomic())
5524 if (auto *AI = dyn_cast<AtomicRMWInst>(&I))
5525 if (AI->isAtomic())
5527 if (auto *AI = dyn_cast<AtomicCmpXchgInst>(&I))
5528 if (AI->isAtomic())
5531}
5532
5533SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
5534 SelectionDAG &DAG) const {
5536 auto *Regs = Subtarget.getSpecialRegisters();
5538 report_fatal_error("Variable-sized stack allocations are not supported "
5539 "in GHC calling convention");
5540 return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
5541 Regs->getStackPointerRegister(), Op.getValueType());
5542}
5543
5544SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
5545 SelectionDAG &DAG) const {
5547 auto *Regs = Subtarget.getSpecialRegisters();
5548
5550 report_fatal_error("Variable-sized stack allocations are not supported "
5551 "in GHC calling convention");
5552
5553 SDValue Chain = Op.getOperand(0);
5554 SDValue NewSP = Op.getOperand(1);
5555 SDLoc DL(Op);
5556
5557 // XPLINK: @@ALCAXP (lowerDYNAMIC_STACKALLOC_XPLINK) moves the frame header
5558 // (register save area and reserved words at SP + bias) down with the stack
5559 // pointer, and calls made while the stack pointer is lowered place their
5560 // arguments over the old header. The current header must be copied back to
5561 // the restored stack pointer, otherwise the epilogue and the LE stack walk
5562 // use a clobbered header (abend U4083). No signal may be delivered while
5563 // the stack pointer is changed and the header is copied, so this is done in
5564 // a stub routine (emitted once per module by the AsmPrinter), which gets
5565 // the new stack pointer in R1 and is called with BASR 3,3.
5566 if (Subtarget.isTargetXPLINK64()) {
5567 SDValue Glue;
5568 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, NewSP, Glue);
5569 Glue = Chain.getValue(1);
5570 return DAG.getNode(SystemZISD::XPLINK_STACKRESTORE, DL, MVT::Other, Chain,
5571 Glue);
5572 }
5573
5574 bool StoreBackchain = MF.getSubtarget<SystemZSubtarget>().hasBackChain();
5575 SDValue Backchain;
5576 if (StoreBackchain) {
5577 SDValue OldSP = DAG.getCopyFromReg(
5578 Chain, DL, Regs->getStackPointerRegister(), MVT::i64);
5579 Backchain =
5580 DAG.getLoad(MVT::i64, DL, Chain, getBackchainAddress(OldSP, DAG),
5581 MachinePointerInfo());
5582 }
5583
5584 Chain = DAG.getCopyToReg(Chain, DL, Regs->getStackPointerRegister(), NewSP);
5585
5586 if (StoreBackchain)
5587 Chain = DAG.getStore(Chain, DL, Backchain, getBackchainAddress(NewSP, DAG),
5588 MachinePointerInfo());
5589
5590 return Chain;
5591}
5592
5593SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
5594 SelectionDAG &DAG) const {
5595 bool IsData = Op.getConstantOperandVal(4);
5596 if (!IsData)
5597 // Just preserve the chain.
5598 return Op.getOperand(0);
5599
5600 SDLoc DL(Op);
5601 bool IsWrite = Op.getConstantOperandVal(2);
5602 unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
5603 auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
5604 SDValue Ops[] = {Op.getOperand(0), DAG.getTargetConstant(Code, DL, MVT::i32),
5605 Op.getOperand(1)};
5606 return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, DL,
5607 Node->getVTList(), Ops,
5608 Node->getMemoryVT(), Node->getMemOperand());
5609}
5610
5611SDValue
5612SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
5613 SelectionDAG &DAG) const {
5614 unsigned Opcode, CCValid;
5615 if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) {
5616 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
5617 SDNode *Node = emitIntrinsicWithCCAndChain(DAG, Op, Opcode);
5618 SDValue CC = getCCResult(DAG, SDValue(Node, 0));
5619 DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC);
5620 return SDValue();
5621 }
5622
5623 return SDValue();
5624}
5625
5626SDValue
5627SystemZTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
5628 SelectionDAG &DAG) const {
5629 unsigned Opcode, CCValid;
5630 if (isIntrinsicWithCC(Op, Opcode, CCValid)) {
5631 SDNode *Node = emitIntrinsicWithCC(DAG, Op, Opcode);
5632 if (Op->getNumValues() == 1)
5633 return getCCResult(DAG, SDValue(Node, 0));
5634 assert(Op->getNumValues() == 2 && "Expected a CC and non-CC result");
5635 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), Op->getVTList(),
5636 SDValue(Node, 0), getCCResult(DAG, SDValue(Node, 1)));
5637 }
5638
5639 unsigned Id = Op.getConstantOperandVal(0);
5640 switch (Id) {
5641 case Intrinsic::thread_pointer:
5642 return lowerThreadPointer(SDLoc(Op), DAG);
5643
5644 case Intrinsic::s390_vpdi:
5645 return DAG.getNode(SystemZISD::PERMUTE_DWORDS, SDLoc(Op), Op.getValueType(),
5646 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5647
5648 case Intrinsic::s390_vperm:
5649 return DAG.getNode(SystemZISD::PERMUTE, SDLoc(Op), Op.getValueType(),
5650 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5651
5652 case Intrinsic::s390_vuphb:
5653 case Intrinsic::s390_vuphh:
5654 case Intrinsic::s390_vuphf:
5655 case Intrinsic::s390_vuphg:
5656 return DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(Op), Op.getValueType(),
5657 Op.getOperand(1));
5658
5659 case Intrinsic::s390_vuplhb:
5660 case Intrinsic::s390_vuplhh:
5661 case Intrinsic::s390_vuplhf:
5662 case Intrinsic::s390_vuplhg:
5663 return DAG.getNode(SystemZISD::UNPACKL_HIGH, SDLoc(Op), Op.getValueType(),
5664 Op.getOperand(1));
5665
5666 case Intrinsic::s390_vuplb:
5667 case Intrinsic::s390_vuplhw:
5668 case Intrinsic::s390_vuplf:
5669 case Intrinsic::s390_vuplg:
5670 return DAG.getNode(SystemZISD::UNPACK_LOW, SDLoc(Op), Op.getValueType(),
5671 Op.getOperand(1));
5672
5673 case Intrinsic::s390_vupllb:
5674 case Intrinsic::s390_vupllh:
5675 case Intrinsic::s390_vupllf:
5676 case Intrinsic::s390_vupllg:
5677 return DAG.getNode(SystemZISD::UNPACKL_LOW, SDLoc(Op), Op.getValueType(),
5678 Op.getOperand(1));
5679
5680 case Intrinsic::s390_vsumb:
5681 case Intrinsic::s390_vsumh:
5682 case Intrinsic::s390_vsumgh:
5683 case Intrinsic::s390_vsumgf:
5684 case Intrinsic::s390_vsumqf:
5685 case Intrinsic::s390_vsumqg:
5686 return DAG.getNode(SystemZISD::VSUM, SDLoc(Op), Op.getValueType(),
5687 Op.getOperand(1), Op.getOperand(2));
5688
5689 case Intrinsic::s390_vaq:
5690 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5691 Op.getOperand(1), Op.getOperand(2));
5692 case Intrinsic::s390_vaccb:
5693 case Intrinsic::s390_vacch:
5694 case Intrinsic::s390_vaccf:
5695 case Intrinsic::s390_vaccg:
5696 case Intrinsic::s390_vaccq:
5697 return DAG.getNode(SystemZISD::VACC, SDLoc(Op), Op.getValueType(),
5698 Op.getOperand(1), Op.getOperand(2));
5699 case Intrinsic::s390_vacq:
5700 return DAG.getNode(SystemZISD::VAC, SDLoc(Op), Op.getValueType(),
5701 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5702 case Intrinsic::s390_vacccq:
5703 return DAG.getNode(SystemZISD::VACCC, SDLoc(Op), Op.getValueType(),
5704 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5705
5706 case Intrinsic::s390_vsq:
5707 return DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(),
5708 Op.getOperand(1), Op.getOperand(2));
5709 case Intrinsic::s390_vscbib:
5710 case Intrinsic::s390_vscbih:
5711 case Intrinsic::s390_vscbif:
5712 case Intrinsic::s390_vscbig:
5713 case Intrinsic::s390_vscbiq:
5714 return DAG.getNode(SystemZISD::VSCBI, SDLoc(Op), Op.getValueType(),
5715 Op.getOperand(1), Op.getOperand(2));
5716 case Intrinsic::s390_vsbiq:
5717 return DAG.getNode(SystemZISD::VSBI, SDLoc(Op), Op.getValueType(),
5718 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5719 case Intrinsic::s390_vsbcbiq:
5720 return DAG.getNode(SystemZISD::VSBCBI, SDLoc(Op), Op.getValueType(),
5721 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5722
5723 case Intrinsic::s390_vmhb:
5724 case Intrinsic::s390_vmhh:
5725 case Intrinsic::s390_vmhf:
5726 case Intrinsic::s390_vmhg:
5727 case Intrinsic::s390_vmhq:
5728 return DAG.getNode(ISD::MULHS, SDLoc(Op), Op.getValueType(),
5729 Op.getOperand(1), Op.getOperand(2));
5730 case Intrinsic::s390_vmlhb:
5731 case Intrinsic::s390_vmlhh:
5732 case Intrinsic::s390_vmlhf:
5733 case Intrinsic::s390_vmlhg:
5734 case Intrinsic::s390_vmlhq:
5735 return DAG.getNode(ISD::MULHU, SDLoc(Op), Op.getValueType(),
5736 Op.getOperand(1), Op.getOperand(2));
5737
5738 case Intrinsic::s390_vavgb:
5739 case Intrinsic::s390_vavgh:
5740 case Intrinsic::s390_vavgf:
5741 case Intrinsic::s390_vavgg:
5742 case Intrinsic::s390_vavgq:
5743 return DAG.getNode(ISD::AVGCEILS, SDLoc(Op), Op.getValueType(),
5744 Op.getOperand(1), Op.getOperand(2));
5745 case Intrinsic::s390_vavglb:
5746 case Intrinsic::s390_vavglh:
5747 case Intrinsic::s390_vavglf:
5748 case Intrinsic::s390_vavglg:
5749 case Intrinsic::s390_vavglq:
5750 return DAG.getNode(ISD::AVGCEILU, SDLoc(Op), Op.getValueType(),
5751 Op.getOperand(1), Op.getOperand(2));
5752
5753 case Intrinsic::s390_vmahb:
5754 case Intrinsic::s390_vmahh:
5755 case Intrinsic::s390_vmahf:
5756 case Intrinsic::s390_vmahg:
5757 case Intrinsic::s390_vmahq:
5758 return DAG.getNode(SystemZISD::VMAH, SDLoc(Op), Op.getValueType(),
5759 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5760 case Intrinsic::s390_vmalhb:
5761 case Intrinsic::s390_vmalhh:
5762 case Intrinsic::s390_vmalhf:
5763 case Intrinsic::s390_vmalhg:
5764 case Intrinsic::s390_vmalhq:
5765 return DAG.getNode(SystemZISD::VMALH, SDLoc(Op), Op.getValueType(),
5766 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5767
5768 case Intrinsic::s390_vmeb:
5769 case Intrinsic::s390_vmeh:
5770 case Intrinsic::s390_vmef:
5771 case Intrinsic::s390_vmeg:
5772 return DAG.getNode(SystemZISD::VME, SDLoc(Op), Op.getValueType(),
5773 Op.getOperand(1), Op.getOperand(2));
5774 case Intrinsic::s390_vmleb:
5775 case Intrinsic::s390_vmleh:
5776 case Intrinsic::s390_vmlef:
5777 case Intrinsic::s390_vmleg:
5778 return DAG.getNode(SystemZISD::VMLE, SDLoc(Op), Op.getValueType(),
5779 Op.getOperand(1), Op.getOperand(2));
5780 case Intrinsic::s390_vmob:
5781 case Intrinsic::s390_vmoh:
5782 case Intrinsic::s390_vmof:
5783 case Intrinsic::s390_vmog:
5784 return DAG.getNode(SystemZISD::VMO, SDLoc(Op), Op.getValueType(),
5785 Op.getOperand(1), Op.getOperand(2));
5786 case Intrinsic::s390_vmlob:
5787 case Intrinsic::s390_vmloh:
5788 case Intrinsic::s390_vmlof:
5789 case Intrinsic::s390_vmlog:
5790 return DAG.getNode(SystemZISD::VMLO, SDLoc(Op), Op.getValueType(),
5791 Op.getOperand(1), Op.getOperand(2));
5792
5793 case Intrinsic::s390_vmaeb:
5794 case Intrinsic::s390_vmaeh:
5795 case Intrinsic::s390_vmaef:
5796 case Intrinsic::s390_vmaeg:
5797 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5798 DAG.getNode(SystemZISD::VME, SDLoc(Op), Op.getValueType(),
5799 Op.getOperand(1), Op.getOperand(2)),
5800 Op.getOperand(3));
5801 case Intrinsic::s390_vmaleb:
5802 case Intrinsic::s390_vmaleh:
5803 case Intrinsic::s390_vmalef:
5804 case Intrinsic::s390_vmaleg:
5805 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5806 DAG.getNode(SystemZISD::VMLE, SDLoc(Op), Op.getValueType(),
5807 Op.getOperand(1), Op.getOperand(2)),
5808 Op.getOperand(3));
5809 case Intrinsic::s390_vmaob:
5810 case Intrinsic::s390_vmaoh:
5811 case Intrinsic::s390_vmaof:
5812 case Intrinsic::s390_vmaog:
5813 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5814 DAG.getNode(SystemZISD::VMO, SDLoc(Op), Op.getValueType(),
5815 Op.getOperand(1), Op.getOperand(2)),
5816 Op.getOperand(3));
5817 case Intrinsic::s390_vmalob:
5818 case Intrinsic::s390_vmaloh:
5819 case Intrinsic::s390_vmalof:
5820 case Intrinsic::s390_vmalog:
5821 return DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(),
5822 DAG.getNode(SystemZISD::VMLO, SDLoc(Op), Op.getValueType(),
5823 Op.getOperand(1), Op.getOperand(2)),
5824 Op.getOperand(3));
5825 }
5826
5827 return SDValue();
5828}
5829
5830namespace {
5831// Says that SystemZISD operation Opcode can be used to perform the equivalent
5832// of a VPERM with permute vector Bytes. If Opcode takes three operands,
5833// Operand is the constant third operand, otherwise it is the number of
5834// bytes in each element of the result.
5835struct Permute {
5836 unsigned Opcode;
5837 unsigned Operand;
5838 unsigned char Bytes[SystemZ::VectorBytes];
5839};
5840}
5841
5842static const Permute PermuteForms[] = {
5843 // VMRHG
5844 { SystemZISD::MERGE_HIGH, 8,
5845 { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } },
5846 // VMRHF
5847 { SystemZISD::MERGE_HIGH, 4,
5848 { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } },
5849 // VMRHH
5850 { SystemZISD::MERGE_HIGH, 2,
5851 { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } },
5852 // VMRHB
5853 { SystemZISD::MERGE_HIGH, 1,
5854 { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } },
5855 // VMRLG
5856 { SystemZISD::MERGE_LOW, 8,
5857 { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } },
5858 // VMRLF
5859 { SystemZISD::MERGE_LOW, 4,
5860 { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
5861 // VMRLH
5862 { SystemZISD::MERGE_LOW, 2,
5863 { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
5864 // VMRLB
5865 { SystemZISD::MERGE_LOW, 1,
5866 { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
5867 // VPKG
5868 { SystemZISD::PACK, 4,
5869 { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } },
5870 // VPKF
5871 { SystemZISD::PACK, 2,
5872 { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
5873 // VPKH
5874 { SystemZISD::PACK, 1,
5875 { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
5876 // VPDI V1, V2, 4 (low half of V1, high half of V2)
5877 { SystemZISD::PERMUTE_DWORDS, 4,
5878 { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } },
5879 // VPDI V1, V2, 1 (high half of V1, low half of V2)
5880 { SystemZISD::PERMUTE_DWORDS, 1,
5881 { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } }
5882};
5883
5884// Called after matching a vector shuffle against a particular pattern.
5885// Both the original shuffle and the pattern have two vector operands.
5886// OpNos[0] is the operand of the original shuffle that should be used for
5887// operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything.
5888// OpNos[1] is the same for operand 1 of the pattern. Resolve these -1s and
5889// set OpNo0 and OpNo1 to the shuffle operands that should actually be used
5890// for operands 0 and 1 of the pattern.
5891static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) {
5892 if (OpNos[0] < 0) {
5893 if (OpNos[1] < 0)
5894 return false;
5895 OpNo0 = OpNo1 = OpNos[1];
5896 } else if (OpNos[1] < 0) {
5897 OpNo0 = OpNo1 = OpNos[0];
5898 } else {
5899 OpNo0 = OpNos[0];
5900 OpNo1 = OpNos[1];
5901 }
5902 return true;
5903}
5904
5905// Bytes is a VPERM-like permute vector, except that -1 is used for
5906// undefined bytes. Return true if the VPERM can be implemented using P.
5907// When returning true set OpNo0 to the VPERM operand that should be
5908// used for operand 0 of P and likewise OpNo1 for operand 1 of P.
5909//
5910// For example, if swapping the VPERM operands allows P to match, OpNo0
5911// will be 1 and OpNo1 will be 0. If instead Bytes only refers to one
5912// operand, but rewriting it to use two duplicated operands allows it to
5913// match P, then OpNo0 and OpNo1 will be the same.
5914static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P,
5915 unsigned &OpNo0, unsigned &OpNo1) {
5916 int OpNos[] = { -1, -1 };
5917 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
5918 int Elt = Bytes[I];
5919 if (Elt >= 0) {
5920 // Make sure that the two permute vectors use the same suboperand
5921 // byte number. Only the operand numbers (the high bits) are
5922 // allowed to differ.
5923 if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1))
5924 return false;
5925 int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes;
5926 int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes;
5927 // Make sure that the operand mappings are consistent with previous
5928 // elements.
5929 if (OpNos[ModelOpNo] == 1 - RealOpNo)
5930 return false;
5931 OpNos[ModelOpNo] = RealOpNo;
5932 }
5933 }
5934 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
5935}
5936
5937// As above, but search for a matching permute.
5938static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes,
5939 unsigned &OpNo0, unsigned &OpNo1) {
5940 for (auto &P : PermuteForms)
5941 if (matchPermute(Bytes, P, OpNo0, OpNo1))
5942 return &P;
5943 return nullptr;
5944}
5945
5946// Bytes is a VPERM-like permute vector, except that -1 is used for
5947// undefined bytes. This permute is an operand of an outer permute.
5948// See whether redistributing the -1 bytes gives a shuffle that can be
5949// implemented using P. If so, set Transform to a VPERM-like permute vector
5950// that, when applied to the result of P, gives the original permute in Bytes.
5952 const Permute &P,
5953 SmallVectorImpl<int> &Transform) {
5954 unsigned To = 0;
5955 for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) {
5956 int Elt = Bytes[From];
5957 if (Elt < 0)
5958 // Byte number From of the result is undefined.
5959 Transform[From] = -1;
5960 else {
5961 while (P.Bytes[To] != Elt) {
5962 To += 1;
5963 if (To == SystemZ::VectorBytes)
5964 return false;
5965 }
5966 Transform[From] = To;
5967 }
5968 }
5969 return true;
5970}
5971
5972// As above, but search for a matching permute.
5973static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes,
5974 SmallVectorImpl<int> &Transform) {
5975 for (auto &P : PermuteForms)
5976 if (matchDoublePermute(Bytes, P, Transform))
5977 return &P;
5978 return nullptr;
5979}
5980
5981// Convert the mask of the given shuffle op into a byte-level mask,
5982// as if it had type vNi8.
5983static bool getVPermMask(SDValue ShuffleOp,
5984 SmallVectorImpl<int> &Bytes) {
5985 EVT VT = ShuffleOp.getValueType();
5986 unsigned NumElements = VT.getVectorNumElements();
5987 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
5988
5989 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(ShuffleOp)) {
5990 Bytes.resize(NumElements * BytesPerElement, -1);
5991 for (unsigned I = 0; I < NumElements; ++I) {
5992 int Index = VSN->getMaskElt(I);
5993 if (Index >= 0)
5994 for (unsigned J = 0; J < BytesPerElement; ++J)
5995 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
5996 }
5997 return true;
5998 }
5999 if (SystemZISD::SPLAT == ShuffleOp.getOpcode() &&
6000 isa<ConstantSDNode>(ShuffleOp.getOperand(1))) {
6001 unsigned Index = ShuffleOp.getConstantOperandVal(1);
6002 Bytes.resize(NumElements * BytesPerElement, -1);
6003 for (unsigned I = 0; I < NumElements; ++I)
6004 for (unsigned J = 0; J < BytesPerElement; ++J)
6005 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
6006 return true;
6007 }
6008 return false;
6009}
6010
6011// Bytes is a VPERM-like permute vector, except that -1 is used for
6012// undefined bytes. See whether bytes [Start, Start + BytesPerElement) of
6013// the result come from a contiguous sequence of bytes from one input.
6014// Set Base to the selector for the first byte if so.
6015static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start,
6016 unsigned BytesPerElement, int &Base) {
6017 Base = -1;
6018 for (unsigned I = 0; I < BytesPerElement; ++I) {
6019 if (Bytes[Start + I] >= 0) {
6020 unsigned Elem = Bytes[Start + I];
6021 if (Base < 0) {
6022 Base = Elem - I;
6023 // Make sure the bytes would come from one input operand.
6024 if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size())
6025 return false;
6026 } else if (unsigned(Base) != Elem - I)
6027 return false;
6028 }
6029 }
6030 return true;
6031}
6032
6033// Bytes is a VPERM-like permute vector, except that -1 is used for
6034// undefined bytes. Return true if it can be performed using VSLDB.
6035// When returning true, set StartIndex to the shift amount and OpNo0
6036// and OpNo1 to the VPERM operands that should be used as the first
6037// and second shift operand respectively.
6039 unsigned &StartIndex, unsigned &OpNo0,
6040 unsigned &OpNo1) {
6041 int OpNos[] = { -1, -1 };
6042 int Shift = -1;
6043 for (unsigned I = 0; I < 16; ++I) {
6044 int Index = Bytes[I];
6045 if (Index >= 0) {
6046 int ExpectedShift = (Index - I) % SystemZ::VectorBytes;
6047 int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes;
6048 int RealOpNo = unsigned(Index) / SystemZ::VectorBytes;
6049 if (Shift < 0)
6050 Shift = ExpectedShift;
6051 else if (Shift != ExpectedShift)
6052 return false;
6053 // Make sure that the operand mappings are consistent with previous
6054 // elements.
6055 if (OpNos[ModelOpNo] == 1 - RealOpNo)
6056 return false;
6057 OpNos[ModelOpNo] = RealOpNo;
6058 }
6059 }
6060 StartIndex = Shift;
6061 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
6062}
6063
6064// Create a node that performs P on operands Op0 and Op1, casting the
6065// operands to the appropriate type. The type of the result is determined by P.
6067 const Permute &P, SDValue Op0, SDValue Op1) {
6068 // VPDI (PERMUTE_DWORDS) always operates on v2i64s. The input
6069 // elements of a PACK are twice as wide as the outputs.
6070 unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 :
6071 P.Opcode == SystemZISD::PACK ? P.Operand * 2 :
6072 P.Operand);
6073 // Cast both operands to the appropriate type.
6074 MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8),
6075 SystemZ::VectorBytes / InBytes);
6076 Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0);
6077 Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1);
6078 SDValue Op;
6079 if (P.Opcode == SystemZISD::PERMUTE_DWORDS) {
6080 SDValue Op2 = DAG.getTargetConstant(P.Operand, DL, MVT::i32);
6081 Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2);
6082 } else if (P.Opcode == SystemZISD::PACK) {
6083 MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8),
6084 SystemZ::VectorBytes / P.Operand);
6085 Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1);
6086 } else {
6087 Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1);
6088 }
6089 return Op;
6090}
6091
6092static bool isZeroVector(SDValue N) {
6093 if (N->getOpcode() == ISD::BITCAST)
6094 N = N->getOperand(0);
6095 if (N->getOpcode() == ISD::SPLAT_VECTOR)
6096 if (auto *Op = dyn_cast<ConstantSDNode>(N->getOperand(0)))
6097 return Op->getZExtValue() == 0;
6099}
6100
6101// Return the index of the zero/undef vector, or UINT32_MAX if not found.
6102static uint32_t findZeroVectorIdx(SDValue *Ops, unsigned Num) {
6103 for (unsigned I = 0; I < Num ; I++)
6104 if (isZeroVector(Ops[I]))
6105 return I;
6106 return UINT32_MAX;
6107}
6108
6109// Bytes is a VPERM-like permute vector, except that -1 is used for
6110// undefined bytes. Implement it on operands Ops[0] and Ops[1] using
6111// VSLDB or VPERM.
6113 SDValue *Ops,
6114 const SmallVectorImpl<int> &Bytes) {
6115 for (unsigned I = 0; I < 2; ++I)
6116 Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]);
6117
6118 // First see whether VSLDB can be used.
6119 unsigned StartIndex, OpNo0, OpNo1;
6120 if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1))
6121 return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0],
6122 Ops[OpNo1],
6123 DAG.getTargetConstant(StartIndex, DL, MVT::i32));
6124
6125 // Fall back on VPERM. Construct an SDNode for the permute vector. Try to
6126 // eliminate a zero vector by reusing any zero index in the permute vector.
6127 unsigned ZeroVecIdx = findZeroVectorIdx(&Ops[0], 2);
6128 if (ZeroVecIdx != UINT32_MAX) {
6129 bool MaskFirst = true;
6130 int ZeroIdx = -1;
6131 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
6132 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
6133 unsigned Byte = unsigned(Bytes[I]) % SystemZ::VectorBytes;
6134 if (OpNo == ZeroVecIdx && I == 0) {
6135 // If the first byte is zero, use mask as first operand.
6136 ZeroIdx = 0;
6137 break;
6138 }
6139 if (OpNo != ZeroVecIdx && Byte == 0) {
6140 // If mask contains a zero, use it by placing that vector first.
6141 ZeroIdx = I + SystemZ::VectorBytes;
6142 MaskFirst = false;
6143 break;
6144 }
6145 }
6146 if (ZeroIdx != -1) {
6147 SDValue IndexNodes[SystemZ::VectorBytes];
6148 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
6149 if (Bytes[I] >= 0) {
6150 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
6151 unsigned Byte = unsigned(Bytes[I]) % SystemZ::VectorBytes;
6152 if (OpNo == ZeroVecIdx)
6153 IndexNodes[I] = DAG.getConstant(ZeroIdx, DL, MVT::i32);
6154 else {
6155 unsigned BIdx = MaskFirst ? Byte + SystemZ::VectorBytes : Byte;
6156 IndexNodes[I] = DAG.getConstant(BIdx, DL, MVT::i32);
6157 }
6158 } else
6159 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
6160 }
6161 SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
6162 SDValue Src = ZeroVecIdx == 0 ? Ops[1] : Ops[0];
6163 if (MaskFirst)
6164 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Mask, Src,
6165 Mask);
6166 else
6167 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Src, Mask,
6168 Mask);
6169 }
6170 }
6171
6172 SDValue IndexNodes[SystemZ::VectorBytes];
6173 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
6174 if (Bytes[I] >= 0)
6175 IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32);
6176 else
6177 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
6178 SDValue Op2 = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
6179 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0],
6180 (!Ops[1].isUndef() ? Ops[1] : Ops[0]), Op2);
6181}
6182
6183namespace {
6184// Describes a general N-operand vector shuffle.
6185struct GeneralShuffle {
6186 GeneralShuffle(EVT vt)
6187 : VT(vt), UnpackFromEltSize(UINT_MAX), UnpackLow(false) {}
6188 void addUndef();
6189 bool add(SDValue, unsigned);
6190 SDValue getNode(SelectionDAG &, const SDLoc &);
6191 void tryPrepareForUnpack();
6192 bool unpackWasPrepared() { return UnpackFromEltSize <= 4; }
6193 SDValue insertUnpackIfPrepared(SelectionDAG &DAG, const SDLoc &DL, SDValue Op);
6194
6195 // The operands of the shuffle.
6197
6198 // Index I is -1 if byte I of the result is undefined. Otherwise the
6199 // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand
6200 // Bytes[I] / SystemZ::VectorBytes.
6202
6203 // The type of the shuffle result.
6204 EVT VT;
6205
6206 // Holds a value of 1, 2 or 4 if a final unpack has been prepared for.
6207 unsigned UnpackFromEltSize;
6208 // True if the final unpack uses the low half.
6209 bool UnpackLow;
6210};
6211} // namespace
6212
6213// Add an extra undefined element to the shuffle.
6214void GeneralShuffle::addUndef() {
6215 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
6216 for (unsigned I = 0; I < BytesPerElement; ++I)
6217 Bytes.push_back(-1);
6218}
6219
6220// Add an extra element to the shuffle, taking it from element Elem of Op.
6221// A null Op indicates a vector input whose value will be calculated later;
6222// there is at most one such input per shuffle and it always has the same
6223// type as the result. Aborts and returns false if the source vector elements
6224// of an EXTRACT_VECTOR_ELT are smaller than the destination elements. Per
6225// LLVM they become implicitly extended, but this is rare and not optimized.
6226bool GeneralShuffle::add(SDValue Op, unsigned Elem) {
6227 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
6228
6229 // The source vector can have wider elements than the result,
6230 // either through an explicit TRUNCATE or because of type legalization.
6231 // We want the least significant part.
6232 EVT FromVT = Op.getNode() ? Op.getValueType() : VT;
6233 unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize();
6234
6235 // Return false if the source elements are smaller than their destination
6236 // elements.
6237 if (FromBytesPerElement < BytesPerElement)
6238 return false;
6239
6240 unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes +
6241 (FromBytesPerElement - BytesPerElement));
6242
6243 // Look through things like shuffles and bitcasts.
6244 while (Op.getNode()) {
6245 if (Op.getOpcode() == ISD::BITCAST)
6246 Op = Op.getOperand(0);
6247 else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) {
6248 // See whether the bytes we need come from a contiguous part of one
6249 // operand.
6251 if (!getVPermMask(Op, OpBytes))
6252 break;
6253 int NewByte;
6254 if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte))
6255 break;
6256 if (NewByte < 0) {
6257 addUndef();
6258 return true;
6259 }
6260 Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes);
6261 Byte = unsigned(NewByte) % SystemZ::VectorBytes;
6262 } else if (Op.isUndef()) {
6263 addUndef();
6264 return true;
6265 } else
6266 break;
6267 }
6268
6269 // Make sure that the source of the extraction is in Ops.
6270 unsigned OpNo = 0;
6271 for (; OpNo < Ops.size(); ++OpNo)
6272 if (Ops[OpNo] == Op)
6273 break;
6274 if (OpNo == Ops.size())
6275 Ops.push_back(Op);
6276
6277 // Add the element to Bytes.
6278 unsigned Base = OpNo * SystemZ::VectorBytes + Byte;
6279 for (unsigned I = 0; I < BytesPerElement; ++I)
6280 Bytes.push_back(Base + I);
6281
6282 return true;
6283}
6284
6285// Return SDNodes for the completed shuffle.
6286SDValue GeneralShuffle::getNode(SelectionDAG &DAG, const SDLoc &DL) {
6287 assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector");
6288
6289 if (Ops.size() == 0)
6290 return DAG.getUNDEF(VT);
6291
6292 // Use a single unpack if possible as the last operation.
6293 tryPrepareForUnpack();
6294
6295 // Make sure that there are at least two shuffle operands.
6296 if (Ops.size() == 1)
6297 Ops.push_back(DAG.getUNDEF(MVT::v16i8));
6298
6299 // Create a tree of shuffles, deferring root node until after the loop.
6300 // Try to redistribute the undefined elements of non-root nodes so that
6301 // the non-root shuffles match something like a pack or merge, then adjust
6302 // the parent node's permute vector to compensate for the new order.
6303 // Among other things, this copes with vectors like <2 x i16> that were
6304 // padded with undefined elements during type legalization.
6305 //
6306 // In the best case this redistribution will lead to the whole tree
6307 // using packs and merges. It should rarely be a loss in other cases.
6308 unsigned Stride = 1;
6309 for (; Stride * 2 < Ops.size(); Stride *= 2) {
6310 for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) {
6311 SDValue SubOps[] = { Ops[I], Ops[I + Stride] };
6312
6313 // Create a mask for just these two operands.
6315 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
6316 unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes;
6317 unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes;
6318 if (OpNo == I)
6319 NewBytes[J] = Byte;
6320 else if (OpNo == I + Stride)
6321 NewBytes[J] = SystemZ::VectorBytes + Byte;
6322 else
6323 NewBytes[J] = -1;
6324 }
6325 // See if it would be better to reorganize NewMask to avoid using VPERM.
6327 if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) {
6328 Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]);
6329 // Applying NewBytesMap to Ops[I] gets back to NewBytes.
6330 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
6331 if (NewBytes[J] >= 0) {
6332 assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
6333 "Invalid double permute");
6334 Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J];
6335 } else
6336 assert(NewBytesMap[J] < 0 && "Invalid double permute");
6337 }
6338 } else {
6339 // Just use NewBytes on the operands.
6340 Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes);
6341 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J)
6342 if (NewBytes[J] >= 0)
6343 Bytes[J] = I * SystemZ::VectorBytes + J;
6344 }
6345 }
6346 }
6347
6348 // Now we just have 2 inputs. Put the second operand in Ops[1].
6349 if (Stride > 1) {
6350 Ops[1] = Ops[Stride];
6351 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
6352 if (Bytes[I] >= int(SystemZ::VectorBytes))
6353 Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes;
6354 }
6355
6356 // Look for an instruction that can do the permute without resorting
6357 // to VPERM.
6358 unsigned OpNo0, OpNo1;
6359 SDValue Op;
6360 if (unpackWasPrepared() && Ops[1].isUndef())
6361 Op = Ops[0];
6362 else if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1))
6363 Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]);
6364 else
6365 Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes);
6366
6367 Op = insertUnpackIfPrepared(DAG, DL, Op);
6368
6369 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
6370}
6371
6372#ifndef NDEBUG
6373static void dumpBytes(const SmallVectorImpl<int> &Bytes, std::string Msg) {
6374 dbgs() << Msg.c_str() << " { ";
6375 for (unsigned I = 0; I < Bytes.size(); I++)
6376 dbgs() << Bytes[I] << " ";
6377 dbgs() << "}\n";
6378}
6379#endif
6380
6381// If the Bytes vector matches an unpack operation, prepare to do the unpack
6382// after all else by removing the zero vector and the effect of the unpack on
6383// Bytes.
6384void GeneralShuffle::tryPrepareForUnpack() {
6385 uint32_t ZeroVecOpNo = findZeroVectorIdx(&Ops[0], Ops.size());
6386 if (ZeroVecOpNo == UINT32_MAX || Ops.size() == 1)
6387 return;
6388
6389 // Only do this if removing the zero vector reduces the depth, otherwise
6390 // the critical path will increase with the final unpack.
6391 if (Ops.size() > 2 &&
6392 Log2_32_Ceil(Ops.size()) == Log2_32_Ceil(Ops.size() - 1))
6393 return;
6394
6395 // Find an unpack that would allow removing the zero vector from Ops.
6396 UnpackFromEltSize = 1;
6397 for (; UnpackFromEltSize <= 4; UnpackFromEltSize *= 2) {
6398 bool MatchUnpack = true;
6400 for (unsigned Elt = 0; Elt < SystemZ::VectorBytes; Elt++) {
6401 unsigned ToEltSize = UnpackFromEltSize * 2;
6402 bool IsZextByte = (Elt % ToEltSize) < UnpackFromEltSize;
6403 if (!IsZextByte)
6404 SrcBytes.push_back(Bytes[Elt]);
6405 if (Bytes[Elt] != -1) {
6406 unsigned OpNo = unsigned(Bytes[Elt]) / SystemZ::VectorBytes;
6407 if (IsZextByte != (OpNo == ZeroVecOpNo)) {
6408 MatchUnpack = false;
6409 break;
6410 }
6411 }
6412 }
6413 if (MatchUnpack) {
6414 if (Ops.size() == 2) {
6415 // Don't use unpack if a single source operand needs rearrangement.
6416 bool CanUseUnpackLow = true, CanUseUnpackHigh = true;
6417 for (unsigned i = 0; i < SystemZ::VectorBytes / 2; i++) {
6418 if (SrcBytes[i] == -1)
6419 continue;
6420 if (SrcBytes[i] % 16 != int(i))
6421 CanUseUnpackHigh = false;
6422 if (SrcBytes[i] % 16 != int(i + SystemZ::VectorBytes / 2))
6423 CanUseUnpackLow = false;
6424 if (!CanUseUnpackLow && !CanUseUnpackHigh) {
6425 UnpackFromEltSize = UINT_MAX;
6426 return;
6427 }
6428 }
6429 if (!CanUseUnpackHigh)
6430 UnpackLow = true;
6431 }
6432 break;
6433 }
6434 }
6435 if (UnpackFromEltSize > 4)
6436 return;
6437
6438 LLVM_DEBUG(dbgs() << "Preparing for final unpack of element size "
6439 << UnpackFromEltSize << ". Zero vector is Op#" << ZeroVecOpNo
6440 << ".\n";
6441 dumpBytes(Bytes, "Original Bytes vector:"););
6442
6443 // Apply the unpack in reverse to the Bytes array.
6444 unsigned B = 0;
6445 if (UnpackLow) {
6446 while (B < SystemZ::VectorBytes / 2)
6447 Bytes[B++] = -1;
6448 }
6449 for (unsigned Elt = 0; Elt < SystemZ::VectorBytes;) {
6450 Elt += UnpackFromEltSize;
6451 for (unsigned i = 0; i < UnpackFromEltSize; i++, Elt++, B++)
6452 Bytes[B] = Bytes[Elt];
6453 }
6454 if (!UnpackLow) {
6455 while (B < SystemZ::VectorBytes)
6456 Bytes[B++] = -1;
6457 }
6458
6459 // Remove the zero vector from Ops
6460 Ops.erase(&Ops[ZeroVecOpNo]);
6461 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
6462 if (Bytes[I] >= 0) {
6463 unsigned OpNo = unsigned(Bytes[I]) / SystemZ::VectorBytes;
6464 if (OpNo > ZeroVecOpNo)
6465 Bytes[I] -= SystemZ::VectorBytes;
6466 }
6467
6468 LLVM_DEBUG(dumpBytes(Bytes, "Resulting Bytes vector, zero vector removed:");
6469 dbgs() << "\n";);
6470}
6471
6472SDValue GeneralShuffle::insertUnpackIfPrepared(SelectionDAG &DAG,
6473 const SDLoc &DL,
6474 SDValue Op) {
6475 if (!unpackWasPrepared())
6476 return Op;
6477 unsigned InBits = UnpackFromEltSize * 8;
6478 EVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBits),
6479 SystemZ::VectorBits / InBits);
6480 SDValue PackedOp = DAG.getNode(ISD::BITCAST, DL, InVT, Op);
6481 unsigned OutBits = InBits * 2;
6482 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(OutBits),
6483 SystemZ::VectorBits / OutBits);
6484 return DAG.getNode(UnpackLow ? SystemZISD::UNPACKL_LOW
6485 : SystemZISD::UNPACKL_HIGH,
6486 DL, OutVT, PackedOp);
6487}
6488
6489// Return true if the given BUILD_VECTOR is a scalar-to-vector conversion.
6491 for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I)
6492 if (!Op.getOperand(I).isUndef())
6493 return false;
6494 return true;
6495}
6496
6497// Return a vector of type VT that contains Value in the first element.
6498// The other elements don't matter.
6500 SDValue Value) {
6501 // If we have a constant, replicate it to all elements and let the
6502 // BUILD_VECTOR lowering take care of it.
6503 if (Value.getOpcode() == ISD::Constant ||
6504 Value.getOpcode() == ISD::ConstantFP) {
6506 return DAG.getBuildVector(VT, DL, Ops);
6507 }
6508 if (Value.isUndef())
6509 return DAG.getUNDEF(VT);
6510 return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
6511}
6512
6513// Return a vector of type VT in which Op0 is in element 0 and Op1 is in
6514// element 1. Used for cases in which replication is cheap.
6516 SDValue Op0, SDValue Op1) {
6517 if (Op0.isUndef()) {
6518 if (Op1.isUndef())
6519 return DAG.getUNDEF(VT);
6520 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1);
6521 }
6522 if (Op1.isUndef())
6523 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0);
6524 return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT,
6525 buildScalarToVector(DAG, DL, VT, Op0),
6526 buildScalarToVector(DAG, DL, VT, Op1));
6527}
6528
6529// Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64
6530// vector for them.
6532 SDValue Op1) {
6533 if (Op0.isUndef() && Op1.isUndef())
6534 return DAG.getUNDEF(MVT::v2i64);
6535 // If one of the two inputs is undefined then replicate the other one,
6536 // in order to avoid using another register unnecessarily.
6537 if (Op0.isUndef())
6538 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
6539 else if (Op1.isUndef())
6540 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
6541 else {
6542 Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
6543 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
6544 }
6545 return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1);
6546}
6547
6548// If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually
6549// better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for
6550// the non-EXTRACT_VECTOR_ELT elements. See if the given BUILD_VECTOR
6551// would benefit from this representation and return it if so.
6553 BuildVectorSDNode *BVN) {
6554 EVT VT = BVN->getValueType(0);
6555 unsigned NumElements = VT.getVectorNumElements();
6556
6557 // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation
6558 // on byte vectors. If there are non-EXTRACT_VECTOR_ELT elements that still
6559 // need a BUILD_VECTOR, add an additional placeholder operand for that
6560 // BUILD_VECTOR and store its operands in ResidueOps.
6561 GeneralShuffle GS(VT);
6563 bool FoundOne = false;
6564 for (unsigned I = 0; I < NumElements; ++I) {
6565 SDValue Op = BVN->getOperand(I);
6566 if (Op.getOpcode() == ISD::TRUNCATE)
6567 Op = Op.getOperand(0);
6568 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6569 Op.getOperand(1).getOpcode() == ISD::Constant) {
6570 unsigned Elem = Op.getConstantOperandVal(1);
6571 if (!GS.add(Op.getOperand(0), Elem))
6572 return SDValue();
6573 FoundOne = true;
6574 } else if (Op.isUndef()) {
6575 GS.addUndef();
6576 } else {
6577 if (!GS.add(SDValue(), ResidueOps.size()))
6578 return SDValue();
6579 ResidueOps.push_back(BVN->getOperand(I));
6580 }
6581 }
6582
6583 // Nothing to do if there are no EXTRACT_VECTOR_ELTs.
6584 if (!FoundOne)
6585 return SDValue();
6586
6587 // Create the BUILD_VECTOR for the remaining elements, if any.
6588 if (!ResidueOps.empty()) {
6589 while (ResidueOps.size() < NumElements)
6590 ResidueOps.push_back(DAG.getUNDEF(ResidueOps[0].getValueType()));
6591 for (auto &Op : GS.Ops) {
6592 if (!Op.getNode()) {
6593 Op = DAG.getBuildVector(VT, SDLoc(BVN), ResidueOps);
6594 break;
6595 }
6596 }
6597 }
6598 return GS.getNode(DAG, SDLoc(BVN));
6599}
6600
6601bool SystemZTargetLowering::isVectorElementLoad(SDValue Op) const {
6602 if (Op.getOpcode() == ISD::LOAD && cast<LoadSDNode>(Op)->isUnindexed())
6603 return true;
6604 if (auto *AL = dyn_cast<AtomicSDNode>(Op))
6605 if (AL->getOpcode() == ISD::ATOMIC_LOAD)
6606 return true;
6607 if (Subtarget.hasVectorEnhancements2() && Op.getOpcode() == SystemZISD::LRV)
6608 return true;
6609 return false;
6610}
6611
6613 unsigned MergedBits, EVT VT, SDValue Op0,
6614 SDValue Op1) {
6615 MVT IntVecVT = MVT::getVectorVT(MVT::getIntegerVT(MergedBits),
6616 SystemZ::VectorBits / MergedBits);
6617 assert(VT.getSizeInBits() == 128 && IntVecVT.getSizeInBits() == 128 &&
6618 "Handling full vectors only.");
6619 Op0 = DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0);
6620 Op1 = DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op1);
6621 SDValue Op = DAG.getNode(SystemZISD::MERGE_HIGH, DL, IntVecVT, Op0, Op1);
6622 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
6623}
6624
6626 EVT VT, SmallVectorImpl<SDValue> &Elems,
6627 unsigned Pos) {
6628 SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[Pos + 0], Elems[Pos + 1]);
6629 SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[Pos + 2], Elems[Pos + 3]);
6630 // Avoid unnecessary undefs by reusing the other operand.
6631 if (Op01.isUndef()) {
6632 if (Op23.isUndef())
6633 return Op01;
6634 Op01 = Op23;
6635 } else if (Op23.isUndef())
6636 Op23 = Op01;
6637 // Merging identical replications is a no-op.
6638 if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23)
6639 return Op01;
6640 unsigned MergedBits = VT.getSimpleVT().getScalarSizeInBits() * 2;
6641 return mergeHighParts(DAG, DL, MergedBits, VT, Op01, Op23);
6642}
6643
6644// Combine GPR scalar values Elems into a vector of type VT.
6645SDValue
6646SystemZTargetLowering::buildVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
6647 SmallVectorImpl<SDValue> &Elems) const {
6648 // See whether there is a single replicated value.
6650 unsigned int NumElements = Elems.size();
6651 unsigned int Count = 0;
6652 for (auto Elem : Elems) {
6653 if (!Elem.isUndef()) {
6654 if (!Single.getNode())
6655 Single = Elem;
6656 else if (Elem != Single) {
6657 Single = SDValue();
6658 break;
6659 }
6660 Count += 1;
6661 }
6662 }
6663 // There are three cases here:
6664 //
6665 // - if the only defined element is a loaded one, the best sequence
6666 // is a replicating load.
6667 //
6668 // - otherwise, if the only defined element is an i64 value, we will
6669 // end up with the same VLVGP sequence regardless of whether we short-cut
6670 // for replication or fall through to the later code.
6671 //
6672 // - otherwise, if the only defined element is an i32 or smaller value,
6673 // we would need 2 instructions to replicate it: VLVGP followed by VREPx.
6674 // This is only a win if the single defined element is used more than once.
6675 // In other cases we're better off using a single VLVGx.
6676 if (Single.getNode() && (Count > 1 || isVectorElementLoad(Single)))
6677 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single);
6678
6679 // If all elements are loads, use VLREP/VLEs (below).
6680 bool AllLoads = true;
6681 for (auto Elem : Elems)
6682 if (!isVectorElementLoad(Elem)) {
6683 AllLoads = false;
6684 break;
6685 }
6686
6687 // The best way of building a v2i64 from two i64s is to use VLVGP.
6688 if (VT == MVT::v2i64 && !AllLoads)
6689 return joinDwords(DAG, DL, Elems[0], Elems[1]);
6690
6691 // Use a 64-bit merge high to combine two doubles.
6692 if (VT == MVT::v2f64 && !AllLoads)
6693 return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
6694
6695 // Build v4f32 values directly from the FPRs:
6696 //
6697 // <Axxx> <Bxxx> <Cxxxx> <Dxxx>
6698 // V V VMRHF
6699 // <ABxx> <CDxx>
6700 // V VMRHG
6701 // <ABCD>
6702 if (VT == MVT::v4f32 && !AllLoads)
6703 return buildFPVecFromScalars4(DAG, DL, VT, Elems, 0);
6704
6705 // Same for v8f16.
6706 if (VT == MVT::v8f16 && !AllLoads) {
6707 SDValue Op0123 = buildFPVecFromScalars4(DAG, DL, VT, Elems, 0);
6708 SDValue Op4567 = buildFPVecFromScalars4(DAG, DL, VT, Elems, 4);
6709 // Avoid unnecessary undefs by reusing the other operand.
6710 if (Op0123.isUndef())
6711 Op0123 = Op4567;
6712 else if (Op4567.isUndef())
6713 Op4567 = Op0123;
6714 // Merging identical replications is a no-op.
6715 if (Op0123.getOpcode() == SystemZISD::REPLICATE && Op0123 == Op4567)
6716 return Op0123;
6717 return mergeHighParts(DAG, DL, 64, VT, Op0123, Op4567);
6718 }
6719
6720 // Collect the constant terms.
6723
6724 unsigned NumConstants = 0;
6725 for (unsigned I = 0; I < NumElements; ++I) {
6726 SDValue Elem = Elems[I];
6727 if (Elem.getOpcode() == ISD::Constant ||
6728 Elem.getOpcode() == ISD::ConstantFP) {
6729 NumConstants += 1;
6730 Constants[I] = Elem;
6731 Done[I] = true;
6732 }
6733 }
6734 // If there was at least one constant, fill in the other elements of
6735 // Constants with undefs to get a full vector constant and use that
6736 // as the starting point.
6738 SDValue ReplicatedVal;
6739 if (NumConstants > 0) {
6740 for (unsigned I = 0; I < NumElements; ++I)
6741 if (!Constants[I].getNode())
6742 Constants[I] = DAG.getUNDEF(Elems[I].getValueType());
6743 Result = DAG.getBuildVector(VT, DL, Constants);
6744 } else {
6745 // Otherwise try to use VLREP or VLVGP to start the sequence in order to
6746 // avoid a false dependency on any previous contents of the vector
6747 // register.
6748
6749 // Use a VLREP if at least one element is a load. Make sure to replicate
6750 // the load with the most elements having its value.
6751 std::map<const SDNode*, unsigned> UseCounts;
6752 SDNode *LoadMaxUses = nullptr;
6753 for (unsigned I = 0; I < NumElements; ++I)
6754 if (isVectorElementLoad(Elems[I])) {
6755 SDNode *Ld = Elems[I].getNode();
6756 unsigned Count = ++UseCounts[Ld];
6757 if (LoadMaxUses == nullptr || UseCounts[LoadMaxUses] < Count)
6758 LoadMaxUses = Ld;
6759 }
6760 if (LoadMaxUses != nullptr) {
6761 ReplicatedVal = SDValue(LoadMaxUses, 0);
6762 Result = DAG.getNode(SystemZISD::REPLICATE, DL, VT, ReplicatedVal);
6763 } else {
6764 // Try to use VLVGP.
6765 unsigned I1 = NumElements / 2 - 1;
6766 unsigned I2 = NumElements - 1;
6767 bool Def1 = !Elems[I1].isUndef();
6768 bool Def2 = !Elems[I2].isUndef();
6769 if (Def1 || Def2) {
6770 SDValue Elem1 = Elems[Def1 ? I1 : I2];
6771 SDValue Elem2 = Elems[Def2 ? I2 : I1];
6772 Result = DAG.getNode(ISD::BITCAST, DL, VT,
6773 joinDwords(DAG, DL, Elem1, Elem2));
6774 Done[I1] = true;
6775 Done[I2] = true;
6776 } else
6777 Result = DAG.getUNDEF(VT);
6778 }
6779 }
6780
6781 // Use VLVGx to insert the other elements.
6782 for (unsigned I = 0; I < NumElements; ++I)
6783 if (!Done[I] && !Elems[I].isUndef() && Elems[I] != ReplicatedVal)
6784 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I],
6785 DAG.getConstant(I, DL, MVT::i32));
6786 return Result;
6787}
6788
6789SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op,
6790 SelectionDAG &DAG) const {
6791 auto *BVN = cast<BuildVectorSDNode>(Op.getNode());
6792 SDLoc DL(Op);
6793 EVT VT = Op.getValueType();
6794
6795 if (BVN->isConstant()) {
6796 if (SystemZVectorConstantInfo(BVN).isVectorConstantLegal(Subtarget))
6797 return Op;
6798
6799 // Fall back to loading it from memory.
6800 return SDValue();
6801 }
6802
6803 // See if we should use shuffles to construct the vector from other vectors.
6804 if (SDValue Res = tryBuildVectorShuffle(DAG, BVN))
6805 return Res;
6806
6807 // Detect SCALAR_TO_VECTOR conversions.
6809 return buildScalarToVector(DAG, DL, VT, Op.getOperand(0));
6810
6811 // Otherwise use buildVector to build the vector up from GPRs.
6812 unsigned NumElements = Op.getNumOperands();
6814 for (unsigned I = 0; I < NumElements; ++I)
6815 Ops[I] = Op.getOperand(I);
6816 return buildVector(DAG, DL, VT, Ops);
6817}
6818
6819SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
6820 SelectionDAG &DAG) const {
6821 auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode());
6822 SDLoc DL(Op);
6823 EVT VT = Op.getValueType();
6824 unsigned NumElements = VT.getVectorNumElements();
6825
6826 if (VSN->isSplat()) {
6827 SDValue Op0 = Op.getOperand(0);
6828 unsigned Index = VSN->getSplatIndex();
6829 assert(Index < VT.getVectorNumElements() &&
6830 "Splat index should be defined and in first operand");
6831 // See whether the value we're splatting is directly available as a scalar.
6832 if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
6834 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index));
6835 // Otherwise keep it as a vector-to-vector operation.
6836 return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0),
6837 DAG.getTargetConstant(Index, DL, MVT::i32));
6838 }
6839
6840 GeneralShuffle GS(VT);
6841 for (unsigned I = 0; I < NumElements; ++I) {
6842 int Elt = VSN->getMaskElt(I);
6843 if (Elt < 0)
6844 GS.addUndef();
6845 else if (!GS.add(Op.getOperand(unsigned(Elt) / NumElements),
6846 unsigned(Elt) % NumElements))
6847 return SDValue();
6848 }
6849 return GS.getNode(DAG, SDLoc(VSN));
6850}
6851
6852SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
6853 SelectionDAG &DAG) const {
6854 SDLoc DL(Op);
6855 // Just insert the scalar into element 0 of an undefined vector.
6856 return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL,
6857 Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
6858 Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32));
6859}
6860
6861// Shift the lower 2 bytes of Op to the left in order to insert into the
6862// upper 2 bytes of the FP register.
6864 assert(Op.getSimpleValueType() == MVT::i64 &&
6865 "Expexted to convert i64 to f16.");
6866 SDLoc DL(Op);
6867 SDValue Shft = DAG.getNode(ISD::SHL, DL, MVT::i64, Op,
6868 DAG.getConstant(48, DL, MVT::i64));
6869 SDValue BCast = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Shft);
6870 SDValue F16Val =
6871 DAG.getTargetExtractSubreg(SystemZ::subreg_h16, DL, MVT::f16, BCast);
6872 return F16Val;
6873}
6874
6875// Extract Op into GPR and shift the 2 f16 bytes to the right.
6877 assert(Op.getSimpleValueType() == MVT::f16 &&
6878 "Expected to convert f16 to i64.");
6879 SDNode *U32 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
6880 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h16, DL, MVT::f64,
6881 SDValue(U32, 0), Op);
6882 SDValue BCast = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
6883 SDValue Shft = DAG.getNode(ISD::SRL, DL, MVT::i64, BCast,
6884 DAG.getConstant(48, DL, MVT::i32));
6885 return Shft;
6886}
6887
6889 auto *CIdx = dyn_cast<ConstantSDNode>(Idx);
6890 return CIdx && CIdx->getZExtValue() < VecVT.getVectorNumElements();
6891}
6892
6893SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
6894 SelectionDAG &DAG) const {
6895 // Handle insertions of floating-point values.
6896 SDLoc DL(Op);
6897 SDValue Op0 = Op.getOperand(0);
6898 SDValue Op1 = Op.getOperand(1);
6899 SDValue Op2 = Op.getOperand(2);
6900 EVT VT = Op.getValueType();
6901
6902 // A constant index selects a GR128 subregister.
6903 if (!Subtarget.hasVector())
6904 return isInBoundsConstantVectorIndex(VT, Op2) ? Op : SDValue();
6905
6906 // Insertions into constant indices of a v2f64 can be done using VPDI.
6907 // However, if the inserted value is a bitcast or a constant then it's
6908 // better to use GPRs, as below.
6909 if (VT == MVT::v2f64 && Op1.getOpcode() != ISD::BITCAST &&
6910 Op1.getOpcode() != ISD::ConstantFP &&
6912 return Op;
6913
6914 // Otherwise bitcast to the equivalent integer form and insert via a GPR.
6915 MVT IntVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
6916 MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements());
6917 SDValue IntOp1 =
6918 VT == MVT::v8f16
6919 ? DAG.getZExtOrTrunc(convertFromF16(Op1, DL, DAG), DL, MVT::i32)
6920 : DAG.getNode(ISD::BITCAST, DL, IntVT, Op1);
6921 SDValue Res =
6922 DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT,
6923 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), IntOp1, Op2);
6924 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
6925}
6926
6927SDValue
6928SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
6929 SelectionDAG &DAG) const {
6930 // Handle extractions of floating-point values.
6931 SDLoc DL(Op);
6932 SDValue Op0 = Op.getOperand(0);
6933 SDValue Op1 = Op.getOperand(1);
6934 EVT VT = Op.getValueType();
6935 EVT VecVT = Op0.getValueType();
6936
6937 // Extractions of constant indices can be done directly.
6938 if (isInBoundsConstantVectorIndex(VecVT, Op1))
6939 return Op;
6940
6941 if (!Subtarget.hasVector())
6942 return SDValue();
6943
6944 // Otherwise bitcast to the equivalent integer form and extract via a GPR.
6945 MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
6946 MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements());
6947 MVT ExtrVT = IntVT == MVT::i16 ? MVT::i32 : IntVT;
6948 SDValue Extr = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrVT,
6949 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1);
6950 if (VT == MVT::f16)
6951 return convertToF16(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Extr), DAG);
6952 return DAG.getNode(ISD::BITCAST, DL, VT, Extr);
6953}
6954
6955SDValue SystemZTargetLowering::
6956lowerSIGN_EXTEND_VECTOR_INREG(SDValue Op, SelectionDAG &DAG) const {
6957 SDValue PackedOp = Op.getOperand(0);
6958 EVT OutVT = Op.getValueType();
6959 EVT InVT = PackedOp.getValueType();
6960 unsigned ToBits = OutVT.getScalarSizeInBits();
6961 unsigned FromBits = InVT.getScalarSizeInBits();
6962 unsigned StartOffset = 0;
6963
6964 // If the input is a VECTOR_SHUFFLE, there are a number of important
6965 // cases where we can directly implement the sign-extension of the
6966 // original input lanes of the shuffle.
6967 if (PackedOp.getOpcode() == ISD::VECTOR_SHUFFLE) {
6968 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(PackedOp.getNode());
6969 ArrayRef<int> ShuffleMask = SVN->getMask();
6970 int OutNumElts = OutVT.getVectorNumElements();
6971
6972 // Recognize the special case where the sign-extension can be done
6973 // by the VSEG instruction. Handled via the default expander.
6974 if (ToBits == 64 && OutNumElts == 2) {
6975 int NumElem = ToBits / FromBits;
6976 if (ShuffleMask[0] == NumElem - 1 && ShuffleMask[1] == 2 * NumElem - 1)
6977 return SDValue();
6978 }
6979
6980 // Recognize the special case where we can fold the shuffle by
6981 // replacing some of the UNPACK_HIGH with UNPACK_LOW.
6982 int StartOffsetCandidate = -1;
6983 for (int Elt = 0; Elt < OutNumElts; Elt++) {
6984 if (ShuffleMask[Elt] == -1)
6985 continue;
6986 if (ShuffleMask[Elt] % OutNumElts == Elt) {
6987 if (StartOffsetCandidate == -1)
6988 StartOffsetCandidate = ShuffleMask[Elt] - Elt;
6989 if (StartOffsetCandidate == ShuffleMask[Elt] - Elt)
6990 continue;
6991 }
6992 StartOffsetCandidate = -1;
6993 break;
6994 }
6995 if (StartOffsetCandidate != -1) {
6996 // The mask indexes the concatenation of both shuffle operands: an offset
6997 // past the first operand's lanes selects lanes of the second.
6998 unsigned InNumElts = InVT.getVectorNumElements();
6999 unsigned Offset = StartOffsetCandidate;
7000 unsigned OpNo = Offset >= InNumElts ? 1 : 0;
7001 StartOffset = Offset - OpNo * InNumElts;
7002 PackedOp = PackedOp.getOperand(OpNo);
7003 }
7004 }
7005
7006 do {
7007 FromBits *= 2;
7008 unsigned OutNumElts = SystemZ::VectorBits / FromBits;
7009 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(FromBits), OutNumElts);
7010 unsigned Opcode = SystemZISD::UNPACK_HIGH;
7011 if (StartOffset >= OutNumElts) {
7012 Opcode = SystemZISD::UNPACK_LOW;
7013 StartOffset -= OutNumElts;
7014 }
7015 PackedOp = DAG.getNode(Opcode, SDLoc(PackedOp), OutVT, PackedOp);
7016 } while (FromBits != ToBits);
7017 return PackedOp;
7018}
7019
7020// Lower a ZERO_EXTEND_VECTOR_INREG to a vector shuffle with a zero vector.
7021SDValue SystemZTargetLowering::
7022lowerZERO_EXTEND_VECTOR_INREG(SDValue Op, SelectionDAG &DAG) const {
7023 SDValue PackedOp = Op.getOperand(0);
7024 SDLoc DL(Op);
7025 EVT OutVT = Op.getValueType();
7026 EVT InVT = PackedOp.getValueType();
7027 unsigned InNumElts = InVT.getVectorNumElements();
7028 unsigned OutNumElts = OutVT.getVectorNumElements();
7029 unsigned NumInPerOut = InNumElts / OutNumElts;
7030
7031 SDValue ZeroVec =
7032 DAG.getSplatVector(InVT, DL, DAG.getConstant(0, DL, InVT.getScalarType()));
7033
7034 SmallVector<int, 16> Mask(InNumElts);
7035 unsigned ZeroVecElt = InNumElts;
7036 for (unsigned PackedElt = 0; PackedElt < OutNumElts; PackedElt++) {
7037 unsigned MaskElt = PackedElt * NumInPerOut;
7038 unsigned End = MaskElt + NumInPerOut - 1;
7039 for (; MaskElt < End; MaskElt++)
7040 Mask[MaskElt] = ZeroVecElt++;
7041 Mask[MaskElt] = PackedElt;
7042 }
7043 SDValue Shuf = DAG.getVectorShuffle(InVT, DL, PackedOp, ZeroVec, Mask);
7044 return DAG.getNode(ISD::BITCAST, DL, OutVT, Shuf);
7045}
7046
7047SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG,
7048 unsigned ByScalar) const {
7049 // Look for cases where a vector shift can use the *_BY_SCALAR form.
7050 SDValue Op0 = Op.getOperand(0);
7051 SDValue Op1 = Op.getOperand(1);
7052 SDLoc DL(Op);
7053 EVT VT = Op.getValueType();
7054 unsigned ElemBitSize = VT.getScalarSizeInBits();
7055
7056 // See whether the shift vector is a splat represented as BUILD_VECTOR.
7057 if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) {
7058 APInt SplatBits, SplatUndef;
7059 unsigned SplatBitSize;
7060 bool HasAnyUndefs;
7061 // Check for constant splats. Use ElemBitSize as the minimum element
7062 // width and reject splats that need wider elements.
7063 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
7064 ElemBitSize, true) &&
7065 SplatBitSize == ElemBitSize) {
7066 SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff,
7067 DL, MVT::i32);
7068 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
7069 }
7070 // Check for variable splats.
7071 BitVector UndefElements;
7072 SDValue Splat = BVN->getSplatValue(&UndefElements);
7073 if (Splat) {
7074 // Since i32 is the smallest legal type, we either need a no-op
7075 // or a truncation.
7076 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat);
7077 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
7078 }
7079 }
7080
7081 // See whether the shift vector is a splat represented as SHUFFLE_VECTOR,
7082 // and the shift amount is directly available in a GPR.
7083 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) {
7084 if (VSN->isSplat()) {
7085 SDValue VSNOp0 = VSN->getOperand(0);
7086 unsigned Index = VSN->getSplatIndex();
7087 assert(Index < VT.getVectorNumElements() &&
7088 "Splat index should be defined and in first operand");
7089 if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
7090 VSNOp0.getOpcode() == ISD::BUILD_VECTOR) {
7091 // Since i32 is the smallest legal type, we either need a no-op
7092 // or a truncation.
7093 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
7094 VSNOp0.getOperand(Index));
7095 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
7096 }
7097 }
7098 }
7099
7100 // Otherwise just treat the current form as legal.
7101 return Op;
7102}
7103
7104SDValue SystemZTargetLowering::lowerFSHL(SDValue Op, SelectionDAG &DAG) const {
7105 SDLoc DL(Op);
7106
7107 // i128 FSHL with a constant amount that is a multiple of 8 can be
7108 // implemented via VECTOR_SHUFFLE. If we have the vector-enhancements-2
7109 // facility, FSHL with a constant amount less than 8 can be implemented
7110 // via SHL_DOUBLE_BIT, and FSHL with other constant amounts by a
7111 // combination of the two.
7112 if (auto *ShiftAmtNode = dyn_cast<ConstantSDNode>(Op.getOperand(2))) {
7113 uint64_t ShiftAmt = ShiftAmtNode->getZExtValue() & 127;
7114 if ((ShiftAmt & 7) == 0 || Subtarget.hasVectorEnhancements2()) {
7115 SDValue Op0 = DAG.getBitcast(MVT::v16i8, Op.getOperand(0));
7116 SDValue Op1 = DAG.getBitcast(MVT::v16i8, Op.getOperand(1));
7117 if (ShiftAmt > 120) {
7118 // For N in 121..128, fshl N == fshr (128 - N), and for 1 <= N < 8
7119 // SHR_DOUBLE_BIT emits fewer instructions.
7120 SDValue Val =
7121 DAG.getNode(SystemZISD::SHR_DOUBLE_BIT, DL, MVT::v16i8, Op0, Op1,
7122 DAG.getTargetConstant(128 - ShiftAmt, DL, MVT::i32));
7123 return DAG.getBitcast(MVT::i128, Val);
7124 }
7125 SmallVector<int, 16> Mask(16);
7126 for (unsigned Elt = 0; Elt < 16; Elt++)
7127 Mask[Elt] = (ShiftAmt >> 3) + Elt;
7128 SDValue Shuf1 = DAG.getVectorShuffle(MVT::v16i8, DL, Op0, Op1, Mask);
7129 if ((ShiftAmt & 7) == 0)
7130 return DAG.getBitcast(MVT::i128, Shuf1);
7131 SDValue Shuf2 = DAG.getVectorShuffle(MVT::v16i8, DL, Op1, Op1, Mask);
7132 SDValue Val =
7133 DAG.getNode(SystemZISD::SHL_DOUBLE_BIT, DL, MVT::v16i8, Shuf1, Shuf2,
7134 DAG.getTargetConstant(ShiftAmt & 7, DL, MVT::i32));
7135 return DAG.getBitcast(MVT::i128, Val);
7136 }
7137 }
7138
7139 return SDValue();
7140}
7141
7142SDValue SystemZTargetLowering::lowerFSHR(SDValue Op, SelectionDAG &DAG) const {
7143 SDLoc DL(Op);
7144
7145 // i128 FSHR with a constant amount that is a multiple of 8 can be
7146 // implemented via VECTOR_SHUFFLE. If we have the vector-enhancements-2
7147 // facility, FSHR with a constant amount less than 8 can be implemented
7148 // via SHR_DOUBLE_BIT, and FSHR with other constant amounts by a
7149 // combination of the two.
7150 if (auto *ShiftAmtNode = dyn_cast<ConstantSDNode>(Op.getOperand(2))) {
7151 uint64_t ShiftAmt = ShiftAmtNode->getZExtValue() & 127;
7152 if ((ShiftAmt & 7) == 0 || Subtarget.hasVectorEnhancements2()) {
7153 SDValue Op0 = DAG.getBitcast(MVT::v16i8, Op.getOperand(0));
7154 SDValue Op1 = DAG.getBitcast(MVT::v16i8, Op.getOperand(1));
7155 if (ShiftAmt > 120) {
7156 // For N in 121..128, fshr N == fshl (128 - N), and for 1 <= N < 8
7157 // SHL_DOUBLE_BIT emits fewer instructions.
7158 SDValue Val =
7159 DAG.getNode(SystemZISD::SHL_DOUBLE_BIT, DL, MVT::v16i8, Op0, Op1,
7160 DAG.getTargetConstant(128 - ShiftAmt, DL, MVT::i32));
7161 return DAG.getBitcast(MVT::i128, Val);
7162 }
7163 SmallVector<int, 16> Mask(16);
7164 for (unsigned Elt = 0; Elt < 16; Elt++)
7165 Mask[Elt] = 16 - (ShiftAmt >> 3) + Elt;
7166 SDValue Shuf1 = DAG.getVectorShuffle(MVT::v16i8, DL, Op0, Op1, Mask);
7167 if ((ShiftAmt & 7) == 0)
7168 return DAG.getBitcast(MVT::i128, Shuf1);
7169 SDValue Shuf2 = DAG.getVectorShuffle(MVT::v16i8, DL, Op0, Op0, Mask);
7170 SDValue Val =
7171 DAG.getNode(SystemZISD::SHR_DOUBLE_BIT, DL, MVT::v16i8, Shuf2, Shuf1,
7172 DAG.getTargetConstant(ShiftAmt & 7, DL, MVT::i32));
7173 return DAG.getBitcast(MVT::i128, Val);
7174 }
7175 }
7176
7177 return SDValue();
7178}
7179
7181 SDLoc DL(Op);
7182 SDValue Src = Op.getOperand(0);
7183 MVT DstVT = Op.getSimpleValueType();
7184
7186 unsigned SrcAS = N->getSrcAddressSpace();
7187
7188 assert(SrcAS != N->getDestAddressSpace() &&
7189 "addrspacecast must be between different address spaces");
7190
7191 // addrspacecast [0 <- 1] : Assinging a ptr32 value to a 64-bit pointer.
7192 // addrspacecast [1 <- 0] : Assigining a 64-bit pointer to a ptr32 value.
7193 if (SrcAS == SYSTEMZAS::PTR32 && DstVT == MVT::i64) {
7194 Op = DAG.getNode(ISD::AND, DL, MVT::i32, Src,
7195 DAG.getConstant(0x7fffffff, DL, MVT::i32));
7196 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, DstVT, Op);
7197 } else if (DstVT == MVT::i32) {
7198 Op = DAG.getNode(ISD::TRUNCATE, DL, DstVT, Src);
7199 Op = DAG.getNode(ISD::AND, DL, MVT::i32, Op,
7200 DAG.getConstant(0x7fffffff, DL, MVT::i32));
7201 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, DstVT, Op);
7202 } else {
7203 report_fatal_error("Bad address space in addrspacecast");
7204 }
7205 return Op;
7206}
7207
7208SDValue SystemZTargetLowering::lowerFP_EXTEND(SDValue Op,
7209 SelectionDAG &DAG) const {
7210 SDValue In = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
7211 if (In.getSimpleValueType() != MVT::f16)
7212 return Op; // Legal
7213 return SDValue(); // Let legalizer emit the libcall.
7214}
7215
7217 MVT VT, SDValue Arg, SDLoc DL,
7218 SDValue Chain, bool IsStrict) const {
7219 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected request for libcall!");
7220 MakeLibCallOptions CallOptions;
7221 SDValue Result;
7222 std::tie(Result, Chain) =
7223 makeLibCall(DAG, LC, VT, Arg, CallOptions, DL, Chain);
7224 return IsStrict ? DAG.getMergeValues({Result, Chain}, DL) : Result;
7225}
7226
7227SDValue SystemZTargetLowering::lower_FP_TO_INT(SDValue Op,
7228 SelectionDAG &DAG) const {
7229 bool IsSigned = (Op->getOpcode() == ISD::FP_TO_SINT ||
7230 Op->getOpcode() == ISD::STRICT_FP_TO_SINT);
7231 bool IsStrict = Op->isStrictFPOpcode();
7232 SDLoc DL(Op);
7233 MVT VT = Op.getSimpleValueType();
7234 SDValue InOp = Op.getOperand(IsStrict ? 1 : 0);
7235 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
7236 EVT InVT = InOp.getValueType();
7237
7238 // FP to unsigned is not directly supported on z10. Promoting an i32
7239 // result to (signed) i64 doesn't generate an inexact condition (fp
7240 // exception) for values that are outside the i32 range but in the i64
7241 // range, so use the default expansion.
7242 if (!Subtarget.hasFPExtension() && !IsSigned)
7243 // Expand i32/i64. F16 values will be recognized to fit and extended.
7244 return SDValue();
7245
7246 // Conversion from f16 is done via f32.
7247 if (InOp.getSimpleValueType() == MVT::f16) {
7249 LowerOperationWrapper(Op.getNode(), Results, DAG);
7250 return DAG.getMergeValues(Results, DL);
7251 }
7252
7253 if (VT == MVT::i128) {
7254 RTLIB::Libcall LC =
7255 IsSigned ? RTLIB::getFPTOSINT(InVT, VT) : RTLIB::getFPTOUINT(InVT, VT);
7256 return useLibCall(DAG, LC, VT, InOp, DL, Chain, IsStrict);
7257 }
7258
7259 return Op; // Legal
7260}
7261
7262SDValue SystemZTargetLowering::lower_INT_TO_FP(SDValue Op,
7263 SelectionDAG &DAG) const {
7264 bool IsSigned = (Op->getOpcode() == ISD::SINT_TO_FP ||
7265 Op->getOpcode() == ISD::STRICT_SINT_TO_FP);
7266 bool IsStrict = Op->isStrictFPOpcode();
7267 SDLoc DL(Op);
7268 MVT VT = Op.getSimpleValueType();
7269 SDValue InOp = Op.getOperand(IsStrict ? 1 : 0);
7270 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
7271 EVT InVT = InOp.getValueType();
7272
7273 // Conversion to f16 is done via f32.
7274 if (VT == MVT::f16) {
7276 LowerOperationWrapper(Op.getNode(), Results, DAG);
7277 return DAG.getMergeValues(Results, DL);
7278 }
7279
7280 // Unsigned to fp is not directly supported on z10.
7281 if (!Subtarget.hasFPExtension() && !IsSigned)
7282 return SDValue(); // Expand i64.
7283
7284 if (InVT == MVT::i128) {
7285 RTLIB::Libcall LC =
7286 IsSigned ? RTLIB::getSINTTOFP(InVT, VT) : RTLIB::getUINTTOFP(InVT, VT);
7287 return useLibCall(DAG, LC, VT, InOp, DL, Chain, IsStrict);
7288 }
7289
7290 return Op; // Legal
7291}
7292
7293// Lower an f16 LOAD in case of no vector support.
7294SDValue SystemZTargetLowering::lowerLoadF16(SDValue Op,
7295 SelectionDAG &DAG) const {
7296 EVT RegVT = Op.getValueType();
7297 assert(RegVT == MVT::f16 && "Expected to lower an f16 load.");
7298 (void)RegVT;
7299
7300 // Load as integer.
7301 SDLoc DL(Op);
7302 SDValue NewLd;
7303 if (auto *AtomicLd = dyn_cast<AtomicSDNode>(Op.getNode())) {
7304 assert(EVT(RegVT) == AtomicLd->getMemoryVT() && "Unhandled f16 load");
7305 NewLd = DAG.getAtomicLoad(ISD::EXTLOAD, DL, MVT::i16, MVT::i64,
7306 AtomicLd->getChain(), AtomicLd->getBasePtr(),
7307 AtomicLd->getMemOperand());
7308 } else {
7309 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
7310 assert(EVT(RegVT) == Ld->getMemoryVT() && "Unhandled f16 load");
7311 NewLd = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i64, Ld->getChain(),
7312 Ld->getBasePtr(), Ld->getPointerInfo(), MVT::i16,
7313 Ld->getBaseAlign(), Ld->getMemOperand()->getFlags());
7314 }
7315 SDValue F16Val = convertToF16(NewLd, DAG);
7316 return DAG.getMergeValues({F16Val, NewLd.getValue(1)}, DL);
7317}
7318
7319// Lower an f16 STORE in case of no vector support.
7320SDValue SystemZTargetLowering::lowerStoreF16(SDValue Op,
7321 SelectionDAG &DAG) const {
7322 SDLoc DL(Op);
7323 SDValue Shft = convertFromF16(Op->getOperand(1), DL, DAG);
7324
7325 if (auto *AtomicSt = dyn_cast<AtomicSDNode>(Op.getNode()))
7326 return DAG.getAtomic(ISD::ATOMIC_STORE, DL, MVT::i16, AtomicSt->getChain(),
7327 Shft, AtomicSt->getBasePtr(),
7328 AtomicSt->getMemOperand());
7329
7330 StoreSDNode *St = cast<StoreSDNode>(Op.getNode());
7331 return DAG.getTruncStore(St->getChain(), DL, Shft, St->getBasePtr(), MVT::i16,
7332 St->getMemOperand());
7333}
7334
7335SDValue SystemZTargetLowering::lowerIS_FPCLASS(SDValue Op,
7336 SelectionDAG &DAG) const {
7337 SDLoc DL(Op);
7338 MVT ResultVT = Op.getSimpleValueType();
7339 SDValue Arg = Op.getOperand(0);
7340 unsigned Check = Op.getConstantOperandVal(1);
7341
7342 unsigned TDCMask = 0;
7343 if (Check & fcSNan)
7345 if (Check & fcQNan)
7347 if (Check & fcPosInf)
7349 if (Check & fcNegInf)
7351 if (Check & fcPosNormal)
7353 if (Check & fcNegNormal)
7355 if (Check & fcPosSubnormal)
7357 if (Check & fcNegSubnormal)
7359 if (Check & fcPosZero)
7360 TDCMask |= SystemZ::TDCMASK_ZERO_PLUS;
7361 if (Check & fcNegZero)
7362 TDCMask |= SystemZ::TDCMASK_ZERO_MINUS;
7363 SDValue TDCMaskV = DAG.getConstant(TDCMask, DL, MVT::i64);
7364
7365 SDValue Intr = DAG.getNode(SystemZISD::TDC, DL, ResultVT, Arg, TDCMaskV);
7366 return getCCResult(DAG, Intr);
7367}
7368
7369SDValue SystemZTargetLowering::lowerREADCYCLECOUNTER(SDValue Op,
7370 SelectionDAG &DAG) const {
7371 SDLoc DL(Op);
7372 SDValue Chain = Op.getOperand(0);
7373
7374 // STCKF only supports a memory operand, so we have to use a temporary.
7375 SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
7376 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
7377 MachinePointerInfo MPI =
7379
7380 // Use STCFK to store the TOD clock into the temporary.
7381 SDValue StoreOps[] = {Chain, StackPtr};
7382 Chain = DAG.getMemIntrinsicNode(
7383 SystemZISD::STCKF, DL, DAG.getVTList(MVT::Other), StoreOps, MVT::i64,
7384 MPI, MaybeAlign(), MachineMemOperand::MOStore);
7385
7386 // And read it back from there.
7387 return DAG.getLoad(MVT::i64, DL, Chain, StackPtr, MPI);
7388}
7389
7391 SelectionDAG &DAG) const {
7392 switch (Op.getOpcode()) {
7393 case ISD::FRAMEADDR:
7394 return lowerFRAMEADDR(Op, DAG);
7395 case ISD::RETURNADDR:
7396 return lowerRETURNADDR(Op, DAG);
7397 case ISD::BR_CC:
7398 return lowerBR_CC(Op, DAG);
7399 case ISD::SELECT_CC:
7400 return lowerSELECT_CC(Op, DAG);
7401 case ISD::SETCC:
7402 return lowerSETCC(Op, DAG);
7403 case ISD::STRICT_FSETCC:
7404 return lowerSTRICT_FSETCC(Op, DAG, false);
7406 return lowerSTRICT_FSETCC(Op, DAG, true);
7407 case ISD::GlobalAddress:
7408 return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
7410 return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
7411 case ISD::BlockAddress:
7412 return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
7413 case ISD::JumpTable:
7414 return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
7415 case ISD::ConstantPool:
7416 return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
7417 case ISD::BITCAST:
7418 return lowerBITCAST(Op, DAG);
7419 case ISD::VASTART:
7420 return lowerVASTART(Op, DAG);
7421 case ISD::VACOPY:
7422 return lowerVACOPY(Op, DAG);
7424 return lowerDYNAMIC_STACKALLOC(Op, DAG);
7426 return lowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
7427 case ISD::MULHS:
7428 return lowerMULH(Op, DAG, SystemZISD::SMUL_LOHI);
7429 case ISD::MULHU:
7430 return lowerMULH(Op, DAG, SystemZISD::UMUL_LOHI);
7431 case ISD::SMUL_LOHI:
7432 return lowerSMUL_LOHI(Op, DAG);
7433 case ISD::UMUL_LOHI:
7434 return lowerUMUL_LOHI(Op, DAG);
7435 case ISD::SDIVREM:
7436 return lowerSDIVREM(Op, DAG);
7437 case ISD::UDIVREM:
7438 return lowerUDIVREM(Op, DAG);
7439 case ISD::SADDO:
7440 case ISD::SSUBO:
7441 case ISD::UADDO:
7442 case ISD::USUBO:
7443 return lowerXALUO(Op, DAG);
7444 case ISD::UADDO_CARRY:
7445 case ISD::USUBO_CARRY:
7446 return lowerUADDSUBO_CARRY(Op, DAG);
7447 case ISD::OR:
7448 return lowerOR(Op, DAG);
7449 case ISD::CTPOP:
7450 return lowerCTPOP(Op, DAG);
7451 case ISD::PDEP:
7452 return lowerPDEP(Op, DAG);
7453 case ISD::PEXT:
7454 return lowerPEXT(Op, DAG);
7455 case ISD::VECREDUCE_ADD:
7456 return lowerVECREDUCE_ADD(Op, DAG);
7457 case ISD::ATOMIC_FENCE:
7458 return lowerATOMIC_FENCE(Op, DAG);
7459 case ISD::ATOMIC_STORE:
7460 return lowerATOMIC_STORE(Op, DAG);
7461 case ISD::ATOMIC_LOAD:
7462 return lowerATOMIC_LOAD(Op, DAG);
7464 return lowerATOMIC_LOAD_SUB(Op, DAG);
7466 return lowerATOMIC_CMP_SWAP(Op, DAG);
7467 case ISD::STACKSAVE:
7468 return lowerSTACKSAVE(Op, DAG);
7469 case ISD::STACKRESTORE:
7470 return lowerSTACKRESTORE(Op, DAG);
7471 case ISD::PREFETCH:
7472 return lowerPREFETCH(Op, DAG);
7474 return lowerINTRINSIC_W_CHAIN(Op, DAG);
7476 return lowerINTRINSIC_WO_CHAIN(Op, DAG);
7477 case ISD::BUILD_VECTOR:
7478 return lowerBUILD_VECTOR(Op, DAG);
7480 return lowerVECTOR_SHUFFLE(Op, DAG);
7482 return lowerSCALAR_TO_VECTOR(Op, DAG);
7484 return lowerINSERT_VECTOR_ELT(Op, DAG);
7486 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
7488 return lowerSIGN_EXTEND_VECTOR_INREG(Op, DAG);
7490 return lowerZERO_EXTEND_VECTOR_INREG(Op, DAG);
7491 case ISD::SHL:
7492 return lowerShift(Op, DAG, SystemZISD::VSHL_BY_SCALAR);
7493 case ISD::SRL:
7494 return lowerShift(Op, DAG, SystemZISD::VSRL_BY_SCALAR);
7495 case ISD::SRA:
7496 return lowerShift(Op, DAG, SystemZISD::VSRA_BY_SCALAR);
7497 case ISD::ADDRSPACECAST:
7498 return lowerAddrSpaceCast(Op, DAG);
7499 case ISD::ROTL:
7500 return lowerShift(Op, DAG, SystemZISD::VROTL_BY_SCALAR);
7501 case ISD::FSHL:
7502 return lowerFSHL(Op, DAG);
7503 case ISD::FSHR:
7504 return lowerFSHR(Op, DAG);
7505 case ISD::FP_EXTEND:
7507 return lowerFP_EXTEND(Op, DAG);
7508 case ISD::FP_TO_UINT:
7509 case ISD::FP_TO_SINT:
7512 return lower_FP_TO_INT(Op, DAG);
7513 case ISD::UINT_TO_FP:
7514 case ISD::SINT_TO_FP:
7517 return lower_INT_TO_FP(Op, DAG);
7518 case ISD::LOAD:
7519 return lowerLoadF16(Op, DAG);
7520 case ISD::STORE:
7521 return lowerStoreF16(Op, DAG);
7522 case ISD::IS_FPCLASS:
7523 return lowerIS_FPCLASS(Op, DAG);
7524 case ISD::GET_ROUNDING:
7525 return lowerGET_ROUNDING(Op, DAG);
7527 return lowerREADCYCLECOUNTER(Op, DAG);
7530 // These operations are legal on our platform, but we cannot actually
7531 // set the operation action to Legal as common code would treat this
7532 // as equivalent to Expand. Instead, we keep the operation action to
7533 // Custom and just leave them unchanged here.
7534 return Op;
7535
7536 default:
7537 llvm_unreachable("Unexpected node to lower");
7538 }
7539}
7540
7542 const SDLoc &SL) {
7543 // If i128 is legal, just use a normal bitcast.
7544 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128))
7545 return DAG.getBitcast(MVT::f128, Src);
7546
7547 // Otherwise, f128 must live in FP128, so do a partwise move.
7549 &SystemZ::FP128BitRegClass);
7550
7551 SDValue Hi, Lo;
7552 std::tie(Lo, Hi) = DAG.SplitScalar(Src, SL, MVT::i64, MVT::i64);
7553
7554 Hi = DAG.getBitcast(MVT::f64, Hi);
7555 Lo = DAG.getBitcast(MVT::f64, Lo);
7556
7557 SDNode *Pair = DAG.getMachineNode(
7558 SystemZ::REG_SEQUENCE, SL, MVT::f128,
7559 {DAG.getTargetConstant(SystemZ::FP128BitRegClassID, SL, MVT::i32), Lo,
7560 DAG.getTargetConstant(SystemZ::subreg_l64, SL, MVT::i32), Hi,
7561 DAG.getTargetConstant(SystemZ::subreg_h64, SL, MVT::i32)});
7562 return SDValue(Pair, 0);
7563}
7564
7566 const SDLoc &SL) {
7567 // If i128 is legal, just use a normal bitcast.
7568 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128))
7569 return DAG.getBitcast(MVT::i128, Src);
7570
7571 // Otherwise, f128 must live in FP128, so do a partwise move.
7573 &SystemZ::FP128BitRegClass);
7574
7575 SDValue LoFP =
7576 DAG.getTargetExtractSubreg(SystemZ::subreg_l64, SL, MVT::f64, Src);
7577 SDValue HiFP =
7578 DAG.getTargetExtractSubreg(SystemZ::subreg_h64, SL, MVT::f64, Src);
7579 SDValue Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i64, LoFP);
7580 SDValue Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i64, HiFP);
7581
7582 return DAG.getNode(ISD::BUILD_PAIR, SL, MVT::i128, Lo, Hi);
7583}
7584
7585// Lower operations with invalid operand or result types.
7586void
7589 SelectionDAG &DAG) const {
7590 switch (N->getOpcode()) {
7591 case ISD::ATOMIC_LOAD: {
7592 SDLoc DL(N);
7593 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
7594 SDValue Ops[] = { N->getOperand(0), N->getOperand(1) };
7595 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
7596 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_LOAD_128,
7597 DL, Tys, Ops, MVT::i128, MMO);
7598
7599 SDValue Lowered = lowerGR128ToI128(DAG, Res);
7600 if (N->getValueType(0) == MVT::f128)
7601 Lowered = expandBitCastI128ToF128(DAG, Lowered, DL);
7602 Results.push_back(Lowered);
7603 Results.push_back(Res.getValue(1));
7604 break;
7605 }
7606 case ISD::ATOMIC_STORE: {
7607 SDLoc DL(N);
7608 SDVTList Tys = DAG.getVTList(MVT::Other);
7609 SDValue Val = N->getOperand(1);
7610 if (Val.getValueType() == MVT::f128)
7611 Val = expandBitCastF128ToI128(DAG, Val, DL);
7612 Val = lowerI128ToGR128(DAG, Val);
7613
7614 SDValue Ops[] = {N->getOperand(0), Val, N->getOperand(2)};
7615 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
7616 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_STORE_128,
7617 DL, Tys, Ops, MVT::i128, MMO);
7618 // We have to enforce sequential consistency by performing a
7619 // serialization operation after the store.
7620 if (cast<AtomicSDNode>(N)->getSuccessOrdering() ==
7622 Res = SDValue(DAG.getMachineNode(SystemZ::Serialize, DL,
7623 MVT::Other, Res), 0);
7624 Results.push_back(Res);
7625 break;
7626 }
7628 SDLoc DL(N);
7629 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::i32, MVT::Other);
7630 SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
7631 lowerI128ToGR128(DAG, N->getOperand(2)),
7632 lowerI128ToGR128(DAG, N->getOperand(3)) };
7633 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
7634 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP_128,
7635 DL, Tys, Ops, MVT::i128, MMO);
7636 SDValue Success = emitSETCC(DAG, DL, Res.getValue(1),
7638 Success = DAG.getZExtOrTrunc(Success, DL, N->getValueType(1));
7639 Results.push_back(lowerGR128ToI128(DAG, Res));
7640 Results.push_back(Success);
7641 Results.push_back(Res.getValue(2));
7642 break;
7643 }
7644 case ISD::BITCAST: {
7645 if (useSoftFloat())
7646 return;
7647 SDLoc DL(N);
7648 SDValue Src = N->getOperand(0);
7649 EVT SrcVT = Src.getValueType();
7650 EVT ResVT = N->getValueType(0);
7651 if (ResVT == MVT::i128 && SrcVT == MVT::f128)
7652 Results.push_back(expandBitCastF128ToI128(DAG, Src, DL));
7653 else if (SrcVT == MVT::i16 && ResVT == MVT::f16) {
7654 if (Subtarget.hasVector()) {
7655 SDValue In32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Src);
7656 Results.push_back(SDValue(
7657 DAG.getMachineNode(SystemZ::LEFR_16, DL, MVT::f16, In32), 0));
7658 } else {
7659 SDValue In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Src);
7660 Results.push_back(convertToF16(In64, DAG));
7661 }
7662 } else if (SrcVT == MVT::f16 && ResVT == MVT::i16) {
7663 SDValue ExtractedVal =
7664 Subtarget.hasVector()
7665 ? SDValue(DAG.getMachineNode(SystemZ::LFER_16, DL, MVT::i32, Src),
7666 0)
7667 : convertFromF16(Src, DL, DAG);
7668 Results.push_back(DAG.getZExtOrTrunc(ExtractedVal, DL, ResVT));
7669 }
7670 break;
7671 }
7672 case ISD::UINT_TO_FP:
7673 case ISD::SINT_TO_FP:
7676 if (useSoftFloat())
7677 return;
7678 bool IsStrict = N->isStrictFPOpcode();
7679 SDLoc DL(N);
7680 SDValue InOp = N->getOperand(IsStrict ? 1 : 0);
7681 EVT ResVT = N->getValueType(0);
7682 SDValue Chain = IsStrict ? N->getOperand(0) : DAG.getEntryNode();
7683 if (ResVT == MVT::f16) {
7684 if (!IsStrict) {
7685 SDValue OpF32 = DAG.getNode(N->getOpcode(), DL, MVT::f32, InOp);
7686 Results.push_back(DAG.getFPExtendOrRound(OpF32, DL, MVT::f16));
7687 } else {
7688 SDValue OpF32 =
7689 DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::f32, MVT::Other),
7690 {Chain, InOp});
7691 SDValue F16Res;
7692 std::tie(F16Res, Chain) = DAG.getStrictFPExtendOrRound(
7693 OpF32, OpF32.getValue(1), DL, MVT::f16);
7694 Results.push_back(F16Res);
7695 Results.push_back(Chain);
7696 }
7697 }
7698 break;
7699 }
7700 case ISD::FP_TO_UINT:
7701 case ISD::FP_TO_SINT:
7704 if (useSoftFloat())
7705 return;
7706 bool IsStrict = N->isStrictFPOpcode();
7707 SDLoc DL(N);
7708 EVT ResVT = N->getValueType(0);
7709 SDValue InOp = N->getOperand(IsStrict ? 1 : 0);
7710 EVT InVT = InOp->getValueType(0);
7711 SDValue Chain = IsStrict ? N->getOperand(0) : DAG.getEntryNode();
7712 if (InVT == MVT::f16) {
7713 if (!IsStrict) {
7714 SDValue InF32 = DAG.getFPExtendOrRound(InOp, DL, MVT::f32);
7715 Results.push_back(DAG.getNode(N->getOpcode(), DL, ResVT, InF32));
7716 } else {
7717 SDValue InF32;
7718 std::tie(InF32, Chain) =
7719 DAG.getStrictFPExtendOrRound(InOp, Chain, DL, MVT::f32);
7720 SDValue OpF32 =
7721 DAG.getNode(N->getOpcode(), DL, DAG.getVTList(ResVT, MVT::Other),
7722 {Chain, InF32});
7723 Results.push_back(OpF32);
7724 Results.push_back(OpF32.getValue(1));
7725 }
7726 }
7727 break;
7728 }
7729 case ISD::ATOMIC_SWAP:
7730 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_SWAPW);
7731 break;
7733 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_ADD);
7734 break;
7736 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_SUB);
7737 break;
7739 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_AND);
7740 break;
7742 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_OR);
7743 break;
7745 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_XOR);
7746 break;
7748 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_NAND);
7749 break;
7751 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_MIN);
7752 break;
7754 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_MAX);
7755 break;
7757 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
7758 break;
7760 lowerATOMIC_LOAD_OP(N, Results, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
7761 break;
7762 default:
7763 llvm_unreachable("Unexpected node to lower");
7764 }
7765}
7766
7767void
7773
7774// Return true if VT is a vector whose elements are a whole number of bytes
7775// in width. Also check for presence of vector support.
7776bool SystemZTargetLowering::canTreatAsByteVector(EVT VT) const {
7777 if (!Subtarget.hasVector())
7778 return false;
7779
7780 return VT.isVector() && VT.getScalarSizeInBits() % 8 == 0 && VT.isSimple();
7781}
7782
7783// Try to simplify an EXTRACT_VECTOR_ELT from a vector of type VecVT
7784// producing a result of type ResVT. Op is a possibly bitcast version
7785// of the input vector and Index is the index (based on type VecVT) that
7786// should be extracted. Return the new extraction if a simplification
7787// was possible or if Force is true.
7788SDValue SystemZTargetLowering::combineExtract(const SDLoc &DL, EVT ResVT,
7789 EVT VecVT, SDValue Op,
7790 unsigned Index,
7791 DAGCombinerInfo &DCI,
7792 bool Force) const {
7793 SelectionDAG &DAG = DCI.DAG;
7794
7795 // The number of bytes being extracted.
7796 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
7797
7798 for (;;) {
7799 unsigned Opcode = Op.getOpcode();
7800 if (Opcode == ISD::BITCAST)
7801 // Look through bitcasts.
7802 Op = Op.getOperand(0);
7803 else if ((Opcode == ISD::VECTOR_SHUFFLE || Opcode == SystemZISD::SPLAT) &&
7804 canTreatAsByteVector(Op.getValueType())) {
7805 // Get a VPERM-like permute mask and see whether the bytes covered
7806 // by the extracted element are a contiguous sequence from one
7807 // source operand.
7809 if (!getVPermMask(Op, Bytes))
7810 break;
7811 int First;
7812 if (!getShuffleInput(Bytes, Index * BytesPerElement,
7813 BytesPerElement, First))
7814 break;
7815 if (First < 0)
7816 return DAG.getUNDEF(ResVT);
7817 // Make sure the contiguous sequence starts at a multiple of the
7818 // original element size.
7819 unsigned Byte = unsigned(First) % Bytes.size();
7820 if (Byte % BytesPerElement != 0)
7821 break;
7822 // We can get the extracted value directly from an input.
7823 Index = Byte / BytesPerElement;
7824 Op = Op.getOperand(unsigned(First) / Bytes.size());
7825 Force = true;
7826 } else if (Opcode == ISD::BUILD_VECTOR &&
7827 canTreatAsByteVector(Op.getValueType())) {
7828 // We can only optimize this case if the BUILD_VECTOR elements are
7829 // at least as wide as the extracted value.
7830 EVT OpVT = Op.getValueType();
7831 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
7832 if (OpBytesPerElement < BytesPerElement)
7833 break;
7834 // Make sure that the least-significant bit of the extracted value
7835 // is the least significant bit of an input.
7836 unsigned End = (Index + 1) * BytesPerElement;
7837 if (End % OpBytesPerElement != 0)
7838 break;
7839 // We're extracting the low part of one operand of the BUILD_VECTOR.
7840 Op = Op.getOperand(End / OpBytesPerElement - 1);
7841 EVT ResIntVT = MVT::getIntegerVT(ResVT.getSizeInBits());
7842 if (!isTypeLegal(ResIntVT))
7843 break;
7844 if (!Op.getValueType().isInteger()) {
7845 EVT OpIntVT = MVT::getIntegerVT(Op.getValueSizeInBits());
7846 if (!isTypeLegal(OpIntVT))
7847 break;
7848 Op = DAG.getNode(ISD::BITCAST, DL, OpIntVT, Op);
7849 DCI.AddToWorklist(Op.getNode());
7850 }
7851 Op = DAG.getNode(ISD::TRUNCATE, DL, ResIntVT, Op);
7852 if (ResIntVT != ResVT) {
7853 DCI.AddToWorklist(Op.getNode());
7854 Op = DAG.getNode(ISD::BITCAST, DL, ResVT, Op);
7855 }
7856 return Op;
7857 } else if ((Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
7859 Opcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
7860 canTreatAsByteVector(Op.getValueType()) &&
7861 canTreatAsByteVector(Op.getOperand(0).getValueType())) {
7862 // Make sure that only the unextended bits are significant.
7863 EVT ExtVT = Op.getValueType();
7864 EVT OpVT = Op.getOperand(0).getValueType();
7865 unsigned ExtBytesPerElement = ExtVT.getVectorElementType().getStoreSize();
7866 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
7867 unsigned Byte = Index * BytesPerElement;
7868 unsigned SubByte = Byte % ExtBytesPerElement;
7869 unsigned MinSubByte = ExtBytesPerElement - OpBytesPerElement;
7870 if (SubByte < MinSubByte ||
7871 SubByte + BytesPerElement > ExtBytesPerElement)
7872 break;
7873 // Get the byte offset of the unextended element
7874 Byte = Byte / ExtBytesPerElement * OpBytesPerElement;
7875 // ...then add the byte offset relative to that element.
7876 Byte += SubByte - MinSubByte;
7877 if (Byte % BytesPerElement != 0)
7878 break;
7879 Op = Op.getOperand(0);
7880 Index = Byte / BytesPerElement;
7881 Force = true;
7882 } else
7883 break;
7884 }
7885 if (Force) {
7886 if (Op.getValueType() != VecVT) {
7887 Op = DAG.getNode(ISD::BITCAST, DL, VecVT, Op);
7888 DCI.AddToWorklist(Op.getNode());
7889 }
7890 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Op,
7891 DAG.getConstant(Index, DL, MVT::i32));
7892 }
7893 return SDValue();
7894}
7895
7896// Optimize vector operations in scalar value Op on the basis that Op
7897// is truncated to TruncVT.
7898SDValue SystemZTargetLowering::combineTruncateExtract(
7899 const SDLoc &DL, EVT TruncVT, SDValue Op, DAGCombinerInfo &DCI) const {
7900 // If we have (trunc (extract_vector_elt X, Y)), try to turn it into
7901 // (extract_vector_elt (bitcast X), Y'), where (bitcast X) has elements
7902 // of type TruncVT.
7903 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7904 TruncVT.getSizeInBits() % 8 == 0) {
7905 SDValue Vec = Op.getOperand(0);
7906 EVT VecVT = Vec.getValueType();
7907 if (canTreatAsByteVector(VecVT)) {
7908 if (auto *IndexN = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7909 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
7910 unsigned TruncBytes = TruncVT.getStoreSize();
7911 if (BytesPerElement % TruncBytes == 0) {
7912 // Calculate the value of Y' in the above description. We are
7913 // splitting the original elements into Scale equal-sized pieces
7914 // and for truncation purposes want the last (least-significant)
7915 // of these pieces for IndexN. This is easiest to do by calculating
7916 // the start index of the following element and then subtracting 1.
7917 unsigned Scale = BytesPerElement / TruncBytes;
7918 unsigned NewIndex = (IndexN->getZExtValue() + 1) * Scale - 1;
7919
7920 // Defer the creation of the bitcast from X to combineExtract,
7921 // which might be able to optimize the extraction.
7922 VecVT = EVT::getVectorVT(*DCI.DAG.getContext(),
7923 MVT::getIntegerVT(TruncBytes * 8),
7924 VecVT.getStoreSize() / TruncBytes);
7925 EVT ResVT = (TruncBytes < 4 ? MVT::i32 : TruncVT);
7926 return combineExtract(DL, ResVT, VecVT, Vec, NewIndex, DCI, true);
7927 }
7928 }
7929 }
7930 }
7931 return SDValue();
7932}
7933
7934SDValue SystemZTargetLowering::combineZERO_EXTEND(
7935 SDNode *N, DAGCombinerInfo &DCI) const {
7936 // Convert (zext (select_ccmask C1, C2)) into (select_ccmask C1', C2')
7937 SelectionDAG &DAG = DCI.DAG;
7938 SDValue N0 = N->getOperand(0);
7939 EVT VT = N->getValueType(0);
7940 if (N0.getOpcode() == SystemZISD::SELECT_CCMASK) {
7941 auto *TrueOp = dyn_cast<ConstantSDNode>(N0.getOperand(0));
7942 auto *FalseOp = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7943 if (TrueOp && FalseOp) {
7944 SDLoc DL(N0);
7945 SDValue Ops[] = { DAG.getConstant(TrueOp->getZExtValue(), DL, VT),
7946 DAG.getConstant(FalseOp->getZExtValue(), DL, VT),
7947 N0.getOperand(2), N0.getOperand(3), N0.getOperand(4) };
7948 SDValue NewSelect = DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VT, Ops);
7949 // If N0 has multiple uses, change other uses as well.
7950 if (!N0.hasOneUse()) {
7951 SDValue TruncSelect =
7952 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), NewSelect);
7953 DCI.CombineTo(N0.getNode(), TruncSelect);
7954 }
7955 return NewSelect;
7956 }
7957 }
7958 // Convert (zext (xor (trunc X), C)) into (xor (trunc X), C') if the size
7959 // of the result is smaller than the size of X and all the truncated bits
7960 // of X are already zero.
7961 if (N0.getOpcode() == ISD::XOR &&
7962 N0.hasOneUse() && N0.getOperand(0).hasOneUse() &&
7963 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7964 N0.getOperand(1).getOpcode() == ISD::Constant) {
7965 SDValue X = N0.getOperand(0).getOperand(0);
7966 if (VT.isScalarInteger() && VT.getSizeInBits() < X.getValueSizeInBits()) {
7967 KnownBits Known = DAG.computeKnownBits(X);
7968 APInt TruncatedBits = APInt::getBitsSet(X.getValueSizeInBits(),
7969 N0.getValueSizeInBits(),
7970 VT.getSizeInBits());
7971 if (TruncatedBits.isSubsetOf(Known.Zero)) {
7972 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7973 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
7974 return DAG.getNode(ISD::XOR, SDLoc(N0), VT,
7975 X, DAG.getConstant(Mask, SDLoc(N0), VT));
7976 }
7977 }
7978 }
7979 // Recognize patterns for VECTOR SUBTRACT COMPUTE BORROW INDICATION
7980 // and VECTOR ADD COMPUTE CARRY for i128:
7981 // (zext (setcc_uge X Y)) --> (VSCBI X Y)
7982 // (zext (setcc_ule Y X)) --> (VSCBI X Y)
7983 // (zext (setcc_ult (add X Y) X/Y) -> (VACC X Y)
7984 // (zext (setcc_ugt X/Y (add X Y)) -> (VACC X Y)
7985 // For vector types, these patterns are recognized in the .td file.
7986 if (N0.getOpcode() == ISD::SETCC && isTypeLegal(VT) && VT == MVT::i128 &&
7987 N0.getOperand(0).getValueType() == VT) {
7988 SDValue Op0 = N0.getOperand(0);
7989 SDValue Op1 = N0.getOperand(1);
7990 const ISD::CondCode CC = N0.getOperandCondCode(2);
7991 switch (CC) {
7992 case ISD::SETULE:
7993 std::swap(Op0, Op1);
7994 [[fallthrough]];
7995 case ISD::SETUGE:
7996 return DAG.getNode(SystemZISD::VSCBI, SDLoc(N0), VT, Op0, Op1);
7997 case ISD::SETUGT:
7998 std::swap(Op0, Op1);
7999 [[fallthrough]];
8000 case ISD::SETULT:
8001 if (Op0->hasOneUse() && Op0->getOpcode() == ISD::ADD &&
8002 (Op0->getOperand(0) == Op1 || Op0->getOperand(1) == Op1))
8003 return DAG.getNode(SystemZISD::VACC, SDLoc(N0), VT, Op0->getOperand(0),
8004 Op0->getOperand(1));
8005 break;
8006 default:
8007 break;
8008 }
8009 }
8010
8011 return SDValue();
8012}
8013
8014SDValue SystemZTargetLowering::combineSIGN_EXTEND_INREG(
8015 SDNode *N, DAGCombinerInfo &DCI) const {
8016 // Convert (sext_in_reg (setcc LHS, RHS, COND), i1)
8017 // and (sext_in_reg (any_extend (setcc LHS, RHS, COND)), i1)
8018 // into (select_cc LHS, RHS, -1, 0, COND)
8019 SelectionDAG &DAG = DCI.DAG;
8020 SDValue N0 = N->getOperand(0);
8021 EVT VT = N->getValueType(0);
8022 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8023 if (N0.hasOneUse() && N0.getOpcode() == ISD::ANY_EXTEND)
8024 N0 = N0.getOperand(0);
8025 if (EVT == MVT::i1 && N0.hasOneUse() && N0.getOpcode() == ISD::SETCC) {
8026 SDLoc DL(N0);
8027 SDValue Ops[] = { N0.getOperand(0), N0.getOperand(1),
8028 DAG.getAllOnesConstant(DL, VT),
8029 DAG.getConstant(0, DL, VT), N0.getOperand(2) };
8030 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8031 }
8032 return SDValue();
8033}
8034
8035SDValue SystemZTargetLowering::combineSIGN_EXTEND(
8036 SDNode *N, DAGCombinerInfo &DCI) const {
8037 // Convert (sext (ashr (shl X, C1), C2)) to
8038 // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
8039 // cheap as narrower ones.
8040 SelectionDAG &DAG = DCI.DAG;
8041 SDValue N0 = N->getOperand(0);
8042 EVT VT = N->getValueType(0);
8043 if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
8044 auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8045 SDValue Inner = N0.getOperand(0);
8046 if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
8047 if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
8048 unsigned Extra = (VT.getSizeInBits() - N0.getValueSizeInBits());
8049 unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
8050 unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
8051 EVT ShiftVT = N0.getOperand(1).getValueType();
8052 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
8053 Inner.getOperand(0));
8054 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
8055 DAG.getConstant(NewShlAmt, SDLoc(Inner),
8056 ShiftVT));
8057 return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
8058 DAG.getConstant(NewSraAmt, SDLoc(N0), ShiftVT));
8059 }
8060 }
8061 }
8062
8063 return SDValue();
8064}
8065
8066SDValue SystemZTargetLowering::combineMERGE(
8067 SDNode *N, DAGCombinerInfo &DCI) const {
8068 SelectionDAG &DAG = DCI.DAG;
8069 unsigned Opcode = N->getOpcode();
8070 SDValue Op0 = N->getOperand(0);
8071 SDValue Op1 = N->getOperand(1);
8072 if (Op0.getOpcode() == ISD::BITCAST)
8073 Op0 = Op0.getOperand(0);
8074 if (ISD::isBuildVectorAllZeros(Op0)) {
8075 // (z_merge_* 0, 0) -> 0. This is mostly useful for using VLLEZF
8076 // for v4f32.
8077 if (Op1 == N->getOperand(0))
8078 return Op1;
8079 // (z_merge_? 0, X) -> (z_unpackl_? 0, X).
8080 EVT VT = Op1.getValueType();
8081 unsigned ElemBytes = VT.getVectorElementType().getStoreSize();
8082 if (ElemBytes <= 4) {
8083 Opcode = (Opcode == SystemZISD::MERGE_HIGH ?
8084 SystemZISD::UNPACKL_HIGH : SystemZISD::UNPACKL_LOW);
8085 EVT InVT = VT.changeVectorElementTypeToInteger();
8086 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(ElemBytes * 16),
8087 SystemZ::VectorBytes / ElemBytes / 2);
8088 if (VT != InVT) {
8089 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), InVT, Op1);
8090 DCI.AddToWorklist(Op1.getNode());
8091 }
8092 SDValue Op = DAG.getNode(Opcode, SDLoc(N), OutVT, Op1);
8093 DCI.AddToWorklist(Op.getNode());
8094 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
8095 }
8096 }
8097 return SDValue();
8098}
8099
8100static bool isI128MovedToParts(LoadSDNode *LD, SDNode *&LoPart,
8101 SDNode *&HiPart) {
8102 LoPart = HiPart = nullptr;
8103
8104 // Scan through all users.
8105 for (SDUse &Use : LD->uses()) {
8106 // Skip the uses of the chain.
8107 if (Use.getResNo() != 0)
8108 continue;
8109
8110 // Verify every user is a TRUNCATE to i64 of the low or high half.
8111 SDNode *User = Use.getUser();
8112 bool IsLoPart = true;
8113 if (User->getOpcode() == ISD::SRL &&
8114 User->getOperand(1).getOpcode() == ISD::Constant &&
8115 User->getConstantOperandVal(1) == 64 && User->hasOneUse()) {
8116 User = *User->user_begin();
8117 IsLoPart = false;
8118 }
8119 if (User->getOpcode() != ISD::TRUNCATE || User->getValueType(0) != MVT::i64)
8120 return false;
8121
8122 if (IsLoPart) {
8123 if (LoPart)
8124 return false;
8125 LoPart = User;
8126 } else {
8127 if (HiPart)
8128 return false;
8129 HiPart = User;
8130 }
8131 }
8132 return true;
8133}
8134
8135static bool isF128MovedToParts(LoadSDNode *LD, SDNode *&LoPart,
8136 SDNode *&HiPart) {
8137 LoPart = HiPart = nullptr;
8138
8139 // Scan through all users.
8140 for (SDUse &Use : LD->uses()) {
8141 // Skip the uses of the chain.
8142 if (Use.getResNo() != 0)
8143 continue;
8144
8145 // Verify every user is an EXTRACT_SUBREG of the low or high half.
8146 SDNode *User = Use.getUser();
8147 if (!User->hasOneUse() || !User->isMachineOpcode() ||
8148 User->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
8149 return false;
8150
8151 switch (User->getConstantOperandVal(1)) {
8152 case SystemZ::subreg_l64:
8153 if (LoPart)
8154 return false;
8155 LoPart = User;
8156 break;
8157 case SystemZ::subreg_h64:
8158 if (HiPart)
8159 return false;
8160 HiPart = User;
8161 break;
8162 default:
8163 return false;
8164 }
8165 }
8166 return true;
8167}
8168
8169SDValue SystemZTargetLowering::combineLOAD(
8170 SDNode *N, DAGCombinerInfo &DCI) const {
8171 SelectionDAG &DAG = DCI.DAG;
8172 EVT LdVT = N->getValueType(0);
8173 if (auto *LN = dyn_cast<LoadSDNode>(N)) {
8174 if (LN->getAddressSpace() == SYSTEMZAS::PTR32) {
8175 MVT PtrVT = getPointerTy(DAG.getDataLayout());
8176 MVT LoadNodeVT = LN->getBasePtr().getSimpleValueType();
8177 if (PtrVT != LoadNodeVT) {
8178 SDLoc DL(LN);
8179 SDValue AddrSpaceCast = DAG.getAddrSpaceCast(
8180 DL, PtrVT, LN->getBasePtr(), SYSTEMZAS::PTR32, 0);
8181 return DAG.getExtLoad(LN->getExtensionType(), DL, LN->getValueType(0),
8182 LN->getChain(), AddrSpaceCast, LN->getMemoryVT(),
8183 LN->getMemOperand());
8184 }
8185 }
8186 }
8187 SDLoc DL(N);
8188
8189 // Replace a 128-bit load that is used solely to move its value into GPRs
8190 // by separate loads of both halves.
8191 LoadSDNode *LD = cast<LoadSDNode>(N);
8192 if (LD->isSimple() && ISD::isNormalLoad(LD)) {
8193 SDNode *LoPart, *HiPart;
8194 if ((LdVT == MVT::i128 && isI128MovedToParts(LD, LoPart, HiPart)) ||
8195 (LdVT == MVT::f128 && isF128MovedToParts(LD, LoPart, HiPart))) {
8196 // Rewrite each extraction as an independent load.
8197 SmallVector<SDValue, 2> ArgChains;
8198 if (HiPart) {
8199 SDValue EltLoad = DAG.getLoad(
8200 HiPart->getValueType(0), DL, LD->getChain(), LD->getBasePtr(),
8201 LD->getPointerInfo(), LD->getBaseAlign(),
8202 LD->getMemOperand()->getFlags(), LD->getAAInfo());
8203
8204 DCI.CombineTo(HiPart, EltLoad, true);
8205 ArgChains.push_back(EltLoad.getValue(1));
8206 }
8207 if (LoPart) {
8208 SDValue EltLoad = DAG.getLoad(
8209 LoPart->getValueType(0), DL, LD->getChain(),
8210 DAG.getObjectPtrOffset(DL, LD->getBasePtr(), TypeSize::getFixed(8)),
8211 LD->getPointerInfo().getWithOffset(8), LD->getBaseAlign(),
8212 LD->getMemOperand()->getFlags(), LD->getAAInfo());
8213
8214 DCI.CombineTo(LoPart, EltLoad, true);
8215 ArgChains.push_back(EltLoad.getValue(1));
8216 }
8217
8218 // Collect all chains via TokenFactor.
8219 SDValue Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, ArgChains);
8220 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8221 DCI.AddToWorklist(Chain.getNode());
8222 return SDValue(N, 0);
8223 }
8224 }
8225
8226 if (LdVT.isVector() || LdVT.isInteger())
8227 return SDValue();
8228 // Transform a scalar load that is REPLICATEd as well as having other
8229 // use(s) to the form where the other use(s) use the first element of the
8230 // REPLICATE instead of the load. Otherwise instruction selection will not
8231 // produce a VLREP. Avoid extracting to a GPR, so only do this for floating
8232 // point loads.
8233
8234 SDValue Replicate;
8235 SmallVector<SDNode*, 8> OtherUses;
8236 for (SDUse &Use : N->uses()) {
8237 if (Use.getUser()->getOpcode() == SystemZISD::REPLICATE) {
8238 if (Replicate)
8239 return SDValue(); // Should never happen
8240 Replicate = SDValue(Use.getUser(), 0);
8241 } else if (Use.getResNo() == 0)
8242 OtherUses.push_back(Use.getUser());
8243 }
8244 if (!Replicate || OtherUses.empty())
8245 return SDValue();
8246
8247 SDValue Extract0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, LdVT,
8248 Replicate, DAG.getConstant(0, DL, MVT::i32));
8249 // Update uses of the loaded Value while preserving old chains.
8250 for (SDNode *U : OtherUses) {
8252 for (SDValue Op : U->ops())
8253 Ops.push_back((Op.getNode() == N && Op.getResNo() == 0) ? Extract0 : Op);
8254 DAG.UpdateNodeOperands(U, Ops);
8255 }
8256 return SDValue(N, 0);
8257}
8258
8259bool SystemZTargetLowering::canLoadStoreByteSwapped(EVT VT) const {
8260 if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)
8261 return true;
8262 if (Subtarget.hasVectorEnhancements2())
8263 if (VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v2i64 || VT == MVT::i128)
8264 return true;
8265 return false;
8266}
8267
8269 if (!VT.isVector() || !VT.isSimple() ||
8270 VT.getSizeInBits() != 128 ||
8271 VT.getScalarSizeInBits() % 8 != 0)
8272 return false;
8273
8274 unsigned NumElts = VT.getVectorNumElements();
8275 for (unsigned i = 0; i < NumElts; ++i) {
8276 if (M[i] < 0) continue; // ignore UNDEF indices
8277 if ((unsigned) M[i] != NumElts - 1 - i)
8278 return false;
8279 }
8280
8281 return true;
8282}
8283
8284static bool isOnlyUsedByStores(SDValue StoredVal, SelectionDAG &DAG) {
8285 for (auto *U : StoredVal->users()) {
8286 if (StoreSDNode *ST = dyn_cast<StoreSDNode>(U)) {
8287 EVT CurrMemVT = ST->getMemoryVT().getScalarType();
8288 if (CurrMemVT.isRound() && CurrMemVT.getStoreSize() <= 16)
8289 continue;
8290 } else if (isa<BuildVectorSDNode>(U)) {
8291 SDValue BuildVector = SDValue(U, 0);
8292 if (DAG.isSplatValue(BuildVector, true/*AllowUndefs*/) &&
8293 isOnlyUsedByStores(BuildVector, DAG))
8294 continue;
8295 }
8296 return false;
8297 }
8298 return true;
8299}
8300
8301static bool isI128MovedFromParts(SDValue Val, SDValue &LoPart,
8302 SDValue &HiPart) {
8303 if (Val.getOpcode() != ISD::OR || !Val.getNode()->hasOneUse())
8304 return false;
8305
8306 SDValue Op0 = Val.getOperand(0);
8307 SDValue Op1 = Val.getOperand(1);
8308
8309 if (Op0.getOpcode() == ISD::SHL)
8310 std::swap(Op0, Op1);
8311 if (Op1.getOpcode() != ISD::SHL || !Op1.getNode()->hasOneUse() ||
8312 Op1.getOperand(1).getOpcode() != ISD::Constant ||
8313 Op1.getConstantOperandVal(1) != 64)
8314 return false;
8315 Op1 = Op1.getOperand(0);
8316
8317 if (Op0.getOpcode() != ISD::ZERO_EXTEND || !Op0.getNode()->hasOneUse() ||
8318 Op0.getOperand(0).getValueType() != MVT::i64)
8319 return false;
8320 if (Op1.getOpcode() != ISD::ANY_EXTEND || !Op1.getNode()->hasOneUse() ||
8321 Op1.getOperand(0).getValueType() != MVT::i64)
8322 return false;
8323
8324 LoPart = Op0.getOperand(0);
8325 HiPart = Op1.getOperand(0);
8326 return true;
8327}
8328
8329static bool isF128MovedFromParts(SDValue Val, SDValue &LoPart,
8330 SDValue &HiPart) {
8331 if (!Val.getNode()->hasOneUse() || !Val.isMachineOpcode() ||
8332 Val.getMachineOpcode() != TargetOpcode::REG_SEQUENCE)
8333 return false;
8334
8335 if (Val->getNumOperands() != 5 ||
8336 Val->getOperand(0)->getAsZExtVal() != SystemZ::FP128BitRegClassID ||
8337 Val->getOperand(2)->getAsZExtVal() != SystemZ::subreg_l64 ||
8338 Val->getOperand(4)->getAsZExtVal() != SystemZ::subreg_h64)
8339 return false;
8340
8341 LoPart = Val->getOperand(1);
8342 HiPart = Val->getOperand(3);
8343 return true;
8344}
8345
8346SDValue SystemZTargetLowering::combineSTORE(
8347 SDNode *N, DAGCombinerInfo &DCI) const {
8348 SelectionDAG &DAG = DCI.DAG;
8349 auto *SN = cast<StoreSDNode>(N);
8350 auto &Op1 = N->getOperand(1);
8351 EVT MemVT = SN->getMemoryVT();
8352
8353 if (SN->getAddressSpace() == SYSTEMZAS::PTR32) {
8354 MVT PtrVT = getPointerTy(DAG.getDataLayout());
8355 MVT StoreNodeVT = SN->getBasePtr().getSimpleValueType();
8356 if (PtrVT != StoreNodeVT) {
8357 SDLoc DL(SN);
8358 SDValue AddrSpaceCast = DAG.getAddrSpaceCast(DL, PtrVT, SN->getBasePtr(),
8359 SYSTEMZAS::PTR32, 0);
8360 return DAG.getStore(SN->getChain(), DL, SN->getValue(), AddrSpaceCast,
8361 SN->getPointerInfo(), SN->getBaseAlign(),
8362 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8363 }
8364 }
8365
8366 // If we have (truncstoreiN (extract_vector_elt X, Y), Z) then it is better
8367 // for the extraction to be done on a vMiN value, so that we can use VSTE.
8368 // If X has wider elements then convert it to:
8369 // (truncstoreiN (extract_vector_elt (bitcast X), Y2), Z).
8370 if (MemVT.isInteger() && SN->isTruncatingStore()) {
8371 if (SDValue Value =
8372 combineTruncateExtract(SDLoc(N), MemVT, SN->getValue(), DCI)) {
8373 DCI.AddToWorklist(Value.getNode());
8374
8375 // Rewrite the store with the new form of stored value.
8376 return DAG.getTruncStore(SN->getChain(), SDLoc(SN), Value,
8377 SN->getBasePtr(), SN->getMemoryVT(),
8378 SN->getMemOperand());
8379 }
8380 }
8381
8382 // combine STORE (LOAD_STACK_GUARD) into MOV_STACKGUARD_DAG
8383 if (Op1->isMachineOpcode() &&
8384 (Op1->getMachineOpcode() == SystemZ::LOAD_STACK_GUARD)) {
8385 // Obtain the frame index the store was targeting.
8386 int FI = cast<FrameIndexSDNode>(SN->getOperand(2))->getIndex();
8387 // Prepare operands of the MOV_STACKGUARD ISD Node - Chain and FrameIndex.
8388 SDValue Ops[] = {SN->getChain(), DAG.getTargetFrameIndex(FI, MVT::i64)};
8389 return DAG.getNode(SystemZISD::MOV_STACKGUARD, SDLoc(SN), MVT::Other, Ops);
8390 }
8391
8392 // Combine STORE (BSWAP) into STRVH/STRV/STRVG/VSTBR
8393 if (!SN->isTruncatingStore() &&
8394 Op1.getOpcode() == ISD::BSWAP &&
8395 Op1.getNode()->hasOneUse() &&
8396 canLoadStoreByteSwapped(Op1.getValueType())) {
8397
8398 SDValue BSwapOp = Op1.getOperand(0);
8399
8400 if (BSwapOp.getValueType() == MVT::i16)
8401 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), MVT::i32, BSwapOp);
8402
8403 SDValue Ops[] = {
8404 N->getOperand(0), BSwapOp, N->getOperand(2)
8405 };
8406
8407 return
8408 DAG.getMemIntrinsicNode(SystemZISD::STRV, SDLoc(N), DAG.getVTList(MVT::Other),
8409 Ops, MemVT, SN->getMemOperand());
8410 }
8411 // Combine STORE (element-swap) into VSTER
8412 if (!SN->isTruncatingStore() &&
8413 Op1.getOpcode() == ISD::VECTOR_SHUFFLE &&
8414 Op1.getNode()->hasOneUse() &&
8415 Subtarget.hasVectorEnhancements2()) {
8416 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op1.getNode());
8417 ArrayRef<int> ShuffleMask = SVN->getMask();
8418 if (isVectorElementSwap(ShuffleMask, Op1.getValueType())) {
8419 SDValue Ops[] = {
8420 N->getOperand(0), Op1.getOperand(0), N->getOperand(2)
8421 };
8422
8423 return DAG.getMemIntrinsicNode(SystemZISD::VSTER, SDLoc(N),
8424 DAG.getVTList(MVT::Other),
8425 Ops, MemVT, SN->getMemOperand());
8426 }
8427 }
8428
8429 // Combine STORE (READCYCLECOUNTER) into STCKF.
8430 if (!SN->isTruncatingStore() &&
8432 Op1.hasOneUse() &&
8433 N->getOperand(0).reachesChainWithoutSideEffects(SDValue(Op1.getNode(), 1))) {
8434 SDValue Ops[] = { Op1.getOperand(0), N->getOperand(2) };
8435 return DAG.getMemIntrinsicNode(SystemZISD::STCKF, SDLoc(N),
8436 DAG.getVTList(MVT::Other),
8437 Ops, MemVT, SN->getMemOperand());
8438 }
8439
8440 // Transform a store of a 128-bit value moved from parts into two stores.
8441 if (SN->isSimple() && ISD::isNormalStore(SN)) {
8442 SDValue LoPart, HiPart;
8443 if ((MemVT == MVT::i128 && isI128MovedFromParts(Op1, LoPart, HiPart)) ||
8444 (MemVT == MVT::f128 && isF128MovedFromParts(Op1, LoPart, HiPart))) {
8445 SDLoc DL(SN);
8446 SDValue Chain0 = DAG.getStore(
8447 SN->getChain(), DL, HiPart, SN->getBasePtr(), SN->getPointerInfo(),
8448 SN->getBaseAlign(), SN->getMemOperand()->getFlags(), SN->getAAInfo());
8449 SDValue Chain1 = DAG.getStore(
8450 SN->getChain(), DL, LoPart,
8451 DAG.getObjectPtrOffset(DL, SN->getBasePtr(), TypeSize::getFixed(8)),
8452 SN->getPointerInfo().getWithOffset(8), SN->getBaseAlign(),
8453 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8454
8455 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chain0, Chain1);
8456 }
8457 }
8458
8459 // Replicate a reg or immediate with VREP instead of scalar multiply or
8460 // immediate load. It seems best to do this during the first DAGCombine as
8461 // it is straight-forward to handle the zero-extend node in the initial
8462 // DAG, and also not worry about the keeping the new MemVT legal (e.g. when
8463 // extracting an i16 element from a v16i8 vector).
8464 if (Subtarget.hasVector() && DCI.Level == BeforeLegalizeTypes &&
8465 isOnlyUsedByStores(Op1, DAG)) {
8466 SDValue Word = SDValue();
8467 EVT WordVT;
8468
8469 // Find a replicated immediate and return it if found in Word and its
8470 // type in WordVT.
8471 auto FindReplicatedImm = [&](ConstantSDNode *C, unsigned TotBytes) {
8472 // Some constants are better handled with a scalar store.
8473 if (C->getAPIntValue().getBitWidth() > 64 || C->isAllOnes() ||
8474 isInt<16>(C->getSExtValue()) || MemVT.getStoreSize() <= 2)
8475 return;
8476
8477 APInt Val = C->getAPIntValue();
8478 // Truncate Val in case of a truncating store.
8479 if (!llvm::isUIntN(TotBytes * 8, Val.getZExtValue())) {
8480 assert(SN->isTruncatingStore() &&
8481 "Non-truncating store and immediate value does not fit?");
8482 Val = Val.trunc(TotBytes * 8);
8483 }
8484
8485 SystemZVectorConstantInfo VCI(APInt(TotBytes * 8, Val.getZExtValue()));
8486 if (VCI.isVectorConstantLegal(Subtarget) &&
8487 VCI.Opcode == SystemZISD::REPLICATE) {
8488 Word = DAG.getConstant(VCI.OpVals[0], SDLoc(SN), MVT::i32);
8489 WordVT = VCI.VecVT.getScalarType();
8490 }
8491 };
8492
8493 // Find a replicated register and return it if found in Word and its type
8494 // in WordVT.
8495 auto FindReplicatedReg = [&](SDValue MulOp) {
8496 EVT MulVT = MulOp.getValueType();
8497 if (MulOp->getOpcode() == ISD::MUL &&
8498 (MulVT == MVT::i16 || MulVT == MVT::i32 || MulVT == MVT::i64)) {
8499 // Find a zero extended value and its type.
8500 SDValue LHS = MulOp->getOperand(0);
8501 if (LHS->getOpcode() == ISD::ZERO_EXTEND)
8502 WordVT = LHS->getOperand(0).getValueType();
8503 else if (LHS->getOpcode() == ISD::AssertZext)
8504 WordVT = cast<VTSDNode>(LHS->getOperand(1))->getVT();
8505 else
8506 return;
8507 // Find a replicating constant, e.g. 0x00010001.
8508 if (auto *C = dyn_cast<ConstantSDNode>(MulOp->getOperand(1))) {
8509 SystemZVectorConstantInfo VCI(
8510 APInt(MulVT.getSizeInBits(), C->getZExtValue()));
8511 if (VCI.isVectorConstantLegal(Subtarget) &&
8512 VCI.Opcode == SystemZISD::REPLICATE && VCI.OpVals[0] == 1 &&
8513 WordVT == VCI.VecVT.getScalarType())
8514 Word = DAG.getZExtOrTrunc(LHS->getOperand(0), SDLoc(SN), WordVT);
8515 }
8516 }
8517 };
8518
8519 if (isa<BuildVectorSDNode>(Op1) &&
8520 DAG.isSplatValue(Op1, true/*AllowUndefs*/)) {
8521 SDValue SplatVal = Op1->getOperand(0);
8522 if (auto *C = dyn_cast<ConstantSDNode>(SplatVal))
8523 FindReplicatedImm(C, SplatVal.getValueType().getStoreSize());
8524 else
8525 FindReplicatedReg(SplatVal);
8526 } else {
8527 if (auto *C = dyn_cast<ConstantSDNode>(Op1))
8528 FindReplicatedImm(C, MemVT.getStoreSize());
8529 else
8530 FindReplicatedReg(Op1);
8531 }
8532
8533 if (Word != SDValue()) {
8534 assert(MemVT.getSizeInBits() % WordVT.getSizeInBits() == 0 &&
8535 "Bad type handling");
8536 unsigned NumElts = MemVT.getSizeInBits() / WordVT.getSizeInBits();
8537 EVT SplatVT = EVT::getVectorVT(*DAG.getContext(), WordVT, NumElts);
8538 SDValue SplatVal = DAG.getSplatVector(SplatVT, SDLoc(SN), Word);
8539 return DAG.getStore(SN->getChain(), SDLoc(SN), SplatVal,
8540 SN->getBasePtr(), SN->getMemOperand());
8541 }
8542 }
8543
8544 return SDValue();
8545}
8546
8547SDValue SystemZTargetLowering::combineVECTOR_SHUFFLE(
8548 SDNode *N, DAGCombinerInfo &DCI) const {
8549 SelectionDAG &DAG = DCI.DAG;
8550 // Combine element-swap (LOAD) into VLER
8551 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8552 N->getOperand(0).hasOneUse() &&
8553 Subtarget.hasVectorEnhancements2()) {
8554 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8555 ArrayRef<int> ShuffleMask = SVN->getMask();
8556 if (isVectorElementSwap(ShuffleMask, N->getValueType(0))) {
8557 SDValue Load = N->getOperand(0);
8558 LoadSDNode *LD = cast<LoadSDNode>(Load);
8559
8560 // Create the element-swapping load.
8561 SDValue Ops[] = {
8562 LD->getChain(), // Chain
8563 LD->getBasePtr() // Ptr
8564 };
8565 SDValue ESLoad =
8566 DAG.getMemIntrinsicNode(SystemZISD::VLER, SDLoc(N),
8567 DAG.getVTList(LD->getValueType(0), MVT::Other),
8568 Ops, LD->getMemoryVT(), LD->getMemOperand());
8569
8570 // First, combine the VECTOR_SHUFFLE away. This makes the value produced
8571 // by the load dead.
8572 DCI.CombineTo(N, ESLoad);
8573
8574 // Next, combine the load away, we give it a bogus result value but a real
8575 // chain result. The result value is dead because the shuffle is dead.
8576 DCI.CombineTo(Load.getNode(), ESLoad, ESLoad.getValue(1));
8577
8578 // Return N so it doesn't get rechecked!
8579 return SDValue(N, 0);
8580 }
8581 }
8582
8583 return SDValue();
8584}
8585
8586SDValue SystemZTargetLowering::combineEXTRACT_VECTOR_ELT(
8587 SDNode *N, DAGCombinerInfo &DCI) const {
8588 SelectionDAG &DAG = DCI.DAG;
8589
8590 if (!Subtarget.hasVector())
8591 return SDValue();
8592
8593 // Look through bitcasts that retain the number of vector elements.
8594 SDValue Op = N->getOperand(0);
8595 if (Op.getOpcode() == ISD::BITCAST &&
8596 Op.getValueType().isVector() &&
8597 Op.getOperand(0).getValueType().isVector() &&
8598 Op.getValueType().getVectorNumElements() ==
8599 Op.getOperand(0).getValueType().getVectorNumElements())
8600 Op = Op.getOperand(0);
8601
8602 // Pull BSWAP out of a vector extraction.
8603 if (Op.getOpcode() == ISD::BSWAP && Op.hasOneUse()) {
8604 EVT VecVT = Op.getValueType();
8605 EVT EltVT = VecVT.getVectorElementType();
8606 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), EltVT,
8607 Op.getOperand(0), N->getOperand(1));
8608 DCI.AddToWorklist(Op.getNode());
8609 Op = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Op);
8610 if (EltVT != N->getValueType(0)) {
8611 DCI.AddToWorklist(Op.getNode());
8612 Op = DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Op);
8613 }
8614 return Op;
8615 }
8616
8617 // Try to simplify a vector extraction.
8618 if (auto *IndexN = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8619 SDValue Op0 = N->getOperand(0);
8620 EVT VecVT = Op0.getValueType();
8621 if (canTreatAsByteVector(VecVT))
8622 return combineExtract(SDLoc(N), N->getValueType(0), VecVT, Op0,
8623 IndexN->getZExtValue(), DCI, false);
8624 }
8625 return SDValue();
8626}
8627
8628SDValue SystemZTargetLowering::combineJOIN_DWORDS(
8629 SDNode *N, DAGCombinerInfo &DCI) const {
8630 SelectionDAG &DAG = DCI.DAG;
8631 // (join_dwords X, X) == (replicate X)
8632 if (N->getOperand(0) == N->getOperand(1))
8633 return DAG.getNode(SystemZISD::REPLICATE, SDLoc(N), N->getValueType(0),
8634 N->getOperand(0));
8635 return SDValue();
8636}
8637
8639 SDValue Chain1 = N1->getOperand(0);
8640 SDValue Chain2 = N2->getOperand(0);
8641
8642 // Trivial case: both nodes take the same chain.
8643 if (Chain1 == Chain2)
8644 return Chain1;
8645
8646 // FIXME - we could handle more complex cases via TokenFactor,
8647 // assuming we can verify that this would not create a cycle.
8648 return SDValue();
8649}
8650
8651SDValue SystemZTargetLowering::combineFP_ROUND(
8652 SDNode *N, DAGCombinerInfo &DCI) const {
8653
8654 if (!Subtarget.hasVector())
8655 return SDValue();
8656
8657 // (fpround (extract_vector_elt X 0))
8658 // (fpround (extract_vector_elt X 1)) ->
8659 // (extract_vector_elt (VROUND X) 0)
8660 // (extract_vector_elt (VROUND X) 2)
8661 //
8662 // This is a special case since the target doesn't really support v2f32s.
8663 unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0;
8664 SelectionDAG &DAG = DCI.DAG;
8665 SDValue Op0 = N->getOperand(OpNo);
8666 if (N->getValueType(0) == MVT::f32 && Op0.hasOneUse() &&
8668 Op0.getOperand(0).getValueType() == MVT::v2f64 &&
8669 Op0.getOperand(1).getOpcode() == ISD::Constant &&
8670 Op0.getConstantOperandVal(1) == 0) {
8671 SDValue Vec = Op0.getOperand(0);
8672 for (auto *U : Vec->users()) {
8673 if (U != Op0.getNode() && U->hasOneUse() &&
8674 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8675 U->getOperand(0) == Vec &&
8676 U->getOperand(1).getOpcode() == ISD::Constant &&
8677 U->getConstantOperandVal(1) == 1) {
8678 SDValue OtherRound = SDValue(*U->user_begin(), 0);
8679 if (OtherRound.getOpcode() == N->getOpcode() &&
8680 OtherRound.getOperand(OpNo) == SDValue(U, 0) &&
8681 OtherRound.getValueType() == MVT::f32) {
8682 SDValue VRound, Chain;
8683 if (N->isStrictFPOpcode()) {
8684 Chain = MergeInputChains(N, OtherRound.getNode());
8685 if (!Chain)
8686 continue;
8687 VRound = DAG.getNode(SystemZISD::STRICT_VROUND, SDLoc(N),
8688 {MVT::v4f32, MVT::Other}, {Chain, Vec});
8689 Chain = VRound.getValue(1);
8690 } else
8691 VRound = DAG.getNode(SystemZISD::VROUND, SDLoc(N),
8692 MVT::v4f32, Vec);
8693 DCI.AddToWorklist(VRound.getNode());
8694 SDValue Extract1 =
8695 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f32,
8696 VRound, DAG.getConstant(2, SDLoc(U), MVT::i32));
8697 DCI.AddToWorklist(Extract1.getNode());
8698 DAG.ReplaceAllUsesOfValueWith(OtherRound, Extract1);
8699 if (Chain)
8700 DAG.ReplaceAllUsesOfValueWith(OtherRound.getValue(1), Chain);
8701 SDValue Extract0 =
8702 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f32,
8703 VRound, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
8704 if (Chain)
8705 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0),
8706 N->getVTList(), Extract0, Chain);
8707 return Extract0;
8708 }
8709 }
8710 }
8711 }
8712 return SDValue();
8713}
8714
8715SDValue SystemZTargetLowering::combineFP_EXTEND(
8716 SDNode *N, DAGCombinerInfo &DCI) const {
8717
8718 if (!Subtarget.hasVector())
8719 return SDValue();
8720
8721 // (fpextend (extract_vector_elt X 0))
8722 // (fpextend (extract_vector_elt X 2)) ->
8723 // (extract_vector_elt (VEXTEND X) 0)
8724 // (extract_vector_elt (VEXTEND X) 1)
8725 //
8726 // This is a special case since the target doesn't really support v2f32s.
8727 unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0;
8728 SelectionDAG &DAG = DCI.DAG;
8729 SDValue Op0 = N->getOperand(OpNo);
8730 if (N->getValueType(0) == MVT::f64 && Op0.hasOneUse() &&
8732 Op0.getOperand(0).getValueType() == MVT::v4f32 &&
8733 Op0.getOperand(1).getOpcode() == ISD::Constant &&
8734 Op0.getConstantOperandVal(1) == 0) {
8735 SDValue Vec = Op0.getOperand(0);
8736 for (auto *U : Vec->users()) {
8737 if (U != Op0.getNode() && U->hasOneUse() &&
8738 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8739 U->getOperand(0) == Vec &&
8740 U->getOperand(1).getOpcode() == ISD::Constant &&
8741 U->getConstantOperandVal(1) == 2) {
8742 SDValue OtherExtend = SDValue(*U->user_begin(), 0);
8743 if (OtherExtend.getOpcode() == N->getOpcode() &&
8744 OtherExtend.getOperand(OpNo) == SDValue(U, 0) &&
8745 OtherExtend.getValueType() == MVT::f64) {
8746 SDValue VExtend, Chain;
8747 if (N->isStrictFPOpcode()) {
8748 Chain = MergeInputChains(N, OtherExtend.getNode());
8749 if (!Chain)
8750 continue;
8751 VExtend = DAG.getNode(SystemZISD::STRICT_VEXTEND, SDLoc(N),
8752 {MVT::v2f64, MVT::Other}, {Chain, Vec});
8753 Chain = VExtend.getValue(1);
8754 } else
8755 VExtend = DAG.getNode(SystemZISD::VEXTEND, SDLoc(N),
8756 MVT::v2f64, Vec);
8757 DCI.AddToWorklist(VExtend.getNode());
8758 SDValue Extract1 =
8759 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f64,
8760 VExtend, DAG.getConstant(1, SDLoc(U), MVT::i32));
8761 DCI.AddToWorklist(Extract1.getNode());
8762 DAG.ReplaceAllUsesOfValueWith(OtherExtend, Extract1);
8763 if (Chain)
8764 DAG.ReplaceAllUsesOfValueWith(OtherExtend.getValue(1), Chain);
8765 SDValue Extract0 =
8766 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f64,
8767 VExtend, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
8768 if (Chain)
8769 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0),
8770 N->getVTList(), Extract0, Chain);
8771 return Extract0;
8772 }
8773 }
8774 }
8775 }
8776 return SDValue();
8777}
8778
8779SDValue SystemZTargetLowering::combineINT_TO_FP(
8780 SDNode *N, DAGCombinerInfo &DCI) const {
8781 if (DCI.Level != BeforeLegalizeTypes)
8782 return SDValue();
8783 SelectionDAG &DAG = DCI.DAG;
8784 LLVMContext &Ctx = *DAG.getContext();
8785 unsigned Opcode = N->getOpcode();
8786 EVT OutVT = N->getValueType(0);
8787 Type *OutLLVMTy = OutVT.getTypeForEVT(Ctx);
8788 SDValue Op = N->getOperand(0);
8789 unsigned OutScalarBits = OutLLVMTy->getScalarSizeInBits();
8790 unsigned InScalarBits = Op->getValueType(0).getScalarSizeInBits();
8791
8792 // Insert an extension before type-legalization to avoid scalarization, e.g.:
8793 // v2f64 = uint_to_fp v2i16
8794 // =>
8795 // v2f64 = uint_to_fp (v2i64 zero_extend v2i16)
8796 if (OutLLVMTy->isVectorTy() && OutScalarBits > InScalarBits &&
8797 OutScalarBits <= 64) {
8798 unsigned NumElts = cast<FixedVectorType>(OutLLVMTy)->getNumElements();
8799 EVT ExtVT = EVT::getVectorVT(
8800 Ctx, EVT::getIntegerVT(Ctx, OutLLVMTy->getScalarSizeInBits()), NumElts);
8801 unsigned ExtOpcode =
8803 SDValue ExtOp = DAG.getNode(ExtOpcode, SDLoc(N), ExtVT, Op);
8804 return DAG.getNode(Opcode, SDLoc(N), OutVT, ExtOp);
8805 }
8806 return SDValue();
8807}
8808
8809SDValue SystemZTargetLowering::combineFCOPYSIGN(
8810 SDNode *N, DAGCombinerInfo &DCI) const {
8811 SelectionDAG &DAG = DCI.DAG;
8812 EVT VT = N->getValueType(0);
8813 SDValue ValOp = N->getOperand(0);
8814 SDValue SignOp = N->getOperand(1);
8815
8816 // Remove the rounding which is not needed.
8817 if (SignOp.getOpcode() == ISD::FP_ROUND) {
8818 SDValue WideOp = SignOp.getOperand(0);
8819 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, ValOp, WideOp);
8820 }
8821
8822 return SDValue();
8823}
8824
8825SDValue SystemZTargetLowering::combineBSWAP(
8826 SDNode *N, DAGCombinerInfo &DCI) const {
8827 SelectionDAG &DAG = DCI.DAG;
8828 // Combine BSWAP (LOAD) into LRVH/LRV/LRVG/VLBR
8829 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8830 N->getOperand(0).hasOneUse() &&
8831 canLoadStoreByteSwapped(N->getValueType(0))) {
8832 SDValue Load = N->getOperand(0);
8833 LoadSDNode *LD = cast<LoadSDNode>(Load);
8834
8835 // Create the byte-swapping load.
8836 SDValue Ops[] = {
8837 LD->getChain(), // Chain
8838 LD->getBasePtr() // Ptr
8839 };
8840 EVT LoadVT = N->getValueType(0);
8841 if (LoadVT == MVT::i16)
8842 LoadVT = MVT::i32;
8843 SDValue BSLoad =
8844 DAG.getMemIntrinsicNode(SystemZISD::LRV, SDLoc(N),
8845 DAG.getVTList(LoadVT, MVT::Other),
8846 Ops, LD->getMemoryVT(), LD->getMemOperand());
8847
8848 // If this is an i16 load, insert the truncate.
8849 SDValue ResVal = BSLoad;
8850 if (N->getValueType(0) == MVT::i16)
8851 ResVal = DAG.getNode(ISD::TRUNCATE, SDLoc(N), MVT::i16, BSLoad);
8852
8853 // First, combine the bswap away. This makes the value produced by the
8854 // load dead.
8855 DCI.CombineTo(N, ResVal);
8856
8857 // Next, combine the load away, we give it a bogus result value but a real
8858 // chain result. The result value is dead because the bswap is dead.
8859 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8860
8861 // Return N so it doesn't get rechecked!
8862 return SDValue(N, 0);
8863 }
8864
8865 // Look through bitcasts that retain the number of vector elements.
8866 SDValue Op = N->getOperand(0);
8867 if (Op.getOpcode() == ISD::BITCAST &&
8868 Op.getValueType().isVector() &&
8869 Op.getOperand(0).getValueType().isVector() &&
8870 Op.getValueType().getVectorNumElements() ==
8871 Op.getOperand(0).getValueType().getVectorNumElements())
8872 Op = Op.getOperand(0);
8873
8874 // Push BSWAP into a vector insertion if at least one side then simplifies.
8875 if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT && Op.hasOneUse()) {
8876 SDValue Vec = Op.getOperand(0);
8877 SDValue Elt = Op.getOperand(1);
8878 SDValue Idx = Op.getOperand(2);
8879
8881 Vec.getOpcode() == ISD::BSWAP || Vec.isUndef() ||
8883 Elt.getOpcode() == ISD::BSWAP || Elt.isUndef() ||
8884 (canLoadStoreByteSwapped(N->getValueType(0)) &&
8885 ISD::isNON_EXTLoad(Elt.getNode()) && Elt.hasOneUse())) {
8886 EVT VecVT = N->getValueType(0);
8887 EVT EltVT = N->getValueType(0).getVectorElementType();
8888 if (VecVT != Vec.getValueType()) {
8889 Vec = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Vec);
8890 DCI.AddToWorklist(Vec.getNode());
8891 }
8892 if (EltVT != Elt.getValueType()) {
8893 Elt = DAG.getNode(ISD::BITCAST, SDLoc(N), EltVT, Elt);
8894 DCI.AddToWorklist(Elt.getNode());
8895 }
8896 Vec = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Vec);
8897 DCI.AddToWorklist(Vec.getNode());
8898 Elt = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Elt);
8899 DCI.AddToWorklist(Elt.getNode());
8900 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VecVT,
8901 Vec, Elt, Idx);
8902 }
8903 }
8904
8905 // Push BSWAP into a vector shuffle if at least one side then simplifies.
8906 ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(Op);
8907 if (SV && Op.hasOneUse()) {
8908 SDValue Op0 = Op.getOperand(0);
8909 SDValue Op1 = Op.getOperand(1);
8910
8912 Op0.getOpcode() == ISD::BSWAP || Op0.isUndef() ||
8914 Op1.getOpcode() == ISD::BSWAP || Op1.isUndef()) {
8915 EVT VecVT = N->getValueType(0);
8916 if (VecVT != Op0.getValueType()) {
8917 Op0 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op0);
8918 DCI.AddToWorklist(Op0.getNode());
8919 }
8920 if (VecVT != Op1.getValueType()) {
8921 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), VecVT, Op1);
8922 DCI.AddToWorklist(Op1.getNode());
8923 }
8924 Op0 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op0);
8925 DCI.AddToWorklist(Op0.getNode());
8926 Op1 = DAG.getNode(ISD::BSWAP, SDLoc(N), VecVT, Op1);
8927 DCI.AddToWorklist(Op1.getNode());
8928 return DAG.getVectorShuffle(VecVT, SDLoc(N), Op0, Op1, SV->getMask());
8929 }
8930 }
8931
8932 return SDValue();
8933}
8934
8935SDValue SystemZTargetLowering::combineSETCC(
8936 SDNode *N, DAGCombinerInfo &DCI) const {
8937 SelectionDAG &DAG = DCI.DAG;
8938 const ISD::CondCode CC = N->getOperandCondCode(2);
8939 const SDValue LHS = N->getOperand(0);
8940 const SDValue RHS = N->getOperand(1);
8941 bool CmpNull = isNullConstant(RHS);
8942 bool CmpAllOnes = isAllOnesConstant(RHS);
8943 EVT VT = N->getValueType(0);
8944 SDLoc DL(N);
8945
8946 // Match icmp_eq/ne(bitcast(icmp(X,Y)),0/-1) reduction patterns, and
8947 // change the outer compare to a i128 compare. This will normally
8948 // allow the reduction to be recognized in adjustICmp128, and even if
8949 // not, the i128 compare will still generate better code.
8950 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && (CmpNull || CmpAllOnes)) {
8952 if (Src.getOpcode() == ISD::SETCC &&
8953 Src.getValueType().isFixedLengthVector() &&
8954 Src.getValueType().getScalarType() == MVT::i1) {
8955 EVT CmpVT = Src.getOperand(0).getValueType();
8956 if (CmpVT.getSizeInBits() == 128) {
8957 EVT IntVT = CmpVT.changeVectorElementTypeToInteger();
8958 SDValue LHS =
8959 DAG.getBitcast(MVT::i128, DAG.getSExtOrTrunc(Src, DL, IntVT));
8960 SDValue RHS = CmpNull ? DAG.getConstant(0, DL, MVT::i128)
8961 : DAG.getAllOnesConstant(DL, MVT::i128);
8962 return DAG.getNode(ISD::SETCC, DL, VT, LHS, RHS, N->getOperand(2),
8963 N->getFlags());
8964 }
8965 }
8966 }
8967
8968 return SDValue();
8969}
8970
8971static std::pair<SDValue, int> findCCUse(const SDValue &Val,
8972 unsigned Depth = 0) {
8973 // Limit depth of potentially exponential walk.
8974 if (Depth > 5)
8975 return std::make_pair(SDValue(), SystemZ::CCMASK_NONE);
8976
8977 switch (Val.getOpcode()) {
8978 default:
8979 return std::make_pair(SDValue(), SystemZ::CCMASK_NONE);
8980 case SystemZISD::IPM:
8981 if (Val.getOperand(0).getOpcode() == SystemZISD::CLC ||
8982 Val.getOperand(0).getOpcode() == SystemZISD::STRCMP)
8983 return std::make_pair(Val.getOperand(0), SystemZ::CCMASK_ICMP);
8984 return std::make_pair(Val.getOperand(0), SystemZ::CCMASK_ANY);
8985 case SystemZISD::SELECT_CCMASK: {
8986 SDValue Op4CCReg = Val.getOperand(4);
8987 if (Op4CCReg.getOpcode() == SystemZISD::ICMP ||
8988 Op4CCReg.getOpcode() == SystemZISD::TM) {
8989 auto [OpCC, OpCCValid] = findCCUse(Op4CCReg.getOperand(0), Depth + 1);
8990 if (OpCC != SDValue())
8991 return std::make_pair(OpCC, OpCCValid);
8992 }
8993 auto *CCValid = dyn_cast<ConstantSDNode>(Val.getOperand(2));
8994 if (!CCValid)
8995 return std::make_pair(SDValue(), SystemZ::CCMASK_NONE);
8996 int CCValidVal = CCValid->getZExtValue();
8997 return std::make_pair(Op4CCReg, CCValidVal);
8998 }
8999 case ISD::ADD:
9000 case ISD::AND:
9001 case ISD::OR:
9002 case ISD::XOR:
9003 case ISD::SHL:
9004 case ISD::SRA:
9005 case ISD::SRL:
9006 auto [Op0CC, Op0CCValid] = findCCUse(Val.getOperand(0), Depth + 1);
9007 if (Op0CC != SDValue())
9008 return std::make_pair(Op0CC, Op0CCValid);
9009 return findCCUse(Val.getOperand(1), Depth + 1);
9010 }
9011}
9012
9013static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask,
9014 SelectionDAG &DAG);
9015
9017 SelectionDAG &DAG) {
9018 SDLoc DL(Val);
9019 auto Opcode = Val.getOpcode();
9020 switch (Opcode) {
9021 default:
9022 return {};
9023 case ISD::Constant:
9024 return {Val, Val, Val, Val};
9025 case SystemZISD::IPM: {
9026 SDValue IPMOp0 = Val.getOperand(0);
9027 if (IPMOp0 != CC)
9028 return {};
9029 SmallVector<SDValue, 4> ShiftedCCVals;
9030 for (auto CC : {0, 1, 2, 3})
9031 ShiftedCCVals.emplace_back(
9032 DAG.getConstant((CC << SystemZ::IPM_CC), DL, MVT::i32));
9033 return ShiftedCCVals;
9034 }
9035 case SystemZISD::SELECT_CCMASK: {
9036 SDValue TrueVal = Val.getOperand(0), FalseVal = Val.getOperand(1);
9037 auto *CCValid = dyn_cast<ConstantSDNode>(Val.getOperand(2));
9038 auto *CCMask = dyn_cast<ConstantSDNode>(Val.getOperand(3));
9039 if (!CCValid || !CCMask)
9040 return {};
9041
9042 int CCValidVal = CCValid->getZExtValue();
9043 int CCMaskVal = CCMask->getZExtValue();
9044 // Pruning search tree early - Moving CC test and combineCCMask ahead of
9045 // recursive call to simplifyAssumingCCVal.
9046 SDValue Op4CCReg = Val.getOperand(4);
9047 if (Op4CCReg != CC)
9048 combineCCMask(Op4CCReg, CCValidVal, CCMaskVal, DAG);
9049 if (Op4CCReg != CC)
9050 return {};
9051 const auto &&TrueSDVals = simplifyAssumingCCVal(TrueVal, CC, DAG);
9052 const auto &&FalseSDVals = simplifyAssumingCCVal(FalseVal, CC, DAG);
9053 if (TrueSDVals.empty() || FalseSDVals.empty())
9054 return {};
9055 SmallVector<SDValue, 4> MergedSDVals;
9056 for (auto &CCVal : {0, 1, 2, 3})
9057 MergedSDVals.emplace_back(((CCMaskVal & (1 << (3 - CCVal))) != 0)
9058 ? TrueSDVals[CCVal]
9059 : FalseSDVals[CCVal]);
9060 return MergedSDVals;
9061 }
9062 case ISD::ADD:
9063 case ISD::AND:
9064 case ISD::OR:
9065 case ISD::XOR:
9066 case ISD::SRA:
9067 // Avoid introducing CC spills (because ADD/AND/OR/XOR/SRA
9068 // would clobber CC).
9069 if (!Val.hasOneUse())
9070 return {};
9071 [[fallthrough]];
9072 case ISD::SHL:
9073 case ISD::SRL:
9074 SDValue Op0 = Val.getOperand(0), Op1 = Val.getOperand(1);
9075 const auto &&Op0SDVals = simplifyAssumingCCVal(Op0, CC, DAG);
9076 const auto &&Op1SDVals = simplifyAssumingCCVal(Op1, CC, DAG);
9077 if (Op0SDVals.empty() || Op1SDVals.empty())
9078 return {};
9079 SmallVector<SDValue, 4> BinaryOpSDVals;
9080 for (auto CCVal : {0, 1, 2, 3})
9081 BinaryOpSDVals.emplace_back(DAG.getNode(
9082 Opcode, DL, Val.getValueType(), Op0SDVals[CCVal], Op1SDVals[CCVal]));
9083 return BinaryOpSDVals;
9084 }
9085}
9086
9087static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask,
9088 SelectionDAG &DAG) {
9089 // We have a SELECT_CCMASK or BR_CCMASK comparing the condition code
9090 // set by the CCReg instruction using the CCValid / CCMask masks,
9091 // If the CCReg instruction is itself a ICMP / TM testing the condition
9092 // code set by some other instruction, see whether we can directly
9093 // use that condition code.
9094 auto *CCNode = CCReg.getNode();
9095 if (!CCNode)
9096 return false;
9097
9098 if (CCNode->getOpcode() == SystemZISD::TM) {
9099 if (CCValid != SystemZ::CCMASK_TM)
9100 return false;
9101 auto emulateTMCCMask = [](const SDValue &Op0Val, const SDValue &Op1Val) {
9102 auto *Op0Node = dyn_cast<ConstantSDNode>(Op0Val.getNode());
9103 auto *Op1Node = dyn_cast<ConstantSDNode>(Op1Val.getNode());
9104 if (!Op0Node || !Op1Node)
9105 return -1;
9106 auto Op0APVal = Op0Node->getAPIntValue();
9107 auto Op1APVal = Op1Node->getAPIntValue();
9108 auto Result = Op0APVal & Op1APVal;
9109 bool AllOnes = Result == Op1APVal;
9110 bool AllZeros = Result == 0;
9111 bool IsLeftMostBitSet = Result[Op1APVal.getActiveBits() - 1] != 0;
9112 return AllZeros ? 0 : AllOnes ? 3 : IsLeftMostBitSet ? 2 : 1;
9113 };
9114 SDValue Op0 = CCNode->getOperand(0);
9115 SDValue Op1 = CCNode->getOperand(1);
9116 auto [Op0CC, Op0CCValid] = findCCUse(Op0);
9117 if (Op0CC == SDValue())
9118 return false;
9119 const auto &&Op0SDVals = simplifyAssumingCCVal(Op0, Op0CC, DAG);
9120 const auto &&Op1SDVals = simplifyAssumingCCVal(Op1, Op0CC, DAG);
9121 if (Op0SDVals.empty() || Op1SDVals.empty())
9122 return false;
9123 int NewCCMask = 0;
9124 for (auto CC : {0, 1, 2, 3}) {
9125 auto CCVal = emulateTMCCMask(Op0SDVals[CC], Op1SDVals[CC]);
9126 if (CCVal < 0)
9127 return false;
9128 NewCCMask <<= 1;
9129 NewCCMask |= (CCMask & (1 << (3 - CCVal))) != 0;
9130 }
9131 NewCCMask &= Op0CCValid;
9132 CCReg = Op0CC;
9133 CCMask = NewCCMask;
9134 CCValid = Op0CCValid;
9135 return true;
9136 }
9137 if (CCNode->getOpcode() != SystemZISD::ICMP ||
9138 CCValid != SystemZ::CCMASK_ICMP)
9139 return false;
9140
9141 SDValue CmpOp0 = CCNode->getOperand(0);
9142 SDValue CmpOp1 = CCNode->getOperand(1);
9143 SDValue CmpOp2 = CCNode->getOperand(2);
9144 auto [Op0CC, Op0CCValid] = findCCUse(CmpOp0);
9145 if (Op0CC != SDValue()) {
9146 const auto &&Op0SDVals = simplifyAssumingCCVal(CmpOp0, Op0CC, DAG);
9147 const auto &&Op1SDVals = simplifyAssumingCCVal(CmpOp1, Op0CC, DAG);
9148 if (Op0SDVals.empty() || Op1SDVals.empty())
9149 return false;
9150
9151 auto *CmpType = dyn_cast<ConstantSDNode>(CmpOp2);
9152 auto CmpTypeVal = CmpType->getZExtValue();
9153 const auto compareCCSigned = [&CmpTypeVal](const SDValue &Op0Val,
9154 const SDValue &Op1Val) {
9155 auto *Op0Node = dyn_cast<ConstantSDNode>(Op0Val.getNode());
9156 auto *Op1Node = dyn_cast<ConstantSDNode>(Op1Val.getNode());
9157 if (!Op0Node || !Op1Node)
9158 return -1;
9159 auto Op0APVal = Op0Node->getAPIntValue();
9160 auto Op1APVal = Op1Node->getAPIntValue();
9161 if (CmpTypeVal == SystemZICMP::SignedOnly)
9162 return Op0APVal == Op1APVal ? 0 : Op0APVal.slt(Op1APVal) ? 1 : 2;
9163 return Op0APVal == Op1APVal ? 0 : Op0APVal.ult(Op1APVal) ? 1 : 2;
9164 };
9165 int NewCCMask = 0;
9166 for (auto CC : {0, 1, 2, 3}) {
9167 auto CCVal = compareCCSigned(Op0SDVals[CC], Op1SDVals[CC]);
9168 if (CCVal < 0)
9169 return false;
9170 NewCCMask <<= 1;
9171 NewCCMask |= (CCMask & (1 << (3 - CCVal))) != 0;
9172 }
9173 NewCCMask &= Op0CCValid;
9174 CCMask = NewCCMask;
9175 CCReg = Op0CC;
9176 CCValid = Op0CCValid;
9177 return true;
9178 }
9179
9180 return false;
9181}
9182
9183// Merging versus split in multiple branches cost.
9186 const Value *Lhs,
9187 const Value *Rhs,
9188 const Function *) const {
9189 const auto isFlagOutOpCC = [](const Value *V) {
9190 using namespace llvm::PatternMatch;
9191 const Value *RHSVal;
9192 const APInt *RHSC;
9193 if (const auto *I = dyn_cast<Instruction>(V)) {
9194 // PatternMatch.h provides concise tree-based pattern match of llvm IR.
9195 if (match(I->getOperand(0), m_And(m_Value(RHSVal), m_APInt(RHSC))) ||
9196 match(I, m_Cmp(m_Value(RHSVal), m_APInt(RHSC)))) {
9197 if (const auto *CB = dyn_cast<CallBase>(RHSVal)) {
9198 if (CB->isInlineAsm()) {
9199 const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
9200 return IA && IA->getConstraintString().contains("{@cc}");
9201 }
9202 }
9203 }
9204 }
9205 return false;
9206 };
9207 // Pattern (ICmp %asm) or (ICmp (And %asm)).
9208 // Cost of longest dependency chain (ICmp, And) is 2. CostThreshold or
9209 // BaseCost can be set >=2. If cost of instruction <= CostThreshold
9210 // conditionals will be merged or else conditionals will be split.
9211 if (isFlagOutOpCC(Lhs) && isFlagOutOpCC(Rhs))
9212 return {3, 0, -1};
9213 // Default.
9214 return {-1, -1, -1};
9215}
9216
9217SDValue SystemZTargetLowering::combineBR_CCMASK(SDNode *N,
9218 DAGCombinerInfo &DCI) const {
9219 SelectionDAG &DAG = DCI.DAG;
9220
9221 // Combine BR_CCMASK (ICMP (SELECT_CCMASK)) into a single BR_CCMASK.
9222 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1));
9223 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2));
9224 if (!CCValid || !CCMask)
9225 return SDValue();
9226
9227 int CCValidVal = CCValid->getZExtValue();
9228 int CCMaskVal = CCMask->getZExtValue();
9229 SDValue Chain = N->getOperand(0);
9230 SDValue CCReg = N->getOperand(4);
9231 // If combineCMask was able to merge or simplify ccvalid or ccmask, re-emit
9232 // the modified BR_CCMASK with the new values.
9233 // In order to avoid conditional branches with full or empty cc masks, do not
9234 // do this if ccmask is 0 or equal to ccvalid.
9235 if (combineCCMask(CCReg, CCValidVal, CCMaskVal, DAG) && CCMaskVal != 0 &&
9236 CCMaskVal != CCValidVal)
9237 return DAG.getNode(SystemZISD::BR_CCMASK, SDLoc(N), N->getValueType(0),
9238 Chain,
9239 DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32),
9240 DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32),
9241 N->getOperand(3), CCReg);
9242 return SDValue();
9243}
9244
9245SDValue SystemZTargetLowering::combineSELECT_CCMASK(
9246 SDNode *N, DAGCombinerInfo &DCI) const {
9247 SelectionDAG &DAG = DCI.DAG;
9248
9249 // Combine SELECT_CCMASK (ICMP (SELECT_CCMASK)) into a single SELECT_CCMASK.
9250 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(2));
9251 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(3));
9252 if (!CCValid || !CCMask)
9253 return SDValue();
9254
9255 int CCValidVal = CCValid->getZExtValue();
9256 int CCMaskVal = CCMask->getZExtValue();
9257 SDValue CCReg = N->getOperand(4);
9258
9259 bool IsCombinedCCReg = combineCCMask(CCReg, CCValidVal, CCMaskVal, DAG);
9260
9261 // Populate SDVals vector for each condition code ccval for given Val, which
9262 // can again be another nested select_ccmask with the same CC.
9263 const auto constructCCSDValsFromSELECT = [&CCReg](SDValue &Val) {
9264 if (Val.getOpcode() == SystemZISD::SELECT_CCMASK) {
9266 if (Val.getOperand(4) != CCReg)
9267 return SmallVector<SDValue, 4>{};
9268 SDValue TrueVal = Val.getOperand(0), FalseVal = Val.getOperand(1);
9269 auto *CCMask = dyn_cast<ConstantSDNode>(Val.getOperand(3));
9270 if (!CCMask)
9271 return SmallVector<SDValue, 4>{};
9272
9273 int CCMaskVal = CCMask->getZExtValue();
9274 for (auto &CC : {0, 1, 2, 3})
9275 Res.emplace_back(((CCMaskVal & (1 << (3 - CC))) != 0) ? TrueVal
9276 : FalseVal);
9277 return Res;
9278 }
9279 return SmallVector<SDValue, 4>{Val, Val, Val, Val};
9280 };
9281 // Attempting to optimize TrueVal/FalseVal in outermost select_ccmask either
9282 // with CCReg found by combineCCMask or original CCReg.
9283 SDValue TrueVal = N->getOperand(0);
9284 SDValue FalseVal = N->getOperand(1);
9285 auto &&TrueSDVals = simplifyAssumingCCVal(TrueVal, CCReg, DAG);
9286 auto &&FalseSDVals = simplifyAssumingCCVal(FalseVal, CCReg, DAG);
9287 // TrueSDVals/FalseSDVals might be empty in case of non-constant
9288 // TrueVal/FalseVal for select_ccmask, which can not be optimized further.
9289 if (TrueSDVals.empty())
9290 TrueSDVals = constructCCSDValsFromSELECT(TrueVal);
9291 if (FalseSDVals.empty())
9292 FalseSDVals = constructCCSDValsFromSELECT(FalseVal);
9293 if (!TrueSDVals.empty() && !FalseSDVals.empty()) {
9294 SmallSet<SDValue, 4> MergedSDValsSet;
9295 // Ignoring CC values outside CCValiid.
9296 for (auto CC : {0, 1, 2, 3}) {
9297 if ((CCValidVal & ((1 << (3 - CC)))) != 0)
9298 MergedSDValsSet.insert(((CCMaskVal & (1 << (3 - CC))) != 0)
9299 ? TrueSDVals[CC]
9300 : FalseSDVals[CC]);
9301 }
9302 if (MergedSDValsSet.size() == 1)
9303 return *MergedSDValsSet.begin();
9304 if (MergedSDValsSet.size() == 2) {
9305 auto BeginIt = MergedSDValsSet.begin();
9306 SDValue NewTrueVal = *BeginIt, NewFalseVal = *next(BeginIt);
9307 if (NewTrueVal == FalseVal || NewFalseVal == TrueVal)
9308 std::swap(NewTrueVal, NewFalseVal);
9309 int NewCCMask = 0;
9310 for (auto CC : {0, 1, 2, 3}) {
9311 NewCCMask <<= 1;
9312 NewCCMask |= ((CCMaskVal & (1 << (3 - CC))) != 0)
9313 ? (TrueSDVals[CC] == NewTrueVal)
9314 : (FalseSDVals[CC] == NewTrueVal);
9315 }
9316 CCMaskVal = NewCCMask;
9317 CCMaskVal &= CCValidVal;
9318 TrueVal = NewTrueVal;
9319 FalseVal = NewFalseVal;
9320 IsCombinedCCReg = true;
9321 }
9322 }
9323 // If the condition is trivially false or trivially true after
9324 // combineCCMask, just collapse this SELECT_CCMASK to the indicated value
9325 // (possibly modified by constructCCSDValsFromSELECT).
9326 if (CCMaskVal == 0)
9327 return FalseVal;
9328 if (CCMaskVal == CCValidVal)
9329 return TrueVal;
9330
9331 if (IsCombinedCCReg)
9332 return DAG.getNode(
9333 SystemZISD::SELECT_CCMASK, SDLoc(N), N->getValueType(0), TrueVal,
9334 FalseVal, DAG.getTargetConstant(CCValidVal, SDLoc(N), MVT::i32),
9335 DAG.getTargetConstant(CCMaskVal, SDLoc(N), MVT::i32), CCReg);
9336
9337 return SDValue();
9338}
9339
9340SDValue SystemZTargetLowering::combineGET_CCMASK(
9341 SDNode *N, DAGCombinerInfo &DCI) const {
9342
9343 // Optimize away GET_CCMASK (SELECT_CCMASK) if the CC masks are compatible
9344 auto *CCValid = dyn_cast<ConstantSDNode>(N->getOperand(1));
9345 auto *CCMask = dyn_cast<ConstantSDNode>(N->getOperand(2));
9346 if (!CCValid || !CCMask)
9347 return SDValue();
9348 int CCValidVal = CCValid->getZExtValue();
9349 int CCMaskVal = CCMask->getZExtValue();
9350
9351 SDValue Select = N->getOperand(0);
9352 if (Select->getOpcode() == ISD::TRUNCATE)
9353 Select = Select->getOperand(0);
9354 if (Select->getOpcode() != SystemZISD::SELECT_CCMASK)
9355 return SDValue();
9356
9357 auto *SelectCCValid = dyn_cast<ConstantSDNode>(Select->getOperand(2));
9358 auto *SelectCCMask = dyn_cast<ConstantSDNode>(Select->getOperand(3));
9359 if (!SelectCCValid || !SelectCCMask)
9360 return SDValue();
9361 int SelectCCValidVal = SelectCCValid->getZExtValue();
9362 int SelectCCMaskVal = SelectCCMask->getZExtValue();
9363
9364 auto *TrueVal = dyn_cast<ConstantSDNode>(Select->getOperand(0));
9365 auto *FalseVal = dyn_cast<ConstantSDNode>(Select->getOperand(1));
9366 if (!TrueVal || !FalseVal)
9367 return SDValue();
9368 if (TrueVal->getZExtValue() == 1 && FalseVal->getZExtValue() == 0)
9369 ;
9370 else if (TrueVal->getZExtValue() == 0 && FalseVal->getZExtValue() == 1)
9371 SelectCCMaskVal ^= SelectCCValidVal;
9372 else
9373 return SDValue();
9374
9375 if (SelectCCValidVal & ~CCValidVal)
9376 return SDValue();
9377 if (SelectCCMaskVal != (CCMaskVal & SelectCCValidVal))
9378 return SDValue();
9379
9380 return Select->getOperand(4);
9381}
9382
9383SDValue SystemZTargetLowering::combineIntDIVREM(
9384 SDNode *N, DAGCombinerInfo &DCI) const {
9385 SelectionDAG &DAG = DCI.DAG;
9386 EVT VT = N->getValueType(0);
9387 // In the case where the divisor is a vector of constants a cheaper
9388 // sequence of instructions can replace the divide. BuildSDIV is called to
9389 // do this during DAG combining, but it only succeeds when it can build a
9390 // multiplication node. The only option for SystemZ is ISD::SMUL_LOHI, and
9391 // since it is not Legal but Custom it can only happen before
9392 // legalization. Therefore we must scalarize this early before Combine
9393 // 1. For widened vectors, this is already the result of type legalization.
9394 if (DCI.Level == BeforeLegalizeTypes && VT.isVector() && isTypeLegal(VT) &&
9395 DAG.isConstantIntBuildVectorOrConstantInt(N->getOperand(1)))
9396 return DAG.UnrollVectorOp(N);
9397 return SDValue();
9398}
9399
9400
9401// Transform a right shift of a multiply-and-add into a multiply-and-add-high.
9402// This is closely modeled after the common-code combineShiftToMULH.
9403SDValue SystemZTargetLowering::combineShiftToMulAddHigh(
9404 SDNode *N, DAGCombinerInfo &DCI) const {
9405 SelectionDAG &DAG = DCI.DAG;
9406 SDLoc DL(N);
9407
9408 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
9409 "SRL or SRA node is required here!");
9410
9411 if (!Subtarget.hasVector())
9412 return SDValue();
9413
9414 // Check the shift amount. Proceed with the transformation if the shift
9415 // amount is constant.
9416 ConstantSDNode *ShiftAmtSrc = isConstOrConstSplat(N->getOperand(1));
9417 if (!ShiftAmtSrc)
9418 return SDValue();
9419
9420 // The operation feeding into the shift must be an add.
9421 SDValue ShiftOperand = N->getOperand(0);
9422 if (ShiftOperand.getOpcode() != ISD::ADD)
9423 return SDValue();
9424
9425 // One operand of the add must be a multiply.
9426 SDValue MulOp = ShiftOperand.getOperand(0);
9427 SDValue AddOp = ShiftOperand.getOperand(1);
9428 if (MulOp.getOpcode() != ISD::MUL) {
9429 if (AddOp.getOpcode() != ISD::MUL)
9430 return SDValue();
9431 std::swap(MulOp, AddOp);
9432 }
9433
9434 // All operands must be equivalent extend nodes.
9435 SDValue LeftOp = MulOp.getOperand(0);
9436 SDValue RightOp = MulOp.getOperand(1);
9437
9438 bool IsSignExt = LeftOp.getOpcode() == ISD::SIGN_EXTEND;
9439 bool IsZeroExt = LeftOp.getOpcode() == ISD::ZERO_EXTEND;
9440
9441 if (!IsSignExt && !IsZeroExt)
9442 return SDValue();
9443
9444 EVT NarrowVT = LeftOp.getOperand(0).getValueType();
9445 unsigned NarrowVTSize = NarrowVT.getScalarSizeInBits();
9446
9447 SDValue MulhRightOp;
9448 if (ConstantSDNode *Constant = isConstOrConstSplat(RightOp)) {
9449 unsigned ActiveBits = IsSignExt
9450 ? Constant->getAPIntValue().getSignificantBits()
9451 : Constant->getAPIntValue().getActiveBits();
9452 if (ActiveBits > NarrowVTSize)
9453 return SDValue();
9454 MulhRightOp = DAG.getConstant(
9455 Constant->getAPIntValue().trunc(NarrowVT.getScalarSizeInBits()), DL,
9456 NarrowVT);
9457 } else {
9458 if (LeftOp.getOpcode() != RightOp.getOpcode())
9459 return SDValue();
9460 // Check that the two extend nodes are the same type.
9461 if (NarrowVT != RightOp.getOperand(0).getValueType())
9462 return SDValue();
9463 MulhRightOp = RightOp.getOperand(0);
9464 }
9465
9466 SDValue MulhAddOp;
9467 if (ConstantSDNode *Constant = isConstOrConstSplat(AddOp)) {
9468 unsigned ActiveBits = IsSignExt
9469 ? Constant->getAPIntValue().getSignificantBits()
9470 : Constant->getAPIntValue().getActiveBits();
9471 if (ActiveBits > NarrowVTSize)
9472 return SDValue();
9473 MulhAddOp = DAG.getConstant(
9474 Constant->getAPIntValue().trunc(NarrowVT.getScalarSizeInBits()), DL,
9475 NarrowVT);
9476 } else {
9477 if (LeftOp.getOpcode() != AddOp.getOpcode())
9478 return SDValue();
9479 // Check that the two extend nodes are the same type.
9480 if (NarrowVT != AddOp.getOperand(0).getValueType())
9481 return SDValue();
9482 MulhAddOp = AddOp.getOperand(0);
9483 }
9484
9485 EVT WideVT = LeftOp.getValueType();
9486 // Proceed with the transformation if the wide types match.
9487 assert((WideVT == RightOp.getValueType()) &&
9488 "Cannot have a multiply node with two different operand types.");
9489 assert((WideVT == AddOp.getValueType()) &&
9490 "Cannot have an add node with two different operand types.");
9491
9492 // Proceed with the transformation if the wide type is twice as large
9493 // as the narrow type.
9494 if (WideVT.getScalarSizeInBits() != 2 * NarrowVTSize)
9495 return SDValue();
9496
9497 // Check the shift amount with the narrow type size.
9498 // Proceed with the transformation if the shift amount is the width
9499 // of the narrow type.
9500 unsigned ShiftAmt = ShiftAmtSrc->getZExtValue();
9501 if (ShiftAmt != NarrowVTSize)
9502 return SDValue();
9503
9504 // Proceed if we support the multiply-and-add-high operation.
9505 if (!(NarrowVT == MVT::v16i8 || NarrowVT == MVT::v8i16 ||
9506 NarrowVT == MVT::v4i32 ||
9507 (Subtarget.hasVectorEnhancements3() &&
9508 (NarrowVT == MVT::v2i64 || NarrowVT == MVT::i128))))
9509 return SDValue();
9510
9511 // Emit the VMAH (signed) or VMALH (unsigned) operation.
9512 SDValue Result = DAG.getNode(IsSignExt ? SystemZISD::VMAH : SystemZISD::VMALH,
9513 DL, NarrowVT, LeftOp.getOperand(0),
9514 MulhRightOp, MulhAddOp);
9515 bool IsSigned = N->getOpcode() == ISD::SRA;
9516 return DAG.getExtOrTrunc(IsSigned, Result, DL, WideVT);
9517}
9518
9519// Op is an operand of a multiplication. Check whether this can be folded
9520// into an even/odd widening operation; if so, return the opcode to be used
9521// and update Op to the appropriate sub-operand. Note that the caller must
9522// verify that *both* operands of the multiplication support the operation.
9525 SDValue &Op) {
9526 EVT VT = Op.getValueType();
9527
9528 // Check for (sign/zero_extend_vector_inreg (vector_shuffle)) corresponding
9529 // to selecting the even or odd vector elements.
9530 if (VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
9531 (Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
9532 Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG)) {
9533 bool IsSigned = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
9534 unsigned NumElts = VT.getVectorNumElements();
9535 Op = Op.getOperand(0);
9536 if (Op.getValueType().getVectorNumElements() == 2 * NumElts &&
9537 Op.getOpcode() == ISD::VECTOR_SHUFFLE) {
9539 ArrayRef<int> ShuffleMask = SVN->getMask();
9540 bool CanUseEven = true, CanUseOdd = true;
9541 for (unsigned Elt = 0; Elt < NumElts; Elt++) {
9542 if (ShuffleMask[Elt] == -1)
9543 continue;
9544 if (unsigned(ShuffleMask[Elt]) != 2 * Elt)
9545 CanUseEven = false;
9546 if (unsigned(ShuffleMask[Elt]) != 2 * Elt + 1)
9547 CanUseOdd = false;
9548 }
9549 Op = Op.getOperand(0);
9550 if (CanUseEven)
9551 return IsSigned ? SystemZISD::VME : SystemZISD::VMLE;
9552 if (CanUseOdd)
9553 return IsSigned ? SystemZISD::VMO : SystemZISD::VMLO;
9554 }
9555 }
9556
9557 // For z17, we can also support the v2i64->i128 case, which looks like
9558 // (sign/zero_extend (extract_vector_elt X 0/1))
9559 if (VT == MVT::i128 && Subtarget.hasVectorEnhancements3() &&
9560 (Op.getOpcode() == ISD::SIGN_EXTEND ||
9561 Op.getOpcode() == ISD::ZERO_EXTEND)) {
9562 bool IsSigned = Op.getOpcode() == ISD::SIGN_EXTEND;
9563 Op = Op.getOperand(0);
9564 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9565 Op.getOperand(0).getValueType() == MVT::v2i64 &&
9566 Op.getOperand(1).getOpcode() == ISD::Constant) {
9567 unsigned Elem = Op.getConstantOperandVal(1);
9568 Op = Op.getOperand(0);
9569 if (Elem == 0)
9570 return IsSigned ? SystemZISD::VME : SystemZISD::VMLE;
9571 if (Elem == 1)
9572 return IsSigned ? SystemZISD::VMO : SystemZISD::VMLO;
9573 }
9574 }
9575
9576 return 0;
9577}
9578
9579SDValue SystemZTargetLowering::combineMUL(
9580 SDNode *N, DAGCombinerInfo &DCI) const {
9581 SelectionDAG &DAG = DCI.DAG;
9582
9583 // Detect even/odd widening multiplication.
9584 SDValue Op0 = N->getOperand(0);
9585 SDValue Op1 = N->getOperand(1);
9586 unsigned OpcodeCand0 = detectEvenOddMultiplyOperand(DAG, Subtarget, Op0);
9587 unsigned OpcodeCand1 = detectEvenOddMultiplyOperand(DAG, Subtarget, Op1);
9588 if (OpcodeCand0 && OpcodeCand0 == OpcodeCand1)
9589 return DAG.getNode(OpcodeCand0, SDLoc(N), N->getValueType(0), Op0, Op1);
9590
9591 return SDValue();
9592}
9593
9594SDValue SystemZTargetLowering::combineINTRINSIC(
9595 SDNode *N, DAGCombinerInfo &DCI) const {
9596 SelectionDAG &DAG = DCI.DAG;
9597
9598 unsigned Id = N->getConstantOperandVal(1);
9599 switch (Id) {
9600 // VECTOR LOAD (RIGHTMOST) WITH LENGTH with a length operand of 15
9601 // or larger is simply a vector load.
9602 case Intrinsic::s390_vll:
9603 case Intrinsic::s390_vlrl:
9604 if (auto *C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
9605 if (C->getZExtValue() >= 15)
9606 return DAG.getLoad(N->getValueType(0), SDLoc(N), N->getOperand(0),
9607 N->getOperand(3), MachinePointerInfo());
9608 break;
9609 // Likewise for VECTOR STORE (RIGHTMOST) WITH LENGTH.
9610 case Intrinsic::s390_vstl:
9611 case Intrinsic::s390_vstrl:
9612 if (auto *C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
9613 if (C->getZExtValue() >= 15)
9614 return DAG.getStore(N->getOperand(0), SDLoc(N), N->getOperand(2),
9615 N->getOperand(4), MachinePointerInfo());
9616 break;
9617 }
9618
9619 return SDValue();
9620}
9621
9622SDValue SystemZTargetLowering::unwrapAddress(SDValue N) const {
9623 if (N->getOpcode() == SystemZISD::PCREL_WRAPPER)
9624 return N->getOperand(0);
9625 return N;
9626}
9627
9629 DAGCombinerInfo &DCI) const {
9630 switch(N->getOpcode()) {
9631 default: break;
9632 case ISD::ZERO_EXTEND: return combineZERO_EXTEND(N, DCI);
9633 case ISD::SIGN_EXTEND: return combineSIGN_EXTEND(N, DCI);
9634 case ISD::SIGN_EXTEND_INREG: return combineSIGN_EXTEND_INREG(N, DCI);
9635 case SystemZISD::MERGE_HIGH:
9636 case SystemZISD::MERGE_LOW: return combineMERGE(N, DCI);
9637 case ISD::LOAD: return combineLOAD(N, DCI);
9638 case ISD::STORE: return combineSTORE(N, DCI);
9639 case ISD::VECTOR_SHUFFLE: return combineVECTOR_SHUFFLE(N, DCI);
9640 case ISD::EXTRACT_VECTOR_ELT: return combineEXTRACT_VECTOR_ELT(N, DCI);
9641 case SystemZISD::JOIN_DWORDS: return combineJOIN_DWORDS(N, DCI);
9643 case ISD::FP_ROUND: return combineFP_ROUND(N, DCI);
9645 case ISD::FP_EXTEND: return combineFP_EXTEND(N, DCI);
9646 case ISD::SINT_TO_FP:
9647 case ISD::UINT_TO_FP: return combineINT_TO_FP(N, DCI);
9648 case ISD::FCOPYSIGN: return combineFCOPYSIGN(N, DCI);
9649 case ISD::BSWAP: return combineBSWAP(N, DCI);
9650 case ISD::SETCC: return combineSETCC(N, DCI);
9651 case SystemZISD::BR_CCMASK: return combineBR_CCMASK(N, DCI);
9652 case SystemZISD::SELECT_CCMASK: return combineSELECT_CCMASK(N, DCI);
9653 case SystemZISD::GET_CCMASK: return combineGET_CCMASK(N, DCI);
9654 case ISD::SRL:
9655 case ISD::SRA: return combineShiftToMulAddHigh(N, DCI);
9656 case ISD::MUL: return combineMUL(N, DCI);
9657 case ISD::SDIV:
9658 case ISD::UDIV:
9659 case ISD::SREM:
9660 case ISD::UREM: return combineIntDIVREM(N, DCI);
9662 case ISD::INTRINSIC_VOID: return combineINTRINSIC(N, DCI);
9663 }
9664
9665 return SDValue();
9666}
9667
9668// Return the demanded elements for the OpNo source operand of Op. DemandedElts
9669// are for Op.
9670static APInt getDemandedSrcElements(SDValue Op, const APInt &DemandedElts,
9671 unsigned OpNo) {
9672 EVT VT = Op.getValueType();
9673 unsigned NumElts = (VT.isVector() ? VT.getVectorNumElements() : 1);
9674 APInt SrcDemE;
9675 unsigned Opcode = Op.getOpcode();
9676 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
9677 unsigned Id = Op.getConstantOperandVal(0);
9678 switch (Id) {
9679 case Intrinsic::s390_vpksh: // PACKS
9680 case Intrinsic::s390_vpksf:
9681 case Intrinsic::s390_vpksg:
9682 case Intrinsic::s390_vpkshs: // PACKS_CC
9683 case Intrinsic::s390_vpksfs:
9684 case Intrinsic::s390_vpksgs:
9685 case Intrinsic::s390_vpklsh: // PACKLS
9686 case Intrinsic::s390_vpklsf:
9687 case Intrinsic::s390_vpklsg:
9688 case Intrinsic::s390_vpklshs: // PACKLS_CC
9689 case Intrinsic::s390_vpklsfs:
9690 case Intrinsic::s390_vpklsgs:
9691 // VECTOR PACK truncates the elements of two source vectors into one.
9692 SrcDemE = DemandedElts;
9693 if (OpNo == 2)
9694 SrcDemE.lshrInPlace(NumElts / 2);
9695 SrcDemE = SrcDemE.trunc(NumElts / 2);
9696 break;
9697 // VECTOR UNPACK extends half the elements of the source vector.
9698 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
9699 case Intrinsic::s390_vuphh:
9700 case Intrinsic::s390_vuphf:
9701 case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH
9702 case Intrinsic::s390_vuplhh:
9703 case Intrinsic::s390_vuplhf:
9704 SrcDemE = APInt(NumElts * 2, 0);
9705 SrcDemE.insertBits(DemandedElts, 0);
9706 break;
9707 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
9708 case Intrinsic::s390_vuplhw:
9709 case Intrinsic::s390_vuplf:
9710 case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW
9711 case Intrinsic::s390_vupllh:
9712 case Intrinsic::s390_vupllf:
9713 SrcDemE = APInt(NumElts * 2, 0);
9714 SrcDemE.insertBits(DemandedElts, NumElts);
9715 break;
9716 case Intrinsic::s390_vpdi: {
9717 // VECTOR PERMUTE DWORD IMMEDIATE selects one element from each source.
9718 SrcDemE = APInt(NumElts, 0);
9719 if (!DemandedElts[OpNo - 1])
9720 break;
9721 unsigned Mask = Op.getConstantOperandVal(3);
9722 unsigned MaskBit = ((OpNo - 1) ? 1 : 4);
9723 // Demand input element 0 or 1, given by the mask bit value.
9724 SrcDemE.setBit((Mask & MaskBit)? 1 : 0);
9725 break;
9726 }
9727 case Intrinsic::s390_vsldb: {
9728 // VECTOR SHIFT LEFT DOUBLE BY BYTE
9729 assert(VT == MVT::v16i8 && "Unexpected type.");
9730 unsigned FirstIdx = Op.getConstantOperandVal(3);
9731 assert (FirstIdx > 0 && FirstIdx < 16 && "Unused operand.");
9732 unsigned NumSrc0Els = 16 - FirstIdx;
9733 SrcDemE = APInt(NumElts, 0);
9734 if (OpNo == 1) {
9735 APInt DemEls = DemandedElts.trunc(NumSrc0Els);
9736 SrcDemE.insertBits(DemEls, FirstIdx);
9737 } else {
9738 APInt DemEls = DemandedElts.lshr(NumSrc0Els);
9739 SrcDemE.insertBits(DemEls, 0);
9740 }
9741 break;
9742 }
9743 case Intrinsic::s390_vperm:
9744 SrcDemE = APInt::getAllOnes(NumElts);
9745 break;
9746 default:
9747 llvm_unreachable("Unhandled intrinsic.");
9748 break;
9749 }
9750 } else {
9751 switch (Opcode) {
9752 case SystemZISD::JOIN_DWORDS:
9753 // Scalar operand.
9754 SrcDemE = APInt(1, 1);
9755 break;
9756 case SystemZISD::SELECT_CCMASK:
9757 SrcDemE = DemandedElts;
9758 break;
9759 default:
9760 llvm_unreachable("Unhandled opcode.");
9761 break;
9762 }
9763 }
9764 return SrcDemE;
9765}
9766
9768 const APInt &DemandedElts,
9769 const SelectionDAG &DAG, unsigned Depth,
9770 unsigned OpNo) {
9771 APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo);
9772 APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1);
9773 KnownBits LHSKnown =
9774 DAG.computeKnownBits(Op.getOperand(OpNo), Src0DemE, Depth + 1);
9775 KnownBits RHSKnown =
9776 DAG.computeKnownBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1);
9777 Known = LHSKnown.intersectWith(RHSKnown);
9778}
9779
9780void
9783 const APInt &DemandedElts,
9784 const SelectionDAG &DAG,
9785 unsigned Depth) const {
9786 Known.resetAll();
9787
9788 // Intrinsic CC result is returned in the two low bits.
9789 unsigned Tmp0, Tmp1; // not used
9790 if (Op.getResNo() == 1 && isIntrinsicWithCC(Op, Tmp0, Tmp1)) {
9791 Known.Zero.setBitsFrom(2);
9792 return;
9793 }
9794 [[maybe_unused]] EVT VT = Op.getValueType();
9795 if (Op.getResNo() != 0)
9796 return;
9797 assert (Known.getBitWidth() == VT.getScalarSizeInBits() &&
9798 "KnownBits does not match VT in bitwidth");
9799 assert ((!VT.isVector() ||
9800 (DemandedElts.getBitWidth() == VT.getVectorNumElements())) &&
9801 "DemandedElts does not match VT number of elements");
9802 unsigned BitWidth = Known.getBitWidth();
9803 unsigned Opcode = Op.getOpcode();
9804 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
9805 bool IsLogical = false;
9806 unsigned Id = Op.getConstantOperandVal(0);
9807 switch (Id) {
9808 case Intrinsic::s390_vpksh: // PACKS
9809 case Intrinsic::s390_vpksf:
9810 case Intrinsic::s390_vpksg:
9811 case Intrinsic::s390_vpkshs: // PACKS_CC
9812 case Intrinsic::s390_vpksfs:
9813 case Intrinsic::s390_vpksgs:
9814 case Intrinsic::s390_vpklsh: // PACKLS
9815 case Intrinsic::s390_vpklsf:
9816 case Intrinsic::s390_vpklsg:
9817 case Intrinsic::s390_vpklshs: // PACKLS_CC
9818 case Intrinsic::s390_vpklsfs:
9819 case Intrinsic::s390_vpklsgs:
9820 case Intrinsic::s390_vpdi:
9821 case Intrinsic::s390_vsldb:
9822 case Intrinsic::s390_vperm:
9823 computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 1);
9824 break;
9825 case Intrinsic::s390_vuplhb: // VECTOR UNPACK LOGICAL HIGH
9826 case Intrinsic::s390_vuplhh:
9827 case Intrinsic::s390_vuplhf:
9828 case Intrinsic::s390_vupllb: // VECTOR UNPACK LOGICAL LOW
9829 case Intrinsic::s390_vupllh:
9830 case Intrinsic::s390_vupllf:
9831 IsLogical = true;
9832 [[fallthrough]];
9833 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
9834 case Intrinsic::s390_vuphh:
9835 case Intrinsic::s390_vuphf:
9836 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
9837 case Intrinsic::s390_vuplhw:
9838 case Intrinsic::s390_vuplf: {
9839 SDValue SrcOp = Op.getOperand(1);
9840 APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 0);
9841 Known = DAG.computeKnownBits(SrcOp, SrcDemE, Depth + 1);
9842 if (IsLogical) {
9843 Known = Known.zext(BitWidth);
9844 } else
9845 Known = Known.sext(BitWidth);
9846 break;
9847 }
9848 default:
9849 break;
9850 }
9851 } else {
9852 switch (Opcode) {
9853 case SystemZISD::JOIN_DWORDS:
9854 case SystemZISD::SELECT_CCMASK:
9855 computeKnownBitsBinOp(Op, Known, DemandedElts, DAG, Depth, 0);
9856 break;
9857 case SystemZISD::REPLICATE: {
9858 SDValue SrcOp = Op.getOperand(0);
9859 Known = DAG.computeKnownBits(SrcOp, Depth + 1);
9860 if (Known.getBitWidth() < BitWidth && isa<ConstantSDNode>(SrcOp))
9861 Known = Known.sext(BitWidth); // VREPI sign extends the immedate.
9862 break;
9863 }
9864 default:
9865 break;
9866 }
9867 }
9868
9869 // Known has the width of the source operand(s). Adjust if needed to match
9870 // the passed bitwidth.
9871 if (Known.getBitWidth() != BitWidth)
9872 Known = Known.anyextOrTrunc(BitWidth);
9873}
9874
9875static unsigned computeNumSignBitsBinOp(SDValue Op, const APInt &DemandedElts,
9876 const SelectionDAG &DAG, unsigned Depth,
9877 unsigned OpNo) {
9878 APInt Src0DemE = getDemandedSrcElements(Op, DemandedElts, OpNo);
9879 unsigned LHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo), Src0DemE, Depth + 1);
9880 if (LHS == 1) return 1; // Early out.
9881 APInt Src1DemE = getDemandedSrcElements(Op, DemandedElts, OpNo + 1);
9882 unsigned RHS = DAG.ComputeNumSignBits(Op.getOperand(OpNo + 1), Src1DemE, Depth + 1);
9883 if (RHS == 1) return 1; // Early out.
9884 unsigned Common = std::min(LHS, RHS);
9885 unsigned SrcBitWidth = Op.getOperand(OpNo).getScalarValueSizeInBits();
9886 EVT VT = Op.getValueType();
9887 unsigned VTBits = VT.getScalarSizeInBits();
9888 if (SrcBitWidth > VTBits) { // PACK
9889 unsigned SrcExtraBits = SrcBitWidth - VTBits;
9890 if (Common > SrcExtraBits)
9891 return (Common - SrcExtraBits);
9892 return 1;
9893 }
9894 assert (SrcBitWidth == VTBits && "Expected operands of same bitwidth.");
9895 return Common;
9896}
9897
9898unsigned
9900 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9901 unsigned Depth) const {
9902 if (Op.getResNo() != 0)
9903 return 1;
9904 unsigned Opcode = Op.getOpcode();
9905 if (Opcode == ISD::INTRINSIC_WO_CHAIN) {
9906 unsigned Id = Op.getConstantOperandVal(0);
9907 switch (Id) {
9908 case Intrinsic::s390_vpksh: // PACKS
9909 case Intrinsic::s390_vpksf:
9910 case Intrinsic::s390_vpksg:
9911 case Intrinsic::s390_vpkshs: // PACKS_CC
9912 case Intrinsic::s390_vpksfs:
9913 case Intrinsic::s390_vpksgs:
9914 case Intrinsic::s390_vpklsh: // PACKLS
9915 case Intrinsic::s390_vpklsf:
9916 case Intrinsic::s390_vpklsg:
9917 case Intrinsic::s390_vpklshs: // PACKLS_CC
9918 case Intrinsic::s390_vpklsfs:
9919 case Intrinsic::s390_vpklsgs:
9920 case Intrinsic::s390_vpdi:
9921 case Intrinsic::s390_vsldb:
9922 case Intrinsic::s390_vperm:
9923 return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 1);
9924 case Intrinsic::s390_vuphb: // VECTOR UNPACK HIGH
9925 case Intrinsic::s390_vuphh:
9926 case Intrinsic::s390_vuphf:
9927 case Intrinsic::s390_vuplb: // VECTOR UNPACK LOW
9928 case Intrinsic::s390_vuplhw:
9929 case Intrinsic::s390_vuplf: {
9930 SDValue PackedOp = Op.getOperand(1);
9931 APInt SrcDemE = getDemandedSrcElements(Op, DemandedElts, 1);
9932 unsigned Tmp = DAG.ComputeNumSignBits(PackedOp, SrcDemE, Depth + 1);
9933 EVT VT = Op.getValueType();
9934 unsigned VTBits = VT.getScalarSizeInBits();
9935 Tmp += VTBits - PackedOp.getScalarValueSizeInBits();
9936 return Tmp;
9937 }
9938 default:
9939 break;
9940 }
9941 } else {
9942 switch (Opcode) {
9943 case SystemZISD::SELECT_CCMASK:
9944 return computeNumSignBitsBinOp(Op, DemandedElts, DAG, Depth, 0);
9945 default:
9946 break;
9947 }
9948 }
9949
9950 return 1;
9951}
9952
9954 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9955 UndefPoisonKind Kind, unsigned Depth) const {
9956 switch (Op->getOpcode()) {
9957 case SystemZISD::PCREL_WRAPPER:
9958 case SystemZISD::PCREL_OFFSET:
9959 return true;
9960 }
9961 return false;
9962}
9963
9964unsigned
9966 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
9967 unsigned StackAlign = TFI->getStackAlignment();
9968 assert(StackAlign >=1 && isPowerOf2_32(StackAlign) &&
9969 "Unexpected stack alignment");
9970 // The default stack probe size is 4096 if the function has no
9971 // stack-probe-size attribute.
9972 unsigned StackProbeSize =
9973 MF.getFunction().getFnAttributeAsParsedInteger("stack-probe-size", 4096);
9974 // Round down to the stack alignment.
9975 StackProbeSize &= ~(StackAlign - 1);
9976 return StackProbeSize ? StackProbeSize : StackAlign;
9977}
9978
9979//===----------------------------------------------------------------------===//
9980// Custom insertion
9981//===----------------------------------------------------------------------===//
9982
9983// Force base value Base into a register before MI. Return the register.
9985 const SystemZInstrInfo *TII) {
9986 MachineBasicBlock *MBB = MI.getParent();
9987 MachineFunction &MF = *MBB->getParent();
9989
9990 if (Base.isReg()) {
9991 // Copy Base into a new virtual register to help register coalescing in
9992 // cases with multiple uses.
9993 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
9994 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::COPY), Reg)
9995 .add(Base);
9996 return Reg;
9997 }
9998
9999 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10000 BuildMI(*MBB, MI, MI.getDebugLoc(), TII->get(SystemZ::LA), Reg)
10001 .add(Base)
10002 .addImm(0)
10003 .addReg(0);
10004 return Reg;
10005}
10006
10007// The CC operand of MI might be missing a kill marker because there
10008// were multiple uses of CC, and ISel didn't know which to mark.
10009// Figure out whether MI should have had a kill marker.
10011 // Scan forward through BB for a use/def of CC.
10013 for (MachineBasicBlock::iterator miE = MBB->end(); miI != miE; ++miI) {
10014 const MachineInstr &MI = *miI;
10015 if (MI.readsRegister(SystemZ::CC, /*TRI=*/nullptr))
10016 return false;
10017 if (MI.definesRegister(SystemZ::CC, /*TRI=*/nullptr))
10018 break; // Should have kill-flag - update below.
10019 }
10020
10021 // If we hit the end of the block, check whether CC is live into a
10022 // successor.
10023 if (miI == MBB->end()) {
10024 for (const MachineBasicBlock *Succ : MBB->successors())
10025 if (Succ->isLiveIn(SystemZ::CC))
10026 return false;
10027 }
10028
10029 return true;
10030}
10031
10032// Return true if it is OK for this Select pseudo-opcode to be cascaded
10033// together with other Select pseudo-opcodes into a single basic-block with
10034// a conditional jump around it.
10036 switch (MI.getOpcode()) {
10037 case SystemZ::Select32:
10038 case SystemZ::Select64:
10039 case SystemZ::Select128:
10040 case SystemZ::SelectF32:
10041 case SystemZ::SelectF64:
10042 case SystemZ::SelectF128:
10043 case SystemZ::SelectVR32:
10044 case SystemZ::SelectVR64:
10045 case SystemZ::SelectVR128:
10046 return true;
10047
10048 default:
10049 return false;
10050 }
10051}
10052
10053// Helper function, which inserts PHI functions into SinkMBB:
10054// %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ],
10055// where %FalseValue(i) and %TrueValue(i) are taken from Selects.
10057 MachineBasicBlock *TrueMBB,
10058 MachineBasicBlock *FalseMBB,
10059 MachineBasicBlock *SinkMBB) {
10060 MachineFunction *MF = TrueMBB->getParent();
10062
10063 MachineInstr *FirstMI = Selects.front();
10064 unsigned CCValid = FirstMI->getOperand(3).getImm();
10065 unsigned CCMask = FirstMI->getOperand(4).getImm();
10066
10067 MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
10068
10069 // As we are creating the PHIs, we have to be careful if there is more than
10070 // one. Later Selects may reference the results of earlier Selects, but later
10071 // PHIs have to reference the individual true/false inputs from earlier PHIs.
10072 // That also means that PHI construction must work forward from earlier to
10073 // later, and that the code must maintain a mapping from earlier PHI's
10074 // destination registers, and the registers that went into the PHI.
10076
10077 for (auto *MI : Selects) {
10078 Register DestReg = MI->getOperand(0).getReg();
10079 Register TrueReg = MI->getOperand(1).getReg();
10080 Register FalseReg = MI->getOperand(2).getReg();
10081
10082 // If this Select we are generating is the opposite condition from
10083 // the jump we generated, then we have to swap the operands for the
10084 // PHI that is going to be generated.
10085 if (MI->getOperand(4).getImm() == (CCValid ^ CCMask))
10086 std::swap(TrueReg, FalseReg);
10087
10088 if (auto It = RegRewriteTable.find(TrueReg); It != RegRewriteTable.end())
10089 TrueReg = It->second.first;
10090
10091 if (auto It = RegRewriteTable.find(FalseReg); It != RegRewriteTable.end())
10092 FalseReg = It->second.second;
10093
10094 DebugLoc DL = MI->getDebugLoc();
10095 BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(SystemZ::PHI), DestReg)
10096 .addReg(TrueReg).addMBB(TrueMBB)
10097 .addReg(FalseReg).addMBB(FalseMBB);
10098
10099 // Add this PHI to the rewrite table.
10100 RegRewriteTable[DestReg] = std::make_pair(TrueReg, FalseReg);
10101 }
10102
10103 MF->getProperties().resetNoPHIs();
10104}
10105
10107SystemZTargetLowering::emitAdjCallStack(MachineInstr &MI,
10108 MachineBasicBlock *BB) const {
10109 MachineFunction &MF = *BB->getParent();
10110 MachineFrameInfo &MFI = MF.getFrameInfo();
10111 auto *TFL = Subtarget.getFrameLowering<SystemZFrameLowering>();
10112 assert(TFL->hasReservedCallFrame(MF) &&
10113 "ADJSTACKDOWN and ADJSTACKUP should be no-ops");
10114 (void)TFL;
10115 // Get the MaxCallFrameSize value and erase MI since it serves no further
10116 // purpose as the call frame is statically reserved in the prolog. Set
10117 // AdjustsStack as MI is *not* mapped as a frame instruction.
10118 uint32_t NumBytes = MI.getOperand(0).getImm();
10119 if (NumBytes > MFI.getMaxCallFrameSize())
10120 MFI.setMaxCallFrameSize(NumBytes);
10121 MFI.setAdjustsStack(true);
10122
10123 MI.eraseFromParent();
10124 return BB;
10125}
10126
10127// Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
10129SystemZTargetLowering::emitSelect(MachineInstr &MI,
10130 MachineBasicBlock *MBB) const {
10131 assert(isSelectPseudo(MI) && "Bad call to emitSelect()");
10132 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10133
10134 unsigned CCValid = MI.getOperand(3).getImm();
10135 unsigned CCMask = MI.getOperand(4).getImm();
10136
10137 // If we have a sequence of Select* pseudo instructions using the
10138 // same condition code value, we want to expand all of them into
10139 // a single pair of basic blocks using the same condition.
10140 SmallVector<MachineInstr*, 8> Selects;
10141 SmallVector<MachineInstr*, 8> DbgValues;
10142 Selects.push_back(&MI);
10143 unsigned Count = 0;
10144 for (MachineInstr &NextMI : llvm::make_range(
10145 std::next(MachineBasicBlock::iterator(MI)), MBB->end())) {
10146 if (isSelectPseudo(NextMI)) {
10147 assert(NextMI.getOperand(3).getImm() == CCValid &&
10148 "Bad CCValid operands since CC was not redefined.");
10149 if (NextMI.getOperand(4).getImm() == CCMask ||
10150 NextMI.getOperand(4).getImm() == (CCValid ^ CCMask)) {
10151 Selects.push_back(&NextMI);
10152 continue;
10153 }
10154 break;
10155 }
10156 if (NextMI.definesRegister(SystemZ::CC, /*TRI=*/nullptr) ||
10157 NextMI.usesCustomInsertionHook())
10158 break;
10159 bool User = false;
10160 for (auto *SelMI : Selects)
10161 if (NextMI.readsVirtualRegister(SelMI->getOperand(0).getReg())) {
10162 User = true;
10163 break;
10164 }
10165 if (NextMI.isDebugInstr()) {
10166 if (User) {
10167 assert(NextMI.isDebugValue() && "Unhandled debug opcode.");
10168 DbgValues.push_back(&NextMI);
10169 }
10170 } else if (User || ++Count > 20)
10171 break;
10172 }
10173
10174 MachineInstr *LastMI = Selects.back();
10175 bool CCKilled = (LastMI->killsRegister(SystemZ::CC, /*TRI=*/nullptr) ||
10176 checkCCKill(*LastMI, MBB));
10177 MachineBasicBlock *StartMBB = MBB;
10178 MachineBasicBlock *JoinMBB = SystemZ::splitBlockAfter(LastMI, MBB);
10179 MachineBasicBlock *FalseMBB = SystemZ::emitBlockAfter(StartMBB);
10180
10181 // Unless CC was killed in the last Select instruction, mark it as
10182 // live-in to both FalseMBB and JoinMBB.
10183 if (!CCKilled) {
10184 FalseMBB->addLiveIn(SystemZ::CC);
10185 JoinMBB->addLiveIn(SystemZ::CC);
10186 }
10187
10188 // StartMBB:
10189 // BRC CCMask, JoinMBB
10190 // # fallthrough to FalseMBB
10191 MBB = StartMBB;
10192 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::BRC))
10193 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
10194 MBB->addSuccessor(JoinMBB);
10195 MBB->addSuccessor(FalseMBB);
10196
10197 // FalseMBB:
10198 // # fallthrough to JoinMBB
10199 MBB = FalseMBB;
10200 MBB->addSuccessor(JoinMBB);
10201
10202 // JoinMBB:
10203 // %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
10204 // ...
10205 MBB = JoinMBB;
10206 createPHIsForSelects(Selects, StartMBB, FalseMBB, MBB);
10207 for (auto *SelMI : Selects)
10208 SelMI->eraseFromParent();
10209
10211 for (auto *DbgMI : DbgValues)
10212 MBB->splice(InsertPos, StartMBB, DbgMI);
10213
10214 return JoinMBB;
10215}
10216
10217// Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
10218// StoreOpcode is the store to use and Invert says whether the store should
10219// happen when the condition is false rather than true. If a STORE ON
10220// CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
10221MachineBasicBlock *SystemZTargetLowering::emitCondStore(MachineInstr &MI,
10223 unsigned StoreOpcode,
10224 unsigned STOCOpcode,
10225 bool Invert) const {
10226 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10227
10228 Register SrcReg = MI.getOperand(0).getReg();
10229 MachineOperand Base = MI.getOperand(1);
10230 int64_t Disp = MI.getOperand(2).getImm();
10231 Register IndexReg = MI.getOperand(3).getReg();
10232 unsigned CCValid = MI.getOperand(4).getImm();
10233 unsigned CCMask = MI.getOperand(5).getImm();
10234 DebugLoc DL = MI.getDebugLoc();
10235
10236 StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
10237
10238 // ISel pattern matching also adds a load memory operand of the same
10239 // address, so take special care to find the storing memory operand.
10240 MachineMemOperand *MMO = nullptr;
10241 for (auto *I : MI.memoperands())
10242 if (I->isStore()) {
10243 MMO = I;
10244 break;
10245 }
10246
10247 // Use STOCOpcode if possible. We could use different store patterns in
10248 // order to avoid matching the index register, but the performance trade-offs
10249 // might be more complicated in that case.
10250 if (STOCOpcode && !IndexReg && Subtarget.hasLoadStoreOnCond()) {
10251 if (Invert)
10252 CCMask ^= CCValid;
10253
10254 BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
10255 .addReg(SrcReg)
10256 .add(Base)
10257 .addImm(Disp)
10258 .addImm(CCValid)
10259 .addImm(CCMask)
10260 .addMemOperand(MMO);
10261
10262 MI.eraseFromParent();
10263 return MBB;
10264 }
10265
10266 // Get the condition needed to branch around the store.
10267 if (!Invert)
10268 CCMask ^= CCValid;
10269
10270 MachineBasicBlock *StartMBB = MBB;
10271 MachineBasicBlock *JoinMBB = SystemZ::splitBlockBefore(MI, MBB);
10272 MachineBasicBlock *FalseMBB = SystemZ::emitBlockAfter(StartMBB);
10273
10274 // Unless CC was killed in the CondStore instruction, mark it as
10275 // live-in to both FalseMBB and JoinMBB.
10276 if (!MI.killsRegister(SystemZ::CC, /*TRI=*/nullptr) &&
10277 !checkCCKill(MI, JoinMBB)) {
10278 FalseMBB->addLiveIn(SystemZ::CC);
10279 JoinMBB->addLiveIn(SystemZ::CC);
10280 }
10281
10282 // StartMBB:
10283 // BRC CCMask, JoinMBB
10284 // # fallthrough to FalseMBB
10285 MBB = StartMBB;
10286 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10287 .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
10288 MBB->addSuccessor(JoinMBB);
10289 MBB->addSuccessor(FalseMBB);
10290
10291 // FalseMBB:
10292 // store %SrcReg, %Disp(%Index,%Base)
10293 // # fallthrough to JoinMBB
10294 MBB = FalseMBB;
10295 BuildMI(MBB, DL, TII->get(StoreOpcode))
10296 .addReg(SrcReg)
10297 .add(Base)
10298 .addImm(Disp)
10299 .addReg(IndexReg)
10300 .addMemOperand(MMO);
10301 MBB->addSuccessor(JoinMBB);
10302
10303 MI.eraseFromParent();
10304 return JoinMBB;
10305}
10306
10307// Implement EmitInstrWithCustomInserter for pseudo [SU]Cmp128Hi instruction MI.
10309SystemZTargetLowering::emitICmp128Hi(MachineInstr &MI,
10311 bool Unsigned) const {
10312 MachineFunction &MF = *MBB->getParent();
10313 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10314 MachineRegisterInfo &MRI = MF.getRegInfo();
10315
10316 // Synthetic instruction to compare 128-bit values.
10317 // Sets CC 1 if Op0 > Op1, sets a different CC otherwise.
10318 Register Op0 = MI.getOperand(0).getReg();
10319 Register Op1 = MI.getOperand(1).getReg();
10320
10321 MachineBasicBlock *StartMBB = MBB;
10322 MachineBasicBlock *JoinMBB = SystemZ::splitBlockAfter(MI, MBB);
10323 MachineBasicBlock *HiEqMBB = SystemZ::emitBlockAfter(StartMBB);
10324
10325 // StartMBB:
10326 //
10327 // Use VECTOR ELEMENT COMPARE [LOGICAL] to compare the high parts.
10328 // Swap the inputs to get:
10329 // CC 1 if high(Op0) > high(Op1)
10330 // CC 2 if high(Op0) < high(Op1)
10331 // CC 0 if high(Op0) == high(Op1)
10332 //
10333 // If CC != 0, we'd done, so jump over the next instruction.
10334 //
10335 // VEC[L]G Op1, Op0
10336 // JNE JoinMBB
10337 // # fallthrough to HiEqMBB
10338 MBB = StartMBB;
10339 int HiOpcode = Unsigned? SystemZ::VECLG : SystemZ::VECG;
10340 BuildMI(MBB, MI.getDebugLoc(), TII->get(HiOpcode))
10341 .addReg(Op1).addReg(Op0);
10342 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::BRC))
10344 MBB->addSuccessor(JoinMBB);
10345 MBB->addSuccessor(HiEqMBB);
10346
10347 // HiEqMBB:
10348 //
10349 // Otherwise, use VECTOR COMPARE HIGH LOGICAL.
10350 // Since we already know the high parts are equal, the CC
10351 // result will only depend on the low parts:
10352 // CC 1 if low(Op0) > low(Op1)
10353 // CC 3 if low(Op0) <= low(Op1)
10354 //
10355 // VCHLGS Tmp, Op0, Op1
10356 // # fallthrough to JoinMBB
10357 MBB = HiEqMBB;
10358 Register Temp = MRI.createVirtualRegister(&SystemZ::VR128BitRegClass);
10359 BuildMI(MBB, MI.getDebugLoc(), TII->get(SystemZ::VCHLGS), Temp)
10360 .addReg(Op0).addReg(Op1);
10361 MBB->addSuccessor(JoinMBB);
10362
10363 // Mark CC as live-in to JoinMBB.
10364 JoinMBB->addLiveIn(SystemZ::CC);
10365
10366 MI.eraseFromParent();
10367 return JoinMBB;
10368}
10369
10370// Implement EmitInstrWithCustomInserter for subword pseudo ATOMIC_LOADW_* or
10371// ATOMIC_SWAPW instruction MI. BinOpcode is the instruction that performs
10372// the binary operation elided by "*", or 0 for ATOMIC_SWAPW. Invert says
10373// whether the field should be inverted after performing BinOpcode (e.g. for
10374// NAND).
10375MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadBinary(
10376 MachineInstr &MI, MachineBasicBlock *MBB, unsigned BinOpcode,
10377 bool Invert) const {
10378 MachineFunction &MF = *MBB->getParent();
10379 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10380 MachineRegisterInfo &MRI = MF.getRegInfo();
10381
10382 // Extract the operands. Base can be a register or a frame index.
10383 // Src2 can be a register or immediate.
10384 Register Dest = MI.getOperand(0).getReg();
10385 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
10386 int64_t Disp = MI.getOperand(2).getImm();
10387 MachineOperand Src2 = earlyUseOperand(MI.getOperand(3));
10388 Register BitShift = MI.getOperand(4).getReg();
10389 Register NegBitShift = MI.getOperand(5).getReg();
10390 unsigned BitSize = MI.getOperand(6).getImm();
10391 DebugLoc DL = MI.getDebugLoc();
10392
10393 // Get the right opcodes for the displacement.
10394 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
10395 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
10396 assert(LOpcode && CSOpcode && "Displacement out of range");
10397
10398 // Create virtual registers for temporary results.
10399 Register OrigVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10400 Register OldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10401 Register NewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10402 Register RotatedOldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10403 Register RotatedNewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10404
10405 // Insert a basic block for the main loop.
10406 MachineBasicBlock *StartMBB = MBB;
10407 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10408 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10409
10410 // StartMBB:
10411 // ...
10412 // %OrigVal = L Disp(%Base)
10413 // # fall through to LoopMBB
10414 MBB = StartMBB;
10415 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
10416 MBB->addSuccessor(LoopMBB);
10417
10418 // LoopMBB:
10419 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
10420 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
10421 // %RotatedNewVal = OP %RotatedOldVal, %Src2
10422 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
10423 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
10424 // JNE LoopMBB
10425 // # fall through to DoneMBB
10426 MBB = LoopMBB;
10427 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
10428 .addReg(OrigVal).addMBB(StartMBB)
10429 .addReg(Dest).addMBB(LoopMBB);
10430 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
10431 .addReg(OldVal).addReg(BitShift).addImm(0);
10432 if (Invert) {
10433 // Perform the operation normally and then invert every bit of the field.
10434 Register Tmp = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10435 BuildMI(MBB, DL, TII->get(BinOpcode), Tmp)
10436 .addReg(RotatedOldVal)
10437 .add(Src2)
10438 .setOperandDead(3);
10439 // XILF with the upper BitSize bits set.
10440 BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
10441 .addReg(Tmp)
10442 .addImm(-1U << (32 - BitSize))
10443 .setOperandDead(3);
10444 } else if (BinOpcode)
10445 // A simply binary operation.
10446 BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
10447 .addReg(RotatedOldVal)
10448 .add(Src2)
10449 .setOperandDead(3);
10450 else
10451 // Use RISBG to rotate Src2 into position and use it to replace the
10452 // field in RotatedOldVal.
10453 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
10454 .addReg(RotatedOldVal)
10455 .addReg(Src2.getReg())
10456 .addImm(32)
10457 .addImm(31 + BitSize)
10458 .addImm(32 - BitSize)
10459 .setOperandDead(6);
10460 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
10461 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
10462 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
10463 .addReg(OldVal)
10464 .addReg(NewVal)
10465 .add(Base)
10466 .addImm(Disp);
10467 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10469 MBB->addSuccessor(LoopMBB);
10470 MBB->addSuccessor(DoneMBB);
10471
10472 MI.eraseFromParent();
10473 return DoneMBB;
10474}
10475
10476// Implement EmitInstrWithCustomInserter for subword pseudo
10477// ATOMIC_LOADW_{,U}{MIN,MAX} instruction MI. CompareOpcode is the
10478// instruction that should be used to compare the current field with the
10479// minimum or maximum value. KeepOldMask is the BRC condition-code mask
10480// for when the current field should be kept.
10481MachineBasicBlock *SystemZTargetLowering::emitAtomicLoadMinMax(
10482 MachineInstr &MI, MachineBasicBlock *MBB, unsigned CompareOpcode,
10483 unsigned KeepOldMask) const {
10484 MachineFunction &MF = *MBB->getParent();
10485 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10486 MachineRegisterInfo &MRI = MF.getRegInfo();
10487
10488 // Extract the operands. Base can be a register or a frame index.
10489 Register Dest = MI.getOperand(0).getReg();
10490 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
10491 int64_t Disp = MI.getOperand(2).getImm();
10492 Register Src2 = MI.getOperand(3).getReg();
10493 Register BitShift = MI.getOperand(4).getReg();
10494 Register NegBitShift = MI.getOperand(5).getReg();
10495 unsigned BitSize = MI.getOperand(6).getImm();
10496 DebugLoc DL = MI.getDebugLoc();
10497
10498 // Get the right opcodes for the displacement.
10499 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
10500 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
10501 assert(LOpcode && CSOpcode && "Displacement out of range");
10502
10503 // Create virtual registers for temporary results.
10504 Register OrigVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10505 Register OldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10506 Register NewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10507 Register RotatedOldVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10508 Register RotatedAltVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10509 Register RotatedNewVal = MRI.createVirtualRegister(&SystemZ::GR32BitRegClass);
10510
10511 // Insert 3 basic blocks for the loop.
10512 MachineBasicBlock *StartMBB = MBB;
10513 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10514 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10515 MachineBasicBlock *UseAltMBB = SystemZ::emitBlockAfter(LoopMBB);
10516 MachineBasicBlock *UpdateMBB = SystemZ::emitBlockAfter(UseAltMBB);
10517
10518 // StartMBB:
10519 // ...
10520 // %OrigVal = L Disp(%Base)
10521 // # fall through to LoopMBB
10522 MBB = StartMBB;
10523 BuildMI(MBB, DL, TII->get(LOpcode), OrigVal).add(Base).addImm(Disp).addReg(0);
10524 MBB->addSuccessor(LoopMBB);
10525
10526 // LoopMBB:
10527 // %OldVal = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
10528 // %RotatedOldVal = RLL %OldVal, 0(%BitShift)
10529 // CompareOpcode %RotatedOldVal, %Src2
10530 // BRC KeepOldMask, UpdateMBB
10531 MBB = LoopMBB;
10532 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
10533 .addReg(OrigVal).addMBB(StartMBB)
10534 .addReg(Dest).addMBB(UpdateMBB);
10535 BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
10536 .addReg(OldVal).addReg(BitShift).addImm(0);
10537 BuildMI(MBB, DL, TII->get(CompareOpcode))
10538 .addReg(RotatedOldVal).addReg(Src2);
10539 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10540 .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
10541 MBB->addSuccessor(UpdateMBB);
10542 MBB->addSuccessor(UseAltMBB);
10543
10544 // UseAltMBB:
10545 // %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
10546 // # fall through to UpdateMBB
10547 MBB = UseAltMBB;
10548 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
10549 .addReg(RotatedOldVal)
10550 .addReg(Src2)
10551 .addImm(32)
10552 .addImm(31 + BitSize)
10553 .addImm(0)
10554 .setOperandDead(6);
10555 MBB->addSuccessor(UpdateMBB);
10556
10557 // UpdateMBB:
10558 // %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
10559 // [ %RotatedAltVal, UseAltMBB ]
10560 // %NewVal = RLL %RotatedNewVal, 0(%NegBitShift)
10561 // %Dest = CS %OldVal, %NewVal, Disp(%Base)
10562 // JNE LoopMBB
10563 // # fall through to DoneMBB
10564 MBB = UpdateMBB;
10565 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
10566 .addReg(RotatedOldVal).addMBB(LoopMBB)
10567 .addReg(RotatedAltVal).addMBB(UseAltMBB);
10568 BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
10569 .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
10570 BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
10571 .addReg(OldVal)
10572 .addReg(NewVal)
10573 .add(Base)
10574 .addImm(Disp);
10575 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10577 MBB->addSuccessor(LoopMBB);
10578 MBB->addSuccessor(DoneMBB);
10579
10580 MI.eraseFromParent();
10581 return DoneMBB;
10582}
10583
10584// Implement EmitInstrWithCustomInserter for subword pseudo ATOMIC_CMP_SWAPW
10585// instruction MI.
10587SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr &MI,
10588 MachineBasicBlock *MBB) const {
10589 MachineFunction &MF = *MBB->getParent();
10590 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10591 MachineRegisterInfo &MRI = MF.getRegInfo();
10592
10593 // Extract the operands. Base can be a register or a frame index.
10594 Register Dest = MI.getOperand(0).getReg();
10595 MachineOperand Base = earlyUseOperand(MI.getOperand(1));
10596 int64_t Disp = MI.getOperand(2).getImm();
10597 Register CmpVal = MI.getOperand(3).getReg();
10598 Register OrigSwapVal = MI.getOperand(4).getReg();
10599 Register BitShift = MI.getOperand(5).getReg();
10600 Register NegBitShift = MI.getOperand(6).getReg();
10601 int64_t BitSize = MI.getOperand(7).getImm();
10602 DebugLoc DL = MI.getDebugLoc();
10603
10604 const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
10605
10606 // Get the right opcodes for the displacement and zero-extension.
10607 unsigned LOpcode = TII->getOpcodeForOffset(SystemZ::L, Disp);
10608 unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
10609 unsigned ZExtOpcode = BitSize == 8 ? SystemZ::LLCR : SystemZ::LLHR;
10610 assert(LOpcode && CSOpcode && "Displacement out of range");
10611
10612 // Create virtual registers for temporary results.
10613 Register OrigOldVal = MRI.createVirtualRegister(RC);
10614 Register OldVal = MRI.createVirtualRegister(RC);
10615 Register SwapVal = MRI.createVirtualRegister(RC);
10616 Register StoreVal = MRI.createVirtualRegister(RC);
10617 Register OldValRot = MRI.createVirtualRegister(RC);
10618 Register RetryOldVal = MRI.createVirtualRegister(RC);
10619 Register RetrySwapVal = MRI.createVirtualRegister(RC);
10620
10621 // Insert 2 basic blocks for the loop.
10622 MachineBasicBlock *StartMBB = MBB;
10623 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10624 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10625 MachineBasicBlock *SetMBB = SystemZ::emitBlockAfter(LoopMBB);
10626
10627 // StartMBB:
10628 // ...
10629 // %OrigOldVal = L Disp(%Base)
10630 // # fall through to LoopMBB
10631 MBB = StartMBB;
10632 BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
10633 .add(Base)
10634 .addImm(Disp)
10635 .addReg(0);
10636 MBB->addSuccessor(LoopMBB);
10637
10638 // LoopMBB:
10639 // %OldVal = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
10640 // %SwapVal = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
10641 // %OldValRot = RLL %OldVal, BitSize(%BitShift)
10642 // ^^ The low BitSize bits contain the field
10643 // of interest.
10644 // %RetrySwapVal = RISBG32 %SwapVal, %OldValRot, 32, 63-BitSize, 0
10645 // ^^ Replace the upper 32-BitSize bits of the
10646 // swap value with those that we loaded and rotated.
10647 // %Dest = LL[CH] %OldValRot
10648 // CR %Dest, %CmpVal
10649 // JNE DoneMBB
10650 // # Fall through to SetMBB
10651 MBB = LoopMBB;
10652 BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
10653 .addReg(OrigOldVal).addMBB(StartMBB)
10654 .addReg(RetryOldVal).addMBB(SetMBB);
10655 BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
10656 .addReg(OrigSwapVal).addMBB(StartMBB)
10657 .addReg(RetrySwapVal).addMBB(SetMBB);
10658 BuildMI(MBB, DL, TII->get(SystemZ::RLL), OldValRot)
10659 .addReg(OldVal).addReg(BitShift).addImm(BitSize);
10660 BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
10661 .addReg(SwapVal)
10662 .addReg(OldValRot)
10663 .addImm(32)
10664 .addImm(63 - BitSize)
10665 .addImm(0)
10666 .setOperandDead(6);
10667 BuildMI(MBB, DL, TII->get(ZExtOpcode), Dest)
10668 .addReg(OldValRot);
10669 BuildMI(MBB, DL, TII->get(SystemZ::CR))
10670 .addReg(Dest).addReg(CmpVal);
10671 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10674 MBB->addSuccessor(DoneMBB);
10675 MBB->addSuccessor(SetMBB);
10676
10677 // SetMBB:
10678 // %StoreVal = RLL %RetrySwapVal, -BitSize(%NegBitShift)
10679 // ^^ Rotate the new field to its proper position.
10680 // %RetryOldVal = CS %OldVal, %StoreVal, Disp(%Base)
10681 // JNE LoopMBB
10682 // # fall through to ExitMBB
10683 MBB = SetMBB;
10684 BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
10685 .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
10686 BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
10687 .addReg(OldVal)
10688 .addReg(StoreVal)
10689 .add(Base)
10690 .addImm(Disp);
10691 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10693 MBB->addSuccessor(LoopMBB);
10694 MBB->addSuccessor(DoneMBB);
10695
10696 // If the CC def wasn't dead in the ATOMIC_CMP_SWAPW, mark CC as live-in
10697 // to the block after the loop. At this point, CC may have been defined
10698 // either by the CR in LoopMBB or by the CS in SetMBB.
10699 if (!MI.registerDefIsDead(SystemZ::CC, /*TRI=*/nullptr))
10700 DoneMBB->addLiveIn(SystemZ::CC);
10701
10702 MI.eraseFromParent();
10703 return DoneMBB;
10704}
10705
10707SystemZTargetLowering::emitMemMemWrapper(MachineInstr &MI,
10709 unsigned Opcode, bool IsMemset) const {
10710 MachineFunction &MF = *MBB->getParent();
10711 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
10712 MachineRegisterInfo &MRI = MF.getRegInfo();
10713 DebugLoc DL = MI.getDebugLoc();
10714
10715 MachineOperand DestBase = earlyUseOperand(MI.getOperand(0));
10716 uint64_t DestDisp = MI.getOperand(1).getImm();
10717 MachineOperand SrcBase = MachineOperand::CreateReg(0U, false);
10718 uint64_t SrcDisp;
10719
10720 // Fold the displacement Disp if it is out of range.
10721 auto foldDisplIfNeeded = [&](MachineOperand &Base, uint64_t &Disp) -> void {
10722 if (!isUInt<12>(Disp)) {
10723 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10724 unsigned Opcode = TII->getOpcodeForOffset(SystemZ::LA, Disp);
10725 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII->get(Opcode), Reg)
10726 .add(Base).addImm(Disp).addReg(0);
10728 Disp = 0;
10729 }
10730 };
10731
10732 if (!IsMemset) {
10733 SrcBase = earlyUseOperand(MI.getOperand(2));
10734 SrcDisp = MI.getOperand(3).getImm();
10735 } else {
10736 SrcBase = DestBase;
10737 SrcDisp = DestDisp++;
10738 foldDisplIfNeeded(DestBase, DestDisp);
10739 }
10740
10741 MachineOperand &LengthMO = MI.getOperand(IsMemset ? 2 : 4);
10742 bool IsImmForm = LengthMO.isImm();
10743 bool IsRegForm = !IsImmForm;
10744
10745 // Build and insert one Opcode of Length, with special treatment for memset.
10746 auto insertMemMemOp = [&](MachineBasicBlock *InsMBB,
10748 MachineOperand DBase, uint64_t DDisp,
10749 MachineOperand SBase, uint64_t SDisp,
10750 unsigned Length) -> void {
10751 assert(Length > 0 && Length <= 256 && "Building memory op with bad length.");
10752 if (IsMemset) {
10753 MachineOperand ByteMO = earlyUseOperand(MI.getOperand(3));
10754 if (ByteMO.isImm())
10755 BuildMI(*InsMBB, InsPos, DL, TII->get(SystemZ::MVI))
10756 .add(SBase).addImm(SDisp).add(ByteMO);
10757 else
10758 BuildMI(*InsMBB, InsPos, DL, TII->get(SystemZ::STC))
10759 .add(ByteMO).add(SBase).addImm(SDisp).addReg(0);
10760 if (--Length == 0)
10761 return;
10762 }
10763 BuildMI(*MBB, InsPos, DL, TII->get(Opcode))
10764 .add(DBase).addImm(DDisp).addImm(Length)
10765 .add(SBase).addImm(SDisp)
10766 .setMemRefs(MI.memoperands());
10767 };
10768
10769 bool NeedsLoop = false;
10770 uint64_t ImmLength = 0;
10771 Register LenAdjReg = SystemZ::NoRegister;
10772 if (IsImmForm) {
10773 ImmLength = LengthMO.getImm();
10774 ImmLength += IsMemset ? 2 : 1; // Add back the subtracted adjustment.
10775 if (ImmLength == 0) {
10776 MI.eraseFromParent();
10777 return MBB;
10778 }
10779 if (Opcode == SystemZ::CLC) {
10780 if (ImmLength > 3 * 256)
10781 // A two-CLC sequence is a clear win over a loop, not least because
10782 // it needs only one branch. A three-CLC sequence needs the same
10783 // number of branches as a loop (i.e. 2), but is shorter. That
10784 // brings us to lengths greater than 768 bytes. It seems relatively
10785 // likely that a difference will be found within the first 768 bytes,
10786 // so we just optimize for the smallest number of branch
10787 // instructions, in order to avoid polluting the prediction buffer
10788 // too much.
10789 NeedsLoop = true;
10790 } else if (ImmLength > 6 * 256)
10791 // The heuristic we use is to prefer loops for anything that would
10792 // require 7 or more MVCs. With these kinds of sizes there isn't much
10793 // to choose between straight-line code and looping code, since the
10794 // time will be dominated by the MVCs themselves.
10795 NeedsLoop = true;
10796 } else {
10797 NeedsLoop = true;
10798 LenAdjReg = LengthMO.getReg();
10799 }
10800
10801 // When generating more than one CLC, all but the last will need to
10802 // branch to the end when a difference is found.
10803 MachineBasicBlock *EndMBB =
10804 (Opcode == SystemZ::CLC && (ImmLength > 256 || NeedsLoop)
10806 : nullptr);
10807
10808 if (NeedsLoop) {
10809 Register StartCountReg =
10810 MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
10811 if (IsImmForm) {
10812 TII->loadImmediate(*MBB, MI, StartCountReg, ImmLength / 256);
10813 ImmLength &= 255;
10814 } else {
10815 BuildMI(*MBB, MI, DL, TII->get(SystemZ::SRLG), StartCountReg)
10816 .addReg(LenAdjReg)
10817 .addReg(0)
10818 .addImm(8);
10819 }
10820
10821 bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
10822 auto loadZeroAddress = [&]() -> MachineOperand {
10823 Register Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
10824 BuildMI(*MBB, MI, DL, TII->get(SystemZ::LGHI), Reg).addImm(0);
10825 return MachineOperand::CreateReg(Reg, false);
10826 };
10827 if (DestBase.isReg() && DestBase.getReg() == SystemZ::NoRegister)
10828 DestBase = loadZeroAddress();
10829 if (SrcBase.isReg() && SrcBase.getReg() == SystemZ::NoRegister)
10830 SrcBase = HaveSingleBase ? DestBase : loadZeroAddress();
10831
10832 MachineBasicBlock *StartMBB = nullptr;
10833 MachineBasicBlock *LoopMBB = nullptr;
10834 MachineBasicBlock *NextMBB = nullptr;
10835 MachineBasicBlock *DoneMBB = nullptr;
10836 MachineBasicBlock *AllDoneMBB = nullptr;
10837
10838 Register StartSrcReg = forceReg(MI, SrcBase, TII);
10839 Register StartDestReg =
10840 (HaveSingleBase ? StartSrcReg : forceReg(MI, DestBase, TII));
10841
10842 const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
10843 Register ThisSrcReg = MRI.createVirtualRegister(RC);
10844 Register ThisDestReg =
10845 (HaveSingleBase ? ThisSrcReg : MRI.createVirtualRegister(RC));
10846 Register NextSrcReg = MRI.createVirtualRegister(RC);
10847 Register NextDestReg =
10848 (HaveSingleBase ? NextSrcReg : MRI.createVirtualRegister(RC));
10849 RC = &SystemZ::GR64BitRegClass;
10850 Register ThisCountReg = MRI.createVirtualRegister(RC);
10851 Register NextCountReg = MRI.createVirtualRegister(RC);
10852
10853 if (IsRegForm) {
10854 AllDoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10855 StartMBB = SystemZ::emitBlockAfter(MBB);
10856 LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10857 NextMBB = (EndMBB ? SystemZ::emitBlockAfter(LoopMBB) : LoopMBB);
10858 DoneMBB = SystemZ::emitBlockAfter(NextMBB);
10859
10860 // MBB:
10861 // # Jump to AllDoneMBB if LenAdjReg means 0, or fall thru to StartMBB.
10862 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10863 .addReg(LenAdjReg).addImm(IsMemset ? -2 : -1);
10864 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10866 .addMBB(AllDoneMBB);
10867 MBB->addSuccessor(AllDoneMBB);
10868 if (!IsMemset)
10869 MBB->addSuccessor(StartMBB);
10870 else {
10871 // MemsetOneCheckMBB:
10872 // # Jump to MemsetOneMBB for a memset of length 1, or
10873 // # fall thru to StartMBB.
10874 MachineBasicBlock *MemsetOneCheckMBB = SystemZ::emitBlockAfter(MBB);
10875 MachineBasicBlock *MemsetOneMBB = SystemZ::emitBlockAfter(&*MF.rbegin());
10876 MBB->addSuccessor(MemsetOneCheckMBB);
10877 MBB = MemsetOneCheckMBB;
10878 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10879 .addReg(LenAdjReg).addImm(-1);
10880 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10882 .addMBB(MemsetOneMBB);
10883 MBB->addSuccessor(MemsetOneMBB, {10, 100});
10884 MBB->addSuccessor(StartMBB, {90, 100});
10885
10886 // MemsetOneMBB:
10887 // # Jump back to AllDoneMBB after a single MVI or STC.
10888 MBB = MemsetOneMBB;
10889 insertMemMemOp(MBB, MBB->end(),
10890 MachineOperand::CreateReg(StartDestReg, false), DestDisp,
10891 MachineOperand::CreateReg(StartSrcReg, false), SrcDisp,
10892 1);
10893 BuildMI(MBB, DL, TII->get(SystemZ::J)).addMBB(AllDoneMBB);
10894 MBB->addSuccessor(AllDoneMBB);
10895 }
10896
10897 // StartMBB:
10898 // # Jump to DoneMBB if %StartCountReg is zero, or fall through to LoopMBB.
10899 MBB = StartMBB;
10900 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10901 .addReg(StartCountReg).addImm(0);
10902 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10904 .addMBB(DoneMBB);
10905 MBB->addSuccessor(DoneMBB);
10906 MBB->addSuccessor(LoopMBB);
10907 }
10908 else {
10909 StartMBB = MBB;
10910 DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
10911 LoopMBB = SystemZ::emitBlockAfter(StartMBB);
10912 NextMBB = (EndMBB ? SystemZ::emitBlockAfter(LoopMBB) : LoopMBB);
10913
10914 // StartMBB:
10915 // # fall through to LoopMBB
10916 MBB->addSuccessor(LoopMBB);
10917
10918 DestBase = MachineOperand::CreateReg(NextDestReg, false);
10919 SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
10920 if (EndMBB && !ImmLength)
10921 // If the loop handled the whole CLC range, DoneMBB will be empty with
10922 // CC live-through into EndMBB, so add it as live-in.
10923 DoneMBB->addLiveIn(SystemZ::CC);
10924 }
10925
10926 // LoopMBB:
10927 // %ThisDestReg = phi [ %StartDestReg, StartMBB ],
10928 // [ %NextDestReg, NextMBB ]
10929 // %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
10930 // [ %NextSrcReg, NextMBB ]
10931 // %ThisCountReg = phi [ %StartCountReg, StartMBB ],
10932 // [ %NextCountReg, NextMBB ]
10933 // ( PFD 2, 768+DestDisp(%ThisDestReg) )
10934 // Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
10935 // ( JLH EndMBB )
10936 //
10937 // The prefetch is used only for MVC. The JLH is used only for CLC.
10938 MBB = LoopMBB;
10939 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
10940 .addReg(StartDestReg).addMBB(StartMBB)
10941 .addReg(NextDestReg).addMBB(NextMBB);
10942 if (!HaveSingleBase)
10943 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
10944 .addReg(StartSrcReg).addMBB(StartMBB)
10945 .addReg(NextSrcReg).addMBB(NextMBB);
10946 BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
10947 .addReg(StartCountReg).addMBB(StartMBB)
10948 .addReg(NextCountReg).addMBB(NextMBB);
10949 if (Opcode == SystemZ::MVC)
10950 BuildMI(MBB, DL, TII->get(SystemZ::PFD))
10952 .addReg(ThisDestReg).addImm(DestDisp - IsMemset + 768).addReg(0);
10953 insertMemMemOp(MBB, MBB->end(),
10954 MachineOperand::CreateReg(ThisDestReg, false), DestDisp,
10955 MachineOperand::CreateReg(ThisSrcReg, false), SrcDisp, 256);
10956 if (EndMBB) {
10957 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10959 .addMBB(EndMBB);
10960 MBB->addSuccessor(EndMBB);
10961 MBB->addSuccessor(NextMBB);
10962 }
10963
10964 // NextMBB:
10965 // %NextDestReg = LA 256(%ThisDestReg)
10966 // %NextSrcReg = LA 256(%ThisSrcReg)
10967 // %NextCountReg = AGHI %ThisCountReg, -1
10968 // CGHI %NextCountReg, 0
10969 // JLH LoopMBB
10970 // # fall through to DoneMBB
10971 //
10972 // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
10973 MBB = NextMBB;
10974 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
10975 .addReg(ThisDestReg).addImm(256).addReg(0);
10976 if (!HaveSingleBase)
10977 BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
10978 .addReg(ThisSrcReg).addImm(256).addReg(0);
10979 BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
10980 .addReg(ThisCountReg)
10981 .addImm(-1)
10982 .setOperandDead(3);
10983 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
10984 .addReg(NextCountReg).addImm(0);
10985 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
10987 .addMBB(LoopMBB);
10988 MBB->addSuccessor(LoopMBB);
10989 MBB->addSuccessor(DoneMBB);
10990
10991 MBB = DoneMBB;
10992 if (IsRegForm) {
10993 // DoneMBB:
10994 // # Make PHIs for RemDestReg/RemSrcReg as the loop may or may not run.
10995 // # Use EXecute Relative Long for the remainder of the bytes. The target
10996 // instruction of the EXRL will have a length field of 1 since 0 is an
10997 // illegal value. The number of bytes processed becomes (%LenAdjReg &
10998 // 0xff) + 1.
10999 // # Fall through to AllDoneMBB.
11000 Register RemSrcReg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11001 Register RemDestReg = HaveSingleBase ? RemSrcReg
11002 : MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11003 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RemDestReg)
11004 .addReg(StartDestReg).addMBB(StartMBB)
11005 .addReg(NextDestReg).addMBB(NextMBB);
11006 if (!HaveSingleBase)
11007 BuildMI(MBB, DL, TII->get(SystemZ::PHI), RemSrcReg)
11008 .addReg(StartSrcReg).addMBB(StartMBB)
11009 .addReg(NextSrcReg).addMBB(NextMBB);
11010 if (IsMemset)
11011 insertMemMemOp(MBB, MBB->end(),
11012 MachineOperand::CreateReg(RemDestReg, false), DestDisp,
11013 MachineOperand::CreateReg(RemSrcReg, false), SrcDisp, 1);
11014 MachineInstrBuilder EXRL_MIB =
11015 BuildMI(MBB, DL, TII->get(SystemZ::EXRL_Pseudo))
11016 .addImm(Opcode)
11017 .addReg(LenAdjReg)
11018 .addReg(RemDestReg).addImm(DestDisp)
11019 .addReg(RemSrcReg).addImm(SrcDisp);
11020 MBB->addSuccessor(AllDoneMBB);
11021 MBB = AllDoneMBB;
11022 if (Opcode != SystemZ::MVC) {
11023 EXRL_MIB.addReg(SystemZ::CC, RegState::ImplicitDefine);
11024 if (EndMBB)
11025 MBB->addLiveIn(SystemZ::CC);
11026 }
11027 }
11028 MF.getProperties().resetNoPHIs();
11029 }
11030
11031 // Handle any remaining bytes with straight-line code.
11032 while (ImmLength > 0) {
11033 uint64_t ThisLength = std::min(ImmLength, uint64_t(256));
11034 // The previous iteration might have created out-of-range displacements.
11035 // Apply them using LA/LAY if so.
11036 foldDisplIfNeeded(DestBase, DestDisp);
11037 foldDisplIfNeeded(SrcBase, SrcDisp);
11038 insertMemMemOp(MBB, MI, DestBase, DestDisp, SrcBase, SrcDisp, ThisLength);
11039 DestDisp += ThisLength;
11040 SrcDisp += ThisLength;
11041 ImmLength -= ThisLength;
11042 // If there's another CLC to go, branch to the end if a difference
11043 // was found.
11044 if (EndMBB && ImmLength > 0) {
11045 MachineBasicBlock *NextMBB = SystemZ::splitBlockBefore(MI, MBB);
11046 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11048 .addMBB(EndMBB);
11049 MBB->addSuccessor(EndMBB);
11050 MBB->addSuccessor(NextMBB);
11051 MBB = NextMBB;
11052 }
11053 }
11054 if (EndMBB) {
11055 MBB->addSuccessor(EndMBB);
11056 MBB = EndMBB;
11057 MBB->addLiveIn(SystemZ::CC);
11058 }
11059
11060 MI.eraseFromParent();
11061 return MBB;
11062}
11063
11065SystemZTargetLowering::emitMemmoveImm(MachineInstr &MI,
11066 MachineBasicBlock *MBB) const {
11067 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11068
11069 DebugLoc DL = MI.getDebugLoc();
11070 MachineOperand DstAddr = earlyUseOperand(MI.getOperand(0));
11071 MachineOperand SrcAddr = earlyUseOperand(MI.getOperand(1));
11072 uint64_t Len = MI.getOperand(2).getImm();
11073 assert(Len > 0 && Len <= 256 && "Memmove of of unsupported constant length.");
11074
11075 // Use MVC or MVCRL after comparing the addresses.
11076 MachineBasicBlock *DoneMBB = SystemZ::splitBlockAfter(MI, MBB);
11077 MachineBasicBlock *MvcMBB = SystemZ::emitBlockAfter(MBB);
11078 MachineBasicBlock *MvcrlMBB = SystemZ::emitBlockAfter(MvcMBB);
11079 MBB->addSuccessor(MvcMBB);
11080 MBB->addSuccessor(MvcrlMBB);
11081 MvcMBB->addSuccessor(DoneMBB);
11082 MvcrlMBB->addSuccessor(DoneMBB);
11083
11084 BuildMI(MBB, DL, TII->get(SystemZ::CLGR)).add(SrcAddr).add(DstAddr);
11085 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11087 .addMBB(MvcrlMBB);
11088
11089 BuildMI(MvcMBB, DL, TII->get(SystemZ::MVC))
11090 .add(DstAddr).addImm(0)
11091 .addImm(Len)
11092 .add(SrcAddr).addImm(0)
11093 .setMemRefs(MI.memoperands());
11094 BuildMI(MvcMBB, DL, TII->get(SystemZ::J)).addMBB(DoneMBB);
11095
11096 BuildMI(MvcrlMBB, DL, TII->get(SystemZ::LHI), SystemZ::R0L).addImm(Len - 1);
11097 BuildMI(MvcrlMBB, DL, TII->get(SystemZ::MVCRL))
11098 .add(DstAddr).addImm(0)
11099 .add(SrcAddr).addImm(0)
11100 .setMemRefs(MI.memoperands());
11101
11102 MI.eraseFromParent();
11103 return DoneMBB;
11104}
11105
11106// Decompose string pseudo-instruction MI into a loop that continually performs
11107// Opcode until CC != 3.
11108MachineBasicBlock *SystemZTargetLowering::emitStringWrapper(
11109 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
11110 MachineFunction &MF = *MBB->getParent();
11111 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11112 MachineRegisterInfo &MRI = MF.getRegInfo();
11113 DebugLoc DL = MI.getDebugLoc();
11114
11115 uint64_t End1Reg = MI.getOperand(0).getReg();
11116 uint64_t Start1Reg = MI.getOperand(1).getReg();
11117 uint64_t Start2Reg = MI.getOperand(2).getReg();
11118 uint64_t CharReg = MI.getOperand(3).getReg();
11119
11120 const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
11121 uint64_t This1Reg = MRI.createVirtualRegister(RC);
11122 uint64_t This2Reg = MRI.createVirtualRegister(RC);
11123 uint64_t End2Reg = MRI.createVirtualRegister(RC);
11124
11125 MachineBasicBlock *StartMBB = MBB;
11126 MachineBasicBlock *DoneMBB = SystemZ::splitBlockBefore(MI, MBB);
11127 MachineBasicBlock *LoopMBB = SystemZ::emitBlockAfter(StartMBB);
11128
11129 // StartMBB:
11130 // # fall through to LoopMBB
11131 MBB->addSuccessor(LoopMBB);
11132
11133 // LoopMBB:
11134 // %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
11135 // %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
11136 // R0L = %CharReg
11137 // %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
11138 // JO LoopMBB
11139 // # fall through to DoneMBB
11140 //
11141 // The load of R0L can be hoisted by post-RA LICM.
11142 MBB = LoopMBB;
11143
11144 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
11145 .addReg(Start1Reg).addMBB(StartMBB)
11146 .addReg(End1Reg).addMBB(LoopMBB);
11147 BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
11148 .addReg(Start2Reg).addMBB(StartMBB)
11149 .addReg(End2Reg).addMBB(LoopMBB);
11150 BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
11151 BuildMI(MBB, DL, TII->get(Opcode))
11152 .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
11153 .addReg(This1Reg).addReg(This2Reg);
11154 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11156 MBB->addSuccessor(LoopMBB);
11157 MBB->addSuccessor(DoneMBB);
11158
11159 DoneMBB->addLiveIn(SystemZ::CC);
11160
11161 MI.eraseFromParent();
11162 return DoneMBB;
11163}
11164
11165// Update TBEGIN instruction with final opcode and register clobbers.
11166MachineBasicBlock *SystemZTargetLowering::emitTransactionBegin(
11167 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode,
11168 bool NoFloat) const {
11169 MachineFunction &MF = *MBB->getParent();
11170 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11171 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11172
11173 // Update opcode.
11174 MI.setDesc(TII->get(Opcode));
11175
11176 // We cannot handle a TBEGIN that clobbers the stack or frame pointer.
11177 // Make sure to add the corresponding GRSM bits if they are missing.
11178 uint64_t Control = MI.getOperand(2).getImm();
11179 static const unsigned GPRControlBit[16] = {
11180 0x8000, 0x8000, 0x4000, 0x4000, 0x2000, 0x2000, 0x1000, 0x1000,
11181 0x0800, 0x0800, 0x0400, 0x0400, 0x0200, 0x0200, 0x0100, 0x0100
11182 };
11183 Control |= GPRControlBit[15];
11184 if (TFI->hasFP(MF))
11185 Control |= GPRControlBit[11];
11186 MI.getOperand(2).setImm(Control);
11187
11188 // Add GPR clobbers.
11189 for (int I = 0; I < 16; I++) {
11190 if ((Control & GPRControlBit[I]) == 0) {
11191 unsigned Reg = SystemZMC::GR64Regs[I];
11192 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
11193 }
11194 }
11195
11196 // Add FPR/VR clobbers.
11197 if (!NoFloat && (Control & 4) != 0) {
11198 if (Subtarget.hasVector()) {
11199 for (unsigned Reg : SystemZMC::VR128Regs) {
11200 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
11201 }
11202 } else {
11203 for (unsigned Reg : SystemZMC::FP64Regs) {
11204 MI.addOperand(MachineOperand::CreateReg(Reg, true, true));
11205 }
11206 }
11207 }
11208
11209 return MBB;
11210}
11211
11212MachineBasicBlock *SystemZTargetLowering::emitLoadAndTestCmp0(
11213 MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode) const {
11214 MachineFunction &MF = *MBB->getParent();
11215 MachineRegisterInfo *MRI = &MF.getRegInfo();
11216 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11217 DebugLoc DL = MI.getDebugLoc();
11218
11219 Register SrcReg = MI.getOperand(0).getReg();
11220
11221 // Create new virtual register of the same class as source.
11222 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
11223 Register DstReg = MRI->createVirtualRegister(RC);
11224
11225 // Replace pseudo with a normal load-and-test that models the def as
11226 // well.
11227 BuildMI(*MBB, MI, DL, TII->get(Opcode), DstReg)
11228 .addReg(SrcReg)
11229 .setMIFlags(MI.getFlags());
11230 MI.eraseFromParent();
11231
11232 return MBB;
11233}
11234
11235MachineBasicBlock *SystemZTargetLowering::emitProbedAlloca(
11237 MachineFunction &MF = *MBB->getParent();
11238 MachineRegisterInfo *MRI = &MF.getRegInfo();
11239 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11240 DebugLoc DL = MI.getDebugLoc();
11241 const unsigned ProbeSize = getStackProbeSize(MF);
11242 Register DstReg = MI.getOperand(0).getReg();
11243 Register SizeReg = MI.getOperand(2).getReg();
11244
11245 MachineBasicBlock *StartMBB = MBB;
11246 MachineBasicBlock *DoneMBB = SystemZ::splitBlockAfter(MI, MBB);
11247 MachineBasicBlock *LoopTestMBB = SystemZ::emitBlockAfter(StartMBB);
11248 MachineBasicBlock *LoopBodyMBB = SystemZ::emitBlockAfter(LoopTestMBB);
11249 MachineBasicBlock *TailTestMBB = SystemZ::emitBlockAfter(LoopBodyMBB);
11250 MachineBasicBlock *TailMBB = SystemZ::emitBlockAfter(TailTestMBB);
11251
11252 MachineMemOperand *VolLdMMO = MF.getMachineMemOperand(MachinePointerInfo(),
11254
11255 Register PHIReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11256 Register IncReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11257
11258 // LoopTestMBB
11259 // BRC TailTestMBB
11260 // # fallthrough to LoopBodyMBB
11261 StartMBB->addSuccessor(LoopTestMBB);
11262 MBB = LoopTestMBB;
11263 BuildMI(MBB, DL, TII->get(SystemZ::PHI), PHIReg)
11264 .addReg(SizeReg)
11265 .addMBB(StartMBB)
11266 .addReg(IncReg)
11267 .addMBB(LoopBodyMBB);
11268 BuildMI(MBB, DL, TII->get(SystemZ::CLGFI))
11269 .addReg(PHIReg)
11270 .addImm(ProbeSize);
11271 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11273 .addMBB(TailTestMBB);
11274 MBB->addSuccessor(LoopBodyMBB);
11275 MBB->addSuccessor(TailTestMBB);
11276
11277 // LoopBodyMBB: Allocate and probe by means of a volatile compare.
11278 // J LoopTestMBB
11279 MBB = LoopBodyMBB;
11280 BuildMI(MBB, DL, TII->get(SystemZ::SLGFI), IncReg)
11281 .addReg(PHIReg)
11282 .addImm(ProbeSize)
11283 .setOperandDead(3);
11284 BuildMI(MBB, DL, TII->get(SystemZ::SLGFI), SystemZ::R15D)
11285 .addReg(SystemZ::R15D)
11286 .addImm(ProbeSize)
11287 .setOperandDead(3);
11288 BuildMI(MBB, DL, TII->get(SystemZ::CG))
11289 .addReg(SystemZ::R15D)
11290 .addReg(SystemZ::R15D)
11291 .addImm(ProbeSize - 8)
11292 .addReg(0)
11293 .setOperandDead(4)
11294 .setMemRefs(VolLdMMO);
11295 BuildMI(MBB, DL, TII->get(SystemZ::J)).addMBB(LoopTestMBB);
11296 MBB->addSuccessor(LoopTestMBB);
11297
11298 // TailTestMBB
11299 // BRC DoneMBB
11300 // # fallthrough to TailMBB
11301 MBB = TailTestMBB;
11302 BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
11303 .addReg(PHIReg)
11304 .addImm(0);
11305 BuildMI(MBB, DL, TII->get(SystemZ::BRC))
11307 .addMBB(DoneMBB);
11308 MBB->addSuccessor(TailMBB);
11309 MBB->addSuccessor(DoneMBB);
11310
11311 // TailMBB
11312 // # fallthrough to DoneMBB
11313 MBB = TailMBB;
11314 BuildMI(MBB, DL, TII->get(SystemZ::SLGR), SystemZ::R15D)
11315 .addReg(SystemZ::R15D)
11316 .addReg(PHIReg)
11317 .setOperandDead(3);
11318 BuildMI(MBB, DL, TII->get(SystemZ::CG))
11319 .addReg(SystemZ::R15D)
11320 .addReg(SystemZ::R15D)
11321 .addImm(-8)
11322 .addReg(PHIReg)
11323 .setOperandDead(4)
11324 .setMemRefs(VolLdMMO);
11325 MBB->addSuccessor(DoneMBB);
11326
11327 // DoneMBB
11328 MBB = DoneMBB;
11329 BuildMI(*MBB, MBB->begin(), DL, TII->get(TargetOpcode::COPY), DstReg)
11330 .addReg(SystemZ::R15D);
11331
11332 MI.eraseFromParent();
11333 return DoneMBB;
11334}
11335
11336SDValue SystemZTargetLowering::
11337getBackchainAddress(SDValue SP, SelectionDAG &DAG) const {
11339 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>();
11340 SDLoc DL(SP);
11341 return DAG.getNode(ISD::ADD, DL, MVT::i64, SP,
11342 DAG.getIntPtrConstant(TFL->getBackchainOffset(MF), DL));
11343}
11344
11345// Replace a _STACKGUARD_DAG pseudo with a _STACKGUARD pseudo, adding
11346// a dead early-clobber def reg that will be used as a scratch register
11347// when the pseudo is expanded.
11348MachineBasicBlock *SystemZTargetLowering::emitStackGuardPseudo(
11349 MachineInstr &MI, MachineBasicBlock *MBB, unsigned PseudoOp) const {
11350 MachineRegisterInfo *MRI = &MBB->getParent()->getRegInfo();
11351 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
11352 DebugLoc DL = MI.getDebugLoc();
11353 Register AddrReg = MRI->createVirtualRegister(&SystemZ::ADDR64BitRegClass);
11354 BuildMI(*MBB, MI, DL, TII->get(PseudoOp), AddrReg)
11355 .addFrameIndex(MI.getOperand(0).getIndex())
11356 .addImm(MI.getOperand(1).getImm());
11357 MI.eraseFromParent();
11358 return MBB;
11359}
11360
11363 switch (MI.getOpcode()) {
11364 case SystemZ::ADJCALLSTACKDOWN:
11365 case SystemZ::ADJCALLSTACKUP:
11366 return emitAdjCallStack(MI, MBB);
11367
11368 case SystemZ::Select32:
11369 case SystemZ::Select64:
11370 case SystemZ::Select128:
11371 case SystemZ::SelectF32:
11372 case SystemZ::SelectF64:
11373 case SystemZ::SelectF128:
11374 case SystemZ::SelectVR32:
11375 case SystemZ::SelectVR64:
11376 case SystemZ::SelectVR128:
11377 return emitSelect(MI, MBB);
11378
11379 case SystemZ::CondStore8Mux:
11380 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
11381 case SystemZ::CondStore8MuxInv:
11382 return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
11383 case SystemZ::CondStore16Mux:
11384 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
11385 case SystemZ::CondStore16MuxInv:
11386 return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
11387 case SystemZ::CondStore32Mux:
11388 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, false);
11389 case SystemZ::CondStore32MuxInv:
11390 return emitCondStore(MI, MBB, SystemZ::STMux, SystemZ::STOCMux, true);
11391 case SystemZ::CondStore8:
11392 return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
11393 case SystemZ::CondStore8Inv:
11394 return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
11395 case SystemZ::CondStore16:
11396 return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
11397 case SystemZ::CondStore16Inv:
11398 return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
11399 case SystemZ::CondStore32:
11400 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
11401 case SystemZ::CondStore32Inv:
11402 return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
11403 case SystemZ::CondStore64:
11404 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
11405 case SystemZ::CondStore64Inv:
11406 return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
11407 case SystemZ::CondStoreF32:
11408 return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
11409 case SystemZ::CondStoreF32Inv:
11410 return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
11411 case SystemZ::CondStoreF64:
11412 return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
11413 case SystemZ::CondStoreF64Inv:
11414 return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
11415
11416 case SystemZ::SCmp128Hi:
11417 return emitICmp128Hi(MI, MBB, false);
11418 case SystemZ::UCmp128Hi:
11419 return emitICmp128Hi(MI, MBB, true);
11420
11421
11422 case SystemZ::ATOMIC_SWAPW:
11423 return emitAtomicLoadBinary(MI, MBB, 0);
11424
11425 case SystemZ::ATOMIC_LOADW_AR:
11426 return emitAtomicLoadBinary(MI, MBB, SystemZ::AR);
11427 case SystemZ::ATOMIC_LOADW_AFI:
11428 return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI);
11429
11430 case SystemZ::ATOMIC_LOADW_SR:
11431 return emitAtomicLoadBinary(MI, MBB, SystemZ::SR);
11432
11433 case SystemZ::ATOMIC_LOADW_NR:
11434 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR);
11435 case SystemZ::ATOMIC_LOADW_NILH:
11436 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH);
11437
11438 case SystemZ::ATOMIC_LOADW_OR:
11439 return emitAtomicLoadBinary(MI, MBB, SystemZ::OR);
11440 case SystemZ::ATOMIC_LOADW_OILH:
11441 return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH);
11442
11443 case SystemZ::ATOMIC_LOADW_XR:
11444 return emitAtomicLoadBinary(MI, MBB, SystemZ::XR);
11445 case SystemZ::ATOMIC_LOADW_XILF:
11446 return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF);
11447
11448 case SystemZ::ATOMIC_LOADW_NRi:
11449 return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, true);
11450 case SystemZ::ATOMIC_LOADW_NILHi:
11451 return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, true);
11452
11453 case SystemZ::ATOMIC_LOADW_MIN:
11454 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR, SystemZ::CCMASK_CMP_LE);
11455 case SystemZ::ATOMIC_LOADW_MAX:
11456 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR, SystemZ::CCMASK_CMP_GE);
11457 case SystemZ::ATOMIC_LOADW_UMIN:
11458 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR, SystemZ::CCMASK_CMP_LE);
11459 case SystemZ::ATOMIC_LOADW_UMAX:
11460 return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR, SystemZ::CCMASK_CMP_GE);
11461
11462 case SystemZ::ATOMIC_CMP_SWAPW:
11463 return emitAtomicCmpSwapW(MI, MBB);
11464 case SystemZ::MVCImm:
11465 case SystemZ::MVCReg:
11466 return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
11467 case SystemZ::NCImm:
11468 return emitMemMemWrapper(MI, MBB, SystemZ::NC);
11469 case SystemZ::OCImm:
11470 return emitMemMemWrapper(MI, MBB, SystemZ::OC);
11471 case SystemZ::XCImm:
11472 case SystemZ::XCReg:
11473 return emitMemMemWrapper(MI, MBB, SystemZ::XC);
11474 case SystemZ::CLCImm:
11475 case SystemZ::CLCReg:
11476 return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
11477 case SystemZ::MemsetImmImm:
11478 case SystemZ::MemsetImmReg:
11479 case SystemZ::MemsetRegImm:
11480 case SystemZ::MemsetRegReg:
11481 return emitMemMemWrapper(MI, MBB, SystemZ::MVC, true/*IsMemset*/);
11482 case SystemZ::MemmoveImm:
11483 return emitMemmoveImm(MI, MBB);
11484 case SystemZ::CLSTLoop:
11485 return emitStringWrapper(MI, MBB, SystemZ::CLST);
11486 case SystemZ::MVSTLoop:
11487 return emitStringWrapper(MI, MBB, SystemZ::MVST);
11488 case SystemZ::SRSTLoop:
11489 return emitStringWrapper(MI, MBB, SystemZ::SRST);
11490 case SystemZ::TBEGIN:
11491 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, false);
11492 case SystemZ::TBEGIN_nofloat:
11493 return emitTransactionBegin(MI, MBB, SystemZ::TBEGIN, true);
11494 case SystemZ::TBEGINC:
11495 return emitTransactionBegin(MI, MBB, SystemZ::TBEGINC, true);
11496 case SystemZ::LTEBRCompare_Pseudo:
11497 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTEBR);
11498 case SystemZ::LTDBRCompare_Pseudo:
11499 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTDBR);
11500 case SystemZ::LTXBRCompare_Pseudo:
11501 return emitLoadAndTestCmp0(MI, MBB, SystemZ::LTXBR);
11502
11503 case SystemZ::PROBED_ALLOCA:
11504 return emitProbedAlloca(MI, MBB);
11505 case SystemZ::EH_SjLj_SetJmp:
11506 return emitEHSjLjSetJmp(MI, MBB);
11507 case SystemZ::EH_SjLj_LongJmp:
11508 return emitEHSjLjLongJmp(MI, MBB);
11509
11510 case TargetOpcode::STACKMAP:
11511 case TargetOpcode::PATCHPOINT:
11512 return emitPatchPoint(MI, MBB);
11513
11514 case SystemZ::MOV_STACKGUARD_DAG:
11515 return emitStackGuardPseudo(MI, MBB, SystemZ::MOV_STACKGUARD);
11516
11517 case SystemZ::CMP_STACKGUARD_DAG:
11518 return emitStackGuardPseudo(MI, MBB, SystemZ::CMP_STACKGUARD);
11519
11520 default:
11521 llvm_unreachable("Unexpected instr type to insert");
11522 }
11523}
11524
11525SDValue SystemZTargetLowering::lowerGET_ROUNDING(SDValue Op,
11526 SelectionDAG &DAG) const {
11527 SDLoc dl(Op);
11528 /*
11529 The rounding method is in FPC Byte 3 bits 6-7, and has the following
11530 settings:
11531 00 Round to nearest
11532 01 Round to 0
11533 10 Round to +inf
11534 11 Round to -inf
11535
11536 FLT_ROUNDS, on the other hand, expects the following:
11537 -1 Undefined
11538 0 Round to 0
11539 1 Round to nearest
11540 2 Round to +inf
11541 3 Round to -inf
11542 */
11543
11544 // Save FPC to register.
11545 SDValue Chain = Op.getOperand(0);
11546 SDValue EFPC(
11547 DAG.getMachineNode(SystemZ::EFPC, dl, {MVT::i32, MVT::Other}, Chain), 0);
11548 Chain = EFPC.getValue(1);
11549
11550 // Transform as necessary
11551 SDValue CWD1 = DAG.getNode(ISD::AND, dl, MVT::i32, EFPC,
11552 DAG.getConstant(3, dl, MVT::i32));
11553 // RetVal = (CWD1 ^ (CWD1 >> 1)) ^ 1
11554 SDValue CWD2 = DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1,
11555 DAG.getNode(ISD::SRL, dl, MVT::i32, CWD1,
11556 DAG.getConstant(1, dl, MVT::i32)));
11557
11558 SDValue RetVal = DAG.getNode(ISD::XOR, dl, MVT::i32, CWD2,
11559 DAG.getConstant(1, dl, MVT::i32));
11560 RetVal = DAG.getZExtOrTrunc(RetVal, dl, Op.getValueType());
11561
11562 return DAG.getMergeValues({RetVal, Chain}, dl);
11563}
11564
11565SDValue SystemZTargetLowering::lowerVECREDUCE_ADD(SDValue Op,
11566 SelectionDAG &DAG) const {
11567 EVT VT = Op.getValueType();
11568 Op = Op.getOperand(0);
11569 EVT OpVT = Op.getValueType();
11570
11571 assert(OpVT.isVector() && "Operand type for VECREDUCE_ADD is not a vector.");
11572
11573 SDLoc DL(Op);
11574
11575 // load a 0 vector for the third operand of VSUM.
11576 SDValue Zero = DAG.getSplatBuildVector(OpVT, DL, DAG.getConstant(0, DL, VT));
11577
11578 // execute VSUM.
11579 switch (OpVT.getScalarSizeInBits()) {
11580 case 8:
11581 case 16:
11582 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Zero);
11583 [[fallthrough]];
11584 case 32:
11585 case 64:
11586 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::i128, Op,
11587 DAG.getBitcast(Op.getValueType(), Zero));
11588 break;
11589 case 128:
11590 break; // VSUM over v1i128 should not happen and would be a noop
11591 default:
11592 llvm_unreachable("Unexpected scalar size.");
11593 }
11594 // Cast to original vector type, retrieve last element.
11595 return DAG.getNode(
11596 ISD::EXTRACT_VECTOR_ELT, DL, VT, DAG.getBitcast(OpVT, Op),
11597 DAG.getConstant(OpVT.getVectorNumElements() - 1, DL, MVT::i32));
11598}
11599
11600static void printFunctionArgExts(const Function *F, raw_ostream &OS) {
11601 FunctionType *FT = F->getFunctionType();
11602 const AttributeList &Attrs = F->getAttributes();
11603 if (Attrs.hasRetAttrs())
11604 OS << Attrs.getAsString(AttributeList::ReturnIndex) << " ";
11605 OS << *F->getReturnType() << " @" << F->getName() << "(";
11606 for (unsigned I = 0, E = FT->getNumParams(); I != E; ++I) {
11607 if (I)
11608 OS << ", ";
11609 OS << *FT->getParamType(I);
11610 AttributeSet ArgAttrs = Attrs.getParamAttrs(I);
11611 for (auto A : {Attribute::SExt, Attribute::ZExt, Attribute::NoExt})
11612 if (ArgAttrs.hasAttribute(A))
11613 OS << " " << Attribute::getNameFromAttrKind(A);
11614 }
11615 if (F->isVarArg())
11616 OS << ", ...";
11617 OS << ")\n";
11618}
11619
11620bool SystemZTargetLowering::isInternal(const Function *Fn) const {
11621 std::map<const Function *, bool>::iterator Itr = IsInternalCache.find(Fn);
11622 if (Itr == IsInternalCache.end())
11623 Itr = IsInternalCache
11624 .insert(std::pair<const Function *, bool>(
11625 Fn, (Fn->hasLocalLinkage() && !Fn->hasAddressTaken())))
11626 .first;
11627 return Itr->second;
11628}
11629
11630bool SystemZTargetLowering::enableNarrowIntArgsVerification() const {
11631 if (!Subtarget.isTargetELF())
11632 return false;
11633
11634 if (auto V = toOptional(Subtarget.getCLOpts().argext_abi_check))
11635 return *V;
11636
11637#ifdef NDEBUG
11638 return false;
11639#endif
11640
11642}
11643
11644void SystemZTargetLowering::verifyNarrowIntegerArgs_Call(
11645 CallLoweringInfo &CLI, const SmallVectorImpl<ISD::OutputArg> &Outs,
11646 const Function *F, SDValue Callee) const {
11647 if (!enableNarrowIntArgsVerification())
11648 return;
11649 bool IsInternal = false;
11650 const Function *CalleeFn = nullptr;
11651 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
11652 if ((CalleeFn = dyn_cast<Function>(G->getGlobal())))
11653 IsInternal = isInternal(CalleeFn);
11654 bool C_ABI = CLI.CallConv == CallingConv::C && !IsInternal;
11655 if (!verifyNarrowIntegerArgs(C_ABI, Outs, CalleeFn, /*IsRet=*/false)) {
11656 errs() << "Callee: ";
11657 if (CalleeFn != nullptr)
11658 printFunctionArgExts(CalleeFn, errs());
11659 else
11660 errs() << "-\n";
11661 errs() << "Caller: ";
11663 if (CLI.CB)
11664 errs() << " " << *CLI.CB;
11665 llvm_unreachable("");
11666 }
11667 LLVM_DEBUG(dbgs() << "Outgoing call arguments verified as ABI compliant: ";
11668 if (CalleeFn != nullptr) printFunctionArgExts(CalleeFn, dbgs());
11669 else dbgs() << "-\n";);
11670}
11671
11672void SystemZTargetLowering::verifyNarrowIntegerArgs_Ret(
11674 const Function *F) const {
11675 if (!enableNarrowIntArgsVerification())
11676 return;
11677 bool C_ABI = CallConv == CallingConv::C && !isInternal(F);
11678 if (!verifyNarrowIntegerArgs(C_ABI, Outs, F, /*IsRet=*/true)) {
11679 errs() << "Returning from function: ";
11681 llvm_unreachable("");
11682 }
11683 LLVM_DEBUG(dbgs() << "Return argument verified as ABI compliant : ";
11685}
11686
11687// Verify that narrow integer arguments are extended according to the
11688// function header (calllee for a call, containing function for a ret).
11689// If C_ABI is true, an extension attribute must be present.
11690bool SystemZTargetLowering::verifyNarrowIntegerArgs(
11691 bool C_ABI, const SmallVectorImpl<ISD::OutputArg> &Outs,
11692 const Function *FunHeader, bool IsRet) const {
11693 if (IsRet && Outs.size() != 1)
11694 return true;
11695
11696 for (unsigned i = 0; i < Outs.size(); ++i) {
11697 EVT OrigArgVT = Outs[i].ArgVT;
11698 if (!OrigArgVT.isScalarInteger() || OrigArgVT.getSizeInBits() >= 64)
11699 continue;
11700 assert(Outs[i].VT == MVT::i32 && "Unexpected integer argument VT.");
11701 ISD::ArgFlagsTy Flags = Outs[i].Flags;
11702 unsigned OrigIdx = Outs[i].OrigArgIndex;
11703
11704 // Per the C ABI there must be an extension.
11705 if (C_ABI && !Flags.isSExt() && !Flags.isZExt() && !Flags.isNoExt()) {
11706 errs() << "ERROR: (C ABI violation) missing extension attribute on "
11707 << (IsRet ? "return value" : Twine("arg ") + Twine(OrigIdx))
11708 << ".\n";
11709 return false;
11710 }
11711
11712 // Flags should reflect the attributes of the function header.
11713 if (FunHeader) {
11714 const AttributeList &FunAttrs = FunHeader->getAttributes();
11715 const AttributeSet Attrs =
11716 IsRet ? FunAttrs.getRetAttrs() : FunAttrs.getParamAttrs(OrigIdx);
11717 if (Attrs.hasAttribute(Attribute::SExt) && !Flags.isSExt()) {
11718 errs() << "ERROR: Missing SExt on arg " << OrigIdx << ".\n";
11719 return false;
11720 }
11721 if (Attrs.hasAttribute(Attribute::ZExt) && !Flags.isZExt()) {
11722 errs() << "ERROR: Missing ZExt on arg " << OrigIdx << ".\n";
11723 return false;
11724 }
11725 }
11726 }
11727
11728 return true;
11729}
11730
11732 Module &M, const LibcallLoweringInfo &Libcalls) const {
11733 StringRef GuardMode = M.getStackProtectorGuard();
11734
11735 // In the TLS case, no symbol needs to be inserted.
11736 if (GuardMode == "tls" || GuardMode.empty())
11737 return;
11738
11739 // Otherwise (in the global case), insert the appropriate global variable.
11741}
unsigned NumParts
return SDValue()
const AArch64Subtarget & Subtarget
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
uint64_t uint64_t
uint64_t Imm
AMDGPU Register Bank Select
static bool isZeroVector(SDValue N)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis false
Function Alias Analysis Results
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, const CCValAssign &VA, const SDLoc &DL)
static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, const CCValAssign &VA, const SDLoc &DL)
#define Check(C,...)
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
static bool isSelectPseudo(MachineInstr &MI)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
static bool isUndef(const MachineInstr &MI)
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t High
uint64_t IntrinsicInst * II
#define P(N)
static constexpr MCPhysReg SPReg
SmallVector< MachineOperand, 4 > Cond
int64_t C1
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
MachineInstr *& Lo
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
const char * Msg
This file defines the SmallSet class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static SDValue getI128Select(SelectionDAG &DAG, const SDLoc &DL, Comparison C, SDValue TrueOp, SDValue FalseOp)
static SmallVector< SDValue, 4 > simplifyAssumingCCVal(SDValue &Val, SDValue &CC, SelectionDAG &DAG)
static void adjustForTestUnderMask(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static void adjustForLTGFR(Comparison &C)
static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static SDValue joinDwords(SelectionDAG &DAG, const SDLoc &DL, SDValue Op0, SDValue Op1)
#define CONV(X)
static bool isOnlyUsedByStores(SDValue StoredVal, SelectionDAG &DAG)
static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT, unsigned Opcode, SDValue Op0, SDValue Op1, SDValue &Even, SDValue &Odd)
static void adjustForRedundantAnd(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static SDValue lowerAddrSpaceCast(SDValue Op, SelectionDAG &DAG)
static SDValue buildScalarToVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT, SDValue Value)
static SDValue lowerI128ToGR128(SelectionDAG &DAG, SDValue In)
static bool isSimpleShift(SDValue N, unsigned &ShiftVal)
static SDValue mergeHighParts(SelectionDAG &DAG, const SDLoc &DL, unsigned MergedBits, EVT VT, SDValue Op0, SDValue Op1)
static bool isI128MovedToParts(LoadSDNode *LD, SDNode *&LoPart, SDNode *&HiPart)
static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1)
static uint32_t findZeroVectorIdx(SDValue *Ops, unsigned Num)
static bool isVectorElementSwap(ArrayRef< int > M, EVT VT)
static void getCSAddressAndShifts(SDValue Addr, SelectionDAG &DAG, SDLoc DL, SDValue &AlignedAddr, SDValue &BitShift, SDValue &NegBitShift)
static bool isShlDoublePermute(const SmallVectorImpl< int > &Bytes, unsigned &StartIndex, unsigned &OpNo0, unsigned &OpNo1)
static SDValue getPermuteNode(SelectionDAG &DAG, const SDLoc &DL, const Permute &P, SDValue Op0, SDValue Op1)
static SDNode * emitIntrinsicWithCCAndChain(SelectionDAG &DAG, SDValue Op, unsigned Opcode)
static SDValue getCCResult(SelectionDAG &DAG, SDValue CCReg)
static void adjustForStackGuardCompare(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode, unsigned &CCValid)
static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend, SDValue Op0, SDValue Op1, SDValue &Hi, SDValue &Lo)
static bool isF128MovedToParts(LoadSDNode *LD, SDNode *&LoPart, SDNode *&HiPart)
static void createPHIsForSelects(SmallVector< MachineInstr *, 8 > &Selects, MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB, MachineBasicBlock *SinkMBB)
static SDValue getGeneralPermuteNode(SelectionDAG &DAG, const SDLoc &DL, SDValue *Ops, const SmallVectorImpl< int > &Bytes)
static unsigned getVectorComparisonOrInvert(ISD::CondCode CC, CmpMode Mode, bool &Invert)
static unsigned CCMaskForCondCode(ISD::CondCode CC)
static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static void adjustForFNeg(Comparison &C)
static bool isScalarToVector(SDValue Op)
static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue CCReg, unsigned CCValid, unsigned CCMask)
static bool matchPermute(const SmallVectorImpl< int > &Bytes, const Permute &P, unsigned &OpNo0, unsigned &OpNo1)
static bool isAddCarryChain(SDValue Carry)
static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static MachineOperand earlyUseOperand(MachineOperand Op)
static bool canUseSiblingCall(const CCState &ArgCCInfo, SmallVectorImpl< CCValAssign > &ArgLocs, SmallVectorImpl< ISD::OutputArg > &Outs)
static bool getzOSCalleeAndADA(SelectionDAG &DAG, SDValue &Callee, SDValue &ADA, SDLoc &DL, SDValue &Chain)
static SDValue convertToF16(SDValue Op, SelectionDAG &DAG)
static bool combineCCMask(SDValue &CCReg, int &CCValid, int &CCMask, SelectionDAG &DAG)
static bool shouldSwapCmpOperands(const Comparison &C)
static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType)
static SDValue getADAEntry(SelectionDAG &DAG, SDValue Val, SDLoc DL, unsigned Offset, bool LoadAdr=false)
static SDNode * emitIntrinsicWithCC(SelectionDAG &DAG, SDValue Op, unsigned Opcode)
static void adjustForSubtraction(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static bool getVPermMask(SDValue ShuffleOp, SmallVectorImpl< int > &Bytes)
static const Permute PermuteForms[]
static bool isI128MovedFromParts(SDValue Val, SDValue &LoPart, SDValue &HiPart)
static std::pair< SDValue, int > findCCUse(const SDValue &Val, unsigned Depth=0)
static bool isSubBorrowChain(SDValue Carry)
static void adjustICmp128(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static bool analyzeArgSplit(const SmallVectorImpl< ArgTy > &Args, SmallVector< CCValAssign, 16 > &ArgLocs, unsigned I, MVT &PartVT, unsigned &NumParts)
static bool isInBoundsConstantVectorIndex(EVT VecVT, SDValue Idx)
static APInt getDemandedSrcElements(SDValue Op, const APInt &DemandedElts, unsigned OpNo)
static SDValue getAbsolute(SelectionDAG &DAG, const SDLoc &DL, SDValue Op, bool IsNegative)
static unsigned computeNumSignBitsBinOp(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth, unsigned OpNo)
static SDValue expandBitCastI128ToF128(SelectionDAG &DAG, SDValue Src, const SDLoc &SL)
static SDValue tryBuildVectorShuffle(SelectionDAG &DAG, BuildVectorSDNode *BVN)
static SDValue convertFromF16(SDValue Op, SDLoc DL, SelectionDAG &DAG)
static unsigned getVectorComparison(ISD::CondCode CC, CmpMode Mode)
static SDValue lowerGR128ToI128(SelectionDAG &DAG, SDValue In)
static SDValue MergeInputChains(SDNode *N1, SDNode *N2)
static SDValue expandBitCastF128ToI128(SelectionDAG &DAG, SDValue Src, const SDLoc &SL)
static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask, uint64_t Mask, uint64_t CmpVal, unsigned ICmpType)
static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid)
static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL, SDValue Op, SDValue Chain)
static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1, ISD::CondCode Cond, const SDLoc &DL, SDValue Chain=SDValue(), bool IsSignaling=false)
static bool checkCCKill(MachineInstr &MI, MachineBasicBlock *MBB)
static Register forceReg(MachineInstr &MI, MachineOperand &Base, const SystemZInstrInfo *TII)
static bool is32Bit(EVT VT)
static std::pair< unsigned, const TargetRegisterClass * > parseRegisterNumber(StringRef Constraint, const TargetRegisterClass *RC, const unsigned *Map, unsigned Size)
static unsigned detectEvenOddMultiplyOperand(const SelectionDAG &DAG, const SystemZSubtarget &Subtarget, SDValue &Op)
static bool matchDoublePermute(const SmallVectorImpl< int > &Bytes, const Permute &P, SmallVectorImpl< int > &Transform)
static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode, SDValue Call, unsigned CCValid, uint64_t CC, ISD::CondCode Cond)
static Register getOrCreateADAVirtualRegister(MachineFunction &MF)
static SDValue buildFPVecFromScalars4(SelectionDAG &DAG, const SDLoc &DL, EVT VT, SmallVectorImpl< SDValue > &Elems, unsigned Pos)
static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg)
static AddressingMode getLoadStoreAddrMode(bool HasVector, Type *Ty)
static void printFunctionArgExts(const Function *F, raw_ostream &OS)
static SDValue buildMergeScalars(SelectionDAG &DAG, const SDLoc &DL, EVT VT, SDValue Op0, SDValue Op1)
static void computeKnownBitsBinOp(const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth, unsigned OpNo)
static bool getShuffleInput(const SmallVectorImpl< int > &Bytes, unsigned Start, unsigned BytesPerElement, int &Base)
static AddressingMode supportedAddressingMode(Instruction *I, bool HasVector)
static bool isF128MovedFromParts(SDValue Val, SDValue &LoPart, SDValue &HiPart)
static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
Value * LHS
BinaryOperator * Mul
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:225
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:254
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool isSingleWord() const
Determine if this APInt just has one word to store value.
Definition APInt.h:318
LLVM_ABI void insertBits(const APInt &SubBits, unsigned bitPosition)
Insert the bits from a smaller APInt starting at bitPosition.
Definition APInt.cpp:393
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:860
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
an instruction that atomically reads a memory location, combines it with another value,...
@ Add
*p = old + v
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
BinOp getOperation() const
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:448
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
Definition Attributes.h:532
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
static LLVM_ABI StringRef getNameFromAttrKind(Attribute::AttrKind AttrKind)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
A "pseudo-class" with methods for operating on BUILD_VECTORs.
LLVM_ABI bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef, unsigned &SplatBitSize, bool &HasAnyUndefs, unsigned MinSplatBits=0, bool isBigEndian=false) const
Check if this is a constant splat, and if so, find the smallest element size that splats the vector.
LLVM_ABI bool isConstant() const
CCState - This class holds information needed while lowering arguments and return values.
LLVM_ABI void AnalyzeCallResult(const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn Fn)
AnalyzeCallResult - Analyze the return values of a call, incorporating info about the passed values i...
LLVM_ABI bool CheckReturn(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
CheckReturn - Analyze the return values of a function, returning true if the return can be performed ...
LLVM_ABI void AnalyzeReturn(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
AnalyzeReturn - Analyze the returned values of a return, incorporating info about the result values i...
LLVM_ABI void AnalyzeCallOperands(const SmallVectorImpl< ISD::OutputArg > &Outs, CCAssignFn Fn)
AnalyzeCallOperands - Analyze the outgoing arguments to a call, incorporating info about the passed v...
uint64_t getStackSize() const
Returns the size of the currently allocated portion of the stack.
LLVM_ABI void AnalyzeFormalArguments(const SmallVectorImpl< ISD::InputArg > &Ins, CCAssignFn Fn)
AnalyzeFormalArguments - Analyze an array of argument values, incorporating info about the formals in...
CCValAssign - Represent assignment of one arg/retval to a location.
Register getLocReg() const
LocInfo getLocInfo() const
bool needsCustom() const
bool isExtInLoc() const
int64_t getLocMemOffset() const
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
This class represents a function call, abstracting a target machine's calling convention.
bool isTailCall() const
MachineConstantPoolValue * getMachineCPVal() const
const Constant * getConstVal() const
uint64_t getZExtValue() const
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI unsigned getPointerSize(unsigned AS=0) const
The pointer representation size in bytes, rounded up to a whole number of bytes.
A debug info location.
Definition DebugLoc.h:127
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:317
bool hasAddressTaken(const User **=nullptr, bool IgnoreCallbackUses=false, bool IgnoreAssumeLikeCalls=true, bool IngoreLLVMUsed=false, bool IgnoreARCAttachedCall=false, bool IgnoreCastedDirectCall=false) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
Definition Function.cpp:941
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
uint64_t getFnAttributeAsParsedInteger(StringRef Kind, uint64_t Default=0) const
For a string attribute Kind, parse attribute as an integer.
Definition Function.cpp:778
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:730
bool hasLocalLinkage() const
bool hasPrivateLinkage() const
bool hasInternalLinkage() const
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Tracks which library functions to use for a particular subtarget or function.
An instruction for reading from memory.
This class is used to represent ISD::LOAD nodes.
Machine Value Type.
static auto integer_fixedlen_vector_valuetypes()
SimpleValueType SimpleTy
uint64_t getScalarSizeInBits() const
bool isVector() const
Return true if this is a vector value type.
static auto integer_valuetypes()
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
static auto fixedlen_vector_valuetypes()
ElementCount getVectorElementCount() const
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
static MVT getVectorVT(MVT VT, unsigned NumElements)
static MVT getIntegerVT(unsigned BitWidth)
static auto fp_valuetypes()
MVT getScalarType() const
If this is a vector, return the element type, otherwise return this.
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
void setMachineBlockAddressTaken()
Set this block to indicate that its address is used as something other than the target of a terminato...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
void setMaxCallFrameSize(uint64_t S)
LLVM_ABI int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
void setFrameAddressIsTaken(bool T)
uint64_t getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call.
void setReturnAddressIsTaken(bool s)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
void push_back(MachineBasicBlock *MBB)
reverse_iterator rbegin()
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineFunctionProperties & getProperties() const
Get the function properties.
Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & setMemRefs(ArrayRef< MachineMemOperand * > MMOs) const
const MachineInstrBuilder & setOperandDead(unsigned OpIdx) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addFrameIndex(int Idx) const
const MachineInstrBuilder & addRegMask(const uint32_t *Mask) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
Representation of each machine instruction.
bool killsRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr kills the specified register.
const MachineOperand & getOperand(unsigned i) const
A description of a memory reference used in the backend.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
Register getReg() const
getReg - Returns the register number.
LLVM_ABI bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool hasOneUse() const
Return true if there is exactly one use of this node.
SDNodeFlags getFlags() const
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
unsigned getNumOperands() const
Return the number of values used by this operation.
unsigned getMachineOpcode() const
This may only be called if isMachineOpcode returns true.
const SDValue & getOperand(unsigned Num) const
bool hasNUsesOfValue(unsigned NUses, unsigned Value) const
Return true if there are exactly NUSES uses of the indicated value.
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
iterator_range< user_iterator > users()
void setFlags(SDNodeFlags NewFlags)
Represents a use of a SDNode.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
bool isMachineOpcode() const
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
ISD::CondCode getOperandCondCode(unsigned i) const
const APInt & getConstantOperandAPInt(unsigned i) const
uint64_t getScalarValueSizeInBits() const
unsigned getResNo() const
get the index which selects a specific result in the SDNode
uint64_t getConstantOperandVal(unsigned i) const
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
unsigned getMachineOpcode() const
unsigned getOpcode() const
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
SDValue getExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT, unsigned Opcode)
Convert Op, which must be of integer type, to the integer type VT, by either any/sign/zero-extending ...
const TargetSubtargetInfo & getSubtarget() const
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI SDValue getAtomicLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT MemVT, EVT VT, SDValue Chain, SDValue Ptr, MachineMemOperand *MMO)
LLVM_ABI SDValue getConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offs=0, bool isT=false, unsigned TargetFlags=0)
LLVM_ABI bool isConstantIntBuildVectorOrConstantInt(SDValue N, bool AllowOpaques=true) const
Test whether the given value is a constant int or similar node.
LLVM_ABI SDValue UnrollVectorOp(SDNode *N, unsigned ResNE=0)
Utility function used by legalize and lowering to "unroll" a vector operation by splitting out the sc...
LLVM_ABI SDValue getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, unsigned SrcAS, unsigned DestAS, const SDNodeFlags Flags=SDNodeFlags())
Return an AddrSpaceCastSDNode.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
SDValue getGLOBAL_OFFSET_TABLE(EVT VT)
Return a GLOBAL_OFFSET_TABLE node. This does not have a useful SDLoc.
LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, LocationSize Size=LocationSize::precise(0), const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
LLVM_ABI SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDValue Chain, SDValue Ptr, SDValue Val, MachineMemOperand *MMO)
Gets a node for an atomic op, produces result (if relevant) and chain and takes 2 operands.
void addNoMergeSiteInfo(const SDNode *Node, bool NoMerge)
Set NoMergeSiteInfo to be associated with Node if NoMerge is true.
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
const TargetLowering & getTargetLoweringInfo() const
SDValue getTargetJumpTable(int JTI, EVT VT, unsigned TargetFlags=0)
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2, SDValue InGlue, const SDLoc &DL)
Return a new CALLSEQ_END node, which always must have a glue result (to ensure it's not CSE'd).
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI bool isSplatValue(SDValue V, const APInt &DemandedElts, APInt &UndefElts, unsigned Depth=0) const
Test whether V has a splatted value for all the demanded elements.
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
LLVM_ABI SDValue getNegative(SDValue Val, const SDLoc &DL, EVT VT)
Create negative operation as (SUB 0, Val).
const DataLayout & getDataLayout() const
SDValue getTargetFrameIndex(int FI, EVT VT)
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
SDValue getSignedTargetConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
SDValue getSplatVector(EVT VT, const SDLoc &DL, SDValue Op)
SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, const SDLoc &DL)
Return a new CALLSEQ_START node, that starts new call frame, in which InSize bytes are set up inside ...
LLVM_ABI bool SignBitIsZero(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero.
LLVM_ABI SDValue getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand)
A convenience function for creating TargetInstrInfo::EXTRACT_SUBREG nodes.
LLVM_ABI SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI std::pair< SDValue, SDValue > getStrictFPExtendOrRound(SDValue Op, SDValue Chain, const SDLoc &DL, EVT VT)
Convert Op, which must be a STRICT operation of float type, to the float type VT, by either extending...
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of float type, to the float type VT, by either extending or rounding (by tr...
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI unsigned ComputeNumSignBits(SDValue Op, unsigned Depth=0) const
Return the number of times the sign bit of the register is replicated into the other bits.
SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, unsigned TargetFlags=0)
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op)
Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all elements.
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset)
Create an add instruction with appropriate flags when used for addressing some offset of an object.
LLVMContext * getContext() const
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment)
Create a stack temporary based on the size in bytes and the alignment.
LLVM_ABI SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
SDValue getTargetConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offset=0, unsigned TargetFlags=0)
LLVM_ABI SDValue getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand, SDValue Subreg)
A convenience function for creating TargetInstrInfo::INSERT_SUBREG nodes.
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
LLVM_ABI std::pair< SDValue, SDValue > SplitScalar(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the scalar node with EXTRACT_ELEMENT using the provided VTs and return the low/high part.
LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
This SDNode is used to implement the code generator support for the llvm IR shufflevector instruction...
ArrayRef< int > getMask() const
const_iterator begin() const
Definition SmallSet.h:216
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
size_type size() const
Definition SmallSet.h:171
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void resize(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
This class is used to represent ISD::STORE nodes.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:482
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition StringRef.h:712
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
iterator end() const
Definition StringRef.h:116
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
A SystemZ-specific class detailing special use registers particular for calling conventions.
static SystemZConstantPoolValue * Create(const GlobalValue *GV, SystemZCP::SystemZCPModifier Modifier)
SystemZCallingConventionRegisters * getSpecialRegisters() const
AtomicExpansionKind shouldExpandAtomicRMWInIR(const AtomicRMWInst *RMW) const override
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all.
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
This callback is invoked for operations that are unsupported by the target, which are registered to u...
EVT getOptimalMemOpType(LLVMContext &Context, const MemOp &Op, const AttributeList &FuncAttributes) const override
Returns the target specific optimal type for load and store operations as a result of memset,...
bool hasInlineStackProbe(const MachineFunction &MF) const override
Returns true if stack probing through inline assembly is requested.
MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *BB) const override
This method should be implemented by targets that mark instructions with the 'usesCustomInserter' fla...
MachineBasicBlock * emitEHSjLjSetJmp(MachineInstr &MI, MachineBasicBlock *MBB) const
AtomicExpansionKind shouldCastAtomicLoadInIR(LoadInst *LI) const override
Returns how the given (atomic) load should be cast by the IR-level AtomicExpand pass.
EVT getSetCCResultType(const DataLayout &DL, LLVMContext &, EVT) const override
Return the ValueType of the result of SETCC operations.
bool allowTruncateForTailCall(Type *, Type *) const override
Return true if a truncation from FromTy to ToTy is permitted when deciding whether a call is in tail ...
SDValue LowerAsmOutputForConstraint(SDValue &Chain, SDValue &Flag, const SDLoc &DL, const AsmOperandInfo &Constraint, SelectionDAG &DAG) const override
SDValue LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, const SmallVectorImpl< SDValue > &OutVals, const SDLoc &DL, SelectionDAG &DAG) const override
This hook must be implemented to lower outgoing return values, described by the Outs array,...
MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
MachineBasicBlock * emitEHSjLjLongJmp(MachineInstr &MI, MachineBasicBlock *MBB) const
bool CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, const SmallVectorImpl< ISD::OutputArg > &Outs, LLVMContext &Context, const Type *RetTy) const override
This hook should be implemented to check whether the return values described by the Outs array can fi...
bool canMergeStoresTo(unsigned AS, EVT MemVT, const MachineFunction &MF) const override
Returns if it's reasonable to merge stores to MemVT size.
std::pair< SDValue, SDValue > makeExternalCall(SDValue Chain, SelectionDAG &DAG, const char *CalleeName, EVT RetVT, ArrayRef< SDValue > Ops, CallingConv::ID CallConv, bool IsSigned, SDLoc DL, bool DoesNotReturn, bool IsReturnValueUsed) const
void insertSSPDeclarations(Module &M, const LibcallLoweringInfo &Libcalls) const override
Insert SSP declaration if global stack protector is used.
bool mayBeEmittedAsTailCall(const CallInst *CI) const override
Return true if the target may be able emit the call instruction as a tail call.
bool splitValueIntoRegisterParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, unsigned NumParts, MVT PartVT, std::optional< CallingConv::ID > CC) const override
Target-specific splitting of values into parts that fit a register storing a legal type.
bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I=nullptr) const override
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const override
Certain targets require unusual breakdowns of certain types.
bool isGuaranteedNotToBeUndefOrPoisonForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, UndefPoisonKind Kind, unsigned Depth) const override
Return true if this function can prove that Op is never poison and, Kind can be used to track poison ...
SystemZTargetLowering(const TargetMachine &TM, const SystemZSubtarget &STI)
bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, EVT VT) const override
Return true if an FMA operation is faster than a pair of fmul and fadd instructions.
FPImmAction getFPImmAction(const APFloat &Imm, EVT VT, bool ForCodeSize) const override
Returns how the legalizer should materialize the specified FP immediate.
bool isLegalICmpImmediate(int64_t Imm) const override
Return true if the specified immediate is legal icmp immediate, that is the target has icmp instructi...
std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const override
Given a physical register constraint (e.g.
bool isTypeDesirableForOp(SDNode *N, EVT VT) const override
Overload that takes the specific node being optimized.
TargetLowering::ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const override
Examine constraint string and operand type and determine a weight value.
bool allowsMisalignedMemoryAccesses(EVT VT, unsigned AS, Align Alignment, MachineMemOperand::Flags Flags, unsigned *Fast) const override
Determine if the target supports unaligned memory accesses.
const MCPhysReg * getScratchRegisters(CallingConv::ID CC) const override
Returns a 0 terminated array of registers that can be safely used as scratch registers.
TargetLowering::ConstraintType getConstraintType(StringRef Constraint) const override
Given a constraint, return the type of constraint it is for this target.
Register getExceptionSelectorRegister(ExceptionHandling EH, const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception typeid on entry to a la...
SDValue joinRegisterPartsIntoValue(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, MVT PartVT, EVT ValueVT, std::optional< CallingConv::ID > CC) const override
Target-specific combining of register parts into its original value.
bool isTruncateFree(Type *, Type *) const override
Return true if it's free to truncate a value of type FromTy to type ToTy.
SDValue useLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, MVT VT, SDValue Arg, SDLoc DL, SDValue Chain, bool IsStrict) const
unsigned ComputeNumSignBitsForTargetNode(SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const override
Determine the number of bits in the operation that are sign bits.
void LowerOperationWrapper(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
This callback is invoked by the type legalizer to legalize nodes with an illegal operand type but leg...
SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override
This method will be invoked for all target nodes and for any target-independent nodes that the target...
SDValue LowerCall(CallLoweringInfo &CLI, SmallVectorImpl< SDValue > &InVals) const override
This hook must be implemented to lower calls into the specified DAG.
bool isLegalAddImmediate(int64_t Imm) const override
Return true if the specified immediate is legal add immediate, that is the target has add instruction...
CondMergingParams getJumpConditionMergingParams(Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs, const Function *F) const override
TargetLoweringBase::LegalizeTypeAction getPreferredVectorAction(MVT VT) const override
Return the preferred vector type legalization action.
bool findOptimalMemOpLowering(LLVMContext &Context, std::vector< EVT > &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, unsigned SrcAS, const AttributeList &FuncAttributes, EVT *LargestVT=nullptr) const override
Determines the optimal series of memory ops to replace the memset / memcpy.
void ReplaceNodeResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
This callback is invoked when a node result type is illegal for the target, and the operation was reg...
void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const override
Lower the specified operand into the Ops vector.
Register getExceptionPointerRegister(ExceptionHandling EH, const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception address on entry to an ...
unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const override
Certain targets such as MIPS require that some types such as vectors are always broken down into scal...
bool aggressivelyPreferBuildVectorSources(EVT VecVT) const override
AtomicExpansionKind shouldCastAtomicStoreInIR(StoreInst *SI) const override
Returns how the given (atomic) store should be cast by the IR-level AtomicExpand pass into.
Register getRegisterByName(const char *RegName, LLT VT, const MachineFunction &MF) const override
Return the register ID of the name passed in.
bool hasAndNot(SDValue Y) const override
Return true if the target has a bitwise and-not operation: X = ~A & B This can be used to simplify se...
SDValue LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl< ISD::InputArg > &Ins, const SDLoc &DL, SelectionDAG &DAG, SmallVectorImpl< SDValue > &InVals) const override
This hook must be implemented to lower the incoming (formal) arguments, described by the Ins array,...
void computeKnownBitsForTargetNode(const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth=0) const override
Determine which of the bits specified in Mask are known to be either zero or one and return them in t...
unsigned getStackProbeSize(const MachineFunction &MF) const
XPLINK64 calling convention specific use registers Particular to z/OS when in 64 bit mode.
Information about stack frame layout on the target.
unsigned getStackAlignment() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
TargetInstrInfo - Interface to description of machine instruction set.
void setBooleanVectorContents(BooleanContent Ty)
Specify how the target extends the result of a vector boolean value from a vector of i1 to a wider ty...
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
unsigned MaxStoresPerMemcpyOptSize
Likewise for functions with the OptSize attribute.
MachineBasicBlock * emitPatchPoint(MachineInstr &MI, MachineBasicBlock *MBB) const
Replace/modify any TargetFrameIndex operands with a targte-dependent sequence of memory operands that...
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
const TargetMachine & getTargetMachine() const
virtual unsigned getNumRegistersForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain targets require unusual breakdowns of certain types.
virtual MVT getRegisterTypeForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT) const
Certain combinations of ABIs, Targets and features require that types are legal for some operations a...
LegalizeTypeAction
This enum indicates whether a types are legal for a target, and if not, what action should be used to...
virtual void insertSSPDeclarations(Module &M, const LibcallLoweringInfo &Libcalls) const
Inserts necessary declarations for SSP (stack protection) purpose.
void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits)
Set the maximum atomic operation size supported by the backend.
virtual TargetLoweringBase::LegalizeTypeAction getPreferredVectorAction(MVT VT) const
Return the preferred vector type legalization action.
void setAtomicLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Let target indicate that an extending atomic load of the specified type is legal.
virtual unsigned getVectorTypeBreakdownForCallingConv(LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT, unsigned &NumIntermediates, MVT &RegisterVT) const
Certain targets such as MIPS require that some types such as vectors are always broken down into scal...
Register getStackPointerRegisterToSaveRestore() const
If a physical register, this specifies the register that llvm.savestack/llvm.restorestack should save...
void setMinFunctionAlignment(Align Alignment)
Set the target's minimum function alignment.
unsigned MaxStoresPerMemsetOptSize
Likewise for functions with the OptSize attribute.
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of a boolean value from i1 to a wider type.
unsigned MaxStoresPerMemmove
Specify maximum number of store instructions per memmove call.
void computeRegisterProperties(const TargetRegisterInfo *TRI)
Once all of the register classes are added, this allows us to compute derived properties we expose.
unsigned MaxStoresPerMemmoveOptSize
Likewise for functions with the OptSize attribute.
void addRegisterClass(MVT VT, const TargetRegisterClass *RC)
Add the specified register class as an available regclass for the specified value type.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
void setPrefFunctionAlignment(Align Alignment)
Set the target's preferred function alignment.
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
unsigned MaxStoresPerMemset
Specify maximum number of store instructions per memset call.
FPImmAction
How the legalizer should materialize a floating-point immediate.
@ ConstantPool
Load the immediate from the constant pool.
@ Legal
The target can instruction select the immediate natively.
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
virtual const TargetRegisterClass * getRepRegClassFor(MVT VT) const
Return the 'representative' register class for the specified value type.
void setStackPointerRegisterToSaveRestore(Register R)
If set to a physical register, this specifies the register that llvm.savestack/llvm....
AtomicExpansionKind
Enum that specifies what an atomic load/AtomicRMWInst is expanded to, if at all.
void setTargetDAGCombine(ArrayRef< ISD::NodeType > NTs)
Targets should invoke this method for each target independent node that they want to provide a custom...
void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified load with extension does not work with the specified type and indicate wh...
virtual bool shouldSignExtendTypeInLibCall(Type *Ty, bool IsSigned) const
Returns true if arguments should be sign-extended in lib calls.
std::vector< ArgListEntry > ArgListTy
unsigned MaxStoresPerMemcpy
Specify maximum number of store instructions per memcpy call.
virtual MVT getPointerMemTy(const DataLayout &DL, uint32_t AS=0) const
Return the in-memory pointer type for the given address space, defaults to the pointer type from the ...
void setSchedulingPreference(Sched::Preference Pref)
Specify the target scheduling preference.
LegalizeAction getOperationAction(unsigned Op, EVT VT) const
Return how this operation should be treated: either it is legal, needs to be promoted to a larger siz...
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
virtual bool findOptimalMemOpLowering(LLVMContext &Context, std::vector< EVT > &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, unsigned SrcAS, const AttributeList &FuncAttributes, EVT *LargestVT=nullptr) const
Determines the optimal series of memory ops to replace the memset / memcpy.
virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, SelectionDAG &DAG) const
Lower TLS global address SDNode for target independent emulated TLS model.
virtual bool isTypeDesirableForOp(unsigned, EVT VT) const
Return true if the target has native support for the specified value type and it is 'desirable' to us...
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
virtual ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const
Examine constraint string and operand type and determine a weight value.
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
TargetLowering(const TargetLowering &)=delete
virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
std::pair< SDValue, SDValue > makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl, EVT RetVT, ArrayRef< SDValue > Ops, MakeLibCallOptions CallOptions, const SDLoc &dl, SDValue Chain=SDValue()) const
Returns a pair of (return value, chain).
Primary interface to the complete machine description for the target machine.
TLSModel::Model getTLSModel(const GlobalValue *GV) const
Returns the TLS model which should be used for the given global variable.
bool useEmulatedTLS() const
Returns true if this target uses emulated TLS.
TargetOptions Options
CodeModel::Model getCodeModel() const
Returns the code model.
unsigned VerifyArgABICompliance
When set to true, call/return argument extensions of narrow integers are verified in the target backe...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
user_iterator user_begin()
Definition Value.h:404
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI bool isConstantSplatVector(SDValue V, APInt &SplatValue)
Node predicates.
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
LLVM_ABI bool isConstantSplatVectorAllZeros(SDValue V, bool BuildVectorOnly=false)
Return true if the specified value is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are 0 ...
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:851
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:263
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:516
@ POISON
POISON - A poison node.
Definition ISDOpcodes.h:238
@ EH_SJLJ_LONGJMP
OUTCHAIN = EH_SJLJ_LONGJMP(INCHAIN, buffer) This corresponds to the eh.sjlj.longjmp intrinsic.
Definition ISDOpcodes.h:170
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:277
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:811
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ATOMIC_STORE
OUTCHAIN = ATOMIC_STORE(INCHAIN, val, ptr) This corresponds to "store atomic" instruction.
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:885
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:523
@ PSEUDO_FMIN
PSEUDO_FMIN is strictly equivalent to op0 olt op1 ?
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:222
@ GlobalAddress
Definition ISDOpcodes.h:90
@ ATOMIC_CMP_SWAP_WITH_SUCCESS
Val, Success, OUTCHAIN = ATOMIC_CMP_SWAP_WITH_SUCCESS(INCHAIN, ptr, cmp, swap) N.b.
@ STRICT_FMINIMUM
Definition ISDOpcodes.h:476
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:912
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:771
@ MEMBARRIER
MEMBARRIER - Compiler barrier only; generate a no-op.
@ ATOMIC_FENCE
OUTCHAIN = ATOMIC_FENCE(INCHAIN, ordering, scope) This corresponds to the fence instruction.
@ SIGN_EXTEND_VECTOR_INREG
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition ISDOpcodes.h:942
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:282
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ STRICT_PSEUDO_FMAX
Definition ISDOpcodes.h:465
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:256
@ STRICT_FSQRT
Constrained versions of libm-equivalent floating point intrinsics.
Definition ISDOpcodes.h:441
@ BUILTIN_OP_END
BUILTIN_OP_END - This must be the last enum value in this list.
@ GlobalTLSAddress
Definition ISDOpcodes.h:91
@ CTLZ_ZERO_POISON
Definition ISDOpcodes.h:820
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:876
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:731
@ STRICT_UINT_TO_FP
Definition ISDOpcodes.h:490
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:681
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ STRICT_PSEUDO_FMIN
Definition ISDOpcodes.h:464
@ FSINCOS
FSINCOS - Compute both fsin and fcos as a single operation.
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:355
@ BR_JT
BR_JT - Jumptable branch.
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:553
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:828
@ ATOMIC_LOAD
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:235
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:249
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:688
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:351
@ VECREDUCE_ADD
Integer reductions may have a result type larger than the vector element type.
@ GET_ROUNDING
Returns current rounding mode: -1 Undefined 0 Round to 0 1 Round to nearest, ties to even 2 Round to ...
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:720
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:793
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:659
@ STRICT_FMAXIMUM
Definition ISDOpcodes.h:475
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:581
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:882
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:843
@ FMINNUM
FMINNUM/FMAXNUM - Same semantics as the llvm.minnum/maxnum intrinsics.
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ ANY_EXTEND_VECTOR_INREG
ANY_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register any-extension of the low la...
Definition ISDOpcodes.h:931
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:920
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:751
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:837
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:331
@ STRICT_SINT_TO_FP
STRICT_[US]INT_TO_FP - Convert a signed or unsigned integer to a floating point value.
Definition ISDOpcodes.h:489
@ STRICT_FROUNDEVEN
Definition ISDOpcodes.h:469
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:112
@ STRICT_FP_TO_UINT
Definition ISDOpcodes.h:483
@ PEXT
Parallel bit extract (compress) and parallel bit deposit (expand).
Definition ISDOpcodes.h:807
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:505
@ STRICT_FP_TO_SINT
STRICT_FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:482
@ FMINIMUM
FMINIMUM/FMAXIMUM - Same semantics as the llvm.minimum/maximum intrinsics.
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:958
@ READCYCLECOUNTER
READCYCLECOUNTER - This corresponds to the readcyclecounter intrinsic.
@ STRICT_FP_EXTEND
X = STRICT_FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:510
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:763
@ TRAP
TRAP - Trapping instruction.
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ STRICT_FADD
Constrained versions of the binary floating point operators.
Definition ISDOpcodes.h:430
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:570
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ ATOMIC_SWAP
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN,...
@ CTTZ_ZERO_POISON
Bit counting operators with a poisoned result for zero inputs.
Definition ISDOpcodes.h:819
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:991
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:953
@ ADDRSPACECAST
ADDRSPACECAST - This operator converts between pointers of different address spaces.
@ STRICT_FNEARBYINT
Definition ISDOpcodes.h:461
@ EH_SJLJ_SETJMP
RESULT, OUTCHAIN = EH_SJLJ_SETJMP(INCHAIN, buffer) This corresponds to the eh.sjlj....
Definition ISDOpcodes.h:164
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:888
@ BRCOND
BRCOND - Conditional branch.
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:865
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:64
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:539
@ GET_DYNAMIC_AREA_OFFSET
GET_DYNAMIC_AREA_OFFSET - get offset from native SP to the address of the most recent dynamic alloca.
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - Same semantics as the llvm.minimumnum/maximumnum intrinsics.
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:561
bool isNormalStore(const SDNode *N)
Returns true if the specified node is a non-truncating and unindexed store.
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, EVT Type)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
LLVM_ABI CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y).
LLVM_ABI bool isBuildVectorAllZeros(SDValue V)
Return true if the specified value is a BUILD_VECTOR where all of the elements are 0 or undef.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
bool isNormalLoad(const SDNode *N)
Returns true if the specified node is a non-extending and unindexed load.
Flag
These should be considered private to the implementation of the MCInstrDesc class.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
auto m_Cmp()
Matches any compare instruction and ignore it.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
LLVM_ABI Libcall getSINTTOFP(EVT OpVT, EVT RetVT)
getSINTTOFP - Return the SINTTOFP_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getUINTTOFP(EVT OpVT, EVT RetVT)
getUINTTOFP - Return the UINTTOFP_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
LLVM_ABI Libcall getFPTOSINT(EVT OpVT, EVT RetVT)
getFPTOSINT - Return the FPTOSINT_*_* value for the given types, or UNKNOWN_LIBCALL if there is none.
@ System
Synchronized with respect to all concurrently executing threads.
Definition LLVMContext.h:66
const unsigned GR64Regs[16]
const unsigned VR128Regs[32]
const unsigned VR16Regs[32]
const unsigned GR128Regs[16]
const unsigned FP32Regs[16]
const unsigned FP16Regs[16]
const unsigned GR32Regs[16]
const unsigned FP64Regs[16]
const int64_t ELFCallFrameSize
const unsigned VR64Regs[32]
const unsigned FP128Regs[16]
const unsigned VR32Regs[32]
unsigned odd128(bool Is32bit)
const unsigned CCMASK_CMP_GE
Definition SystemZ.h:46
static bool isImmHH(uint64_t Val)
Definition SystemZ.h:182
const unsigned CCMASK_TEND
Definition SystemZ.h:103
const unsigned CCMASK_CS_EQ
Definition SystemZ.h:73
const unsigned CCMASK_TBEGIN
Definition SystemZ.h:98
const unsigned CCMASK_0
Definition SystemZ.h:33
const MCPhysReg ELFArgFPRs[ELFNumArgFPRs]
MachineBasicBlock * splitBlockBefore(MachineBasicBlock::iterator MI, MachineBasicBlock *MBB)
const unsigned CCMASK_TM_SOME_1
Definition SystemZ.h:88
const unsigned CCMASK_LOGICAL_CARRY
Definition SystemZ.h:66
const unsigned TDCMASK_NORMAL_MINUS
Definition SystemZ.h:128
const unsigned CCMASK_TDC
Definition SystemZ.h:115
const unsigned CCMASK_FCMP
Definition SystemZ.h:54
const unsigned CCMASK_TM_SOME_0
Definition SystemZ.h:87
static bool isImmHL(uint64_t Val)
Definition SystemZ.h:177
const unsigned TDCMASK_SUBNORMAL_MINUS
Definition SystemZ.h:130
const unsigned PFD_READ
Definition SystemZ.h:121
const unsigned CCMASK_1
Definition SystemZ.h:34
const unsigned TDCMASK_NORMAL_PLUS
Definition SystemZ.h:127
const unsigned PFD_WRITE
Definition SystemZ.h:122
const unsigned CCMASK_CMP_GT
Definition SystemZ.h:43
const unsigned TDCMASK_QNAN_MINUS
Definition SystemZ.h:134
const unsigned CCMASK_CS
Definition SystemZ.h:75
const unsigned CCMASK_ANY
Definition SystemZ.h:37
const unsigned CCMASK_ARITH
Definition SystemZ.h:61
const unsigned CCMASK_TM_MIXED_MSB_0
Definition SystemZ.h:84
const unsigned TDCMASK_SUBNORMAL_PLUS
Definition SystemZ.h:129
static bool isImmLL(uint64_t Val)
Definition SystemZ.h:167
const unsigned VectorBits
Definition SystemZ.h:160
static bool isImmLH(uint64_t Val)
Definition SystemZ.h:172
MachineBasicBlock * emitBlockAfter(MachineBasicBlock *MBB)
const unsigned TDCMASK_INFINITY_PLUS
Definition SystemZ.h:131
unsigned reverseCCMask(unsigned CCMask)
const unsigned CCMASK_TM_ALL_0
Definition SystemZ.h:83
const unsigned IPM_CC
Definition SystemZ.h:118
const unsigned CCMASK_CMP_LE
Definition SystemZ.h:45
const unsigned CCMASK_CMP_O
Definition SystemZ.h:50
const unsigned CCMASK_CMP_EQ
Definition SystemZ.h:41
const unsigned VectorBytes
Definition SystemZ.h:164
const unsigned TDCMASK_INFINITY_MINUS
Definition SystemZ.h:132
const unsigned CCMASK_ICMP
Definition SystemZ.h:53
const unsigned CCMASK_VCMP_ALL
Definition SystemZ.h:107
const unsigned CCMASK_VCMP_NONE
Definition SystemZ.h:109
MachineBasicBlock * splitBlockAfter(MachineBasicBlock::iterator MI, MachineBasicBlock *MBB)
const unsigned CCMASK_VCMP
Definition SystemZ.h:110
const unsigned CCMASK_TM_MIXED_MSB_1
Definition SystemZ.h:85
const unsigned CCMASK_TM_MSB_0
Definition SystemZ.h:89
const unsigned CCMASK_ARITH_OVERFLOW
Definition SystemZ.h:60
const unsigned CCMASK_CS_NE
Definition SystemZ.h:74
const unsigned TDCMASK_SNAN_PLUS
Definition SystemZ.h:135
const unsigned CCMASK_TM
Definition SystemZ.h:91
const unsigned CCMASK_3
Definition SystemZ.h:36
const unsigned CCMASK_NONE
Definition SystemZ.h:32
const unsigned CCMASK_CMP_LT
Definition SystemZ.h:42
const unsigned CCMASK_CMP_NE
Definition SystemZ.h:44
const unsigned TDCMASK_ZERO_PLUS
Definition SystemZ.h:125
const unsigned TDCMASK_QNAN_PLUS
Definition SystemZ.h:133
const unsigned TDCMASK_ZERO_MINUS
Definition SystemZ.h:126
unsigned even128(bool Is32bit)
const unsigned CCMASK_TM_ALL_1
Definition SystemZ.h:86
const unsigned CCMASK_LOGICAL_BORROW
Definition SystemZ.h:68
const unsigned ELFNumArgFPRs
const unsigned CCMASK_CMP_UO
Definition SystemZ.h:49
const unsigned CCMASK_LOGICAL
Definition SystemZ.h:70
const unsigned CCMASK_TM_MSB_1
Definition SystemZ.h:90
const unsigned TDCMASK_SNAN_MINUS
Definition SystemZ.h:136
support::ulittle32_t Word
Definition IRSymtab.h:53
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
NodeAddr< CodeNode * > Code
Definition RDFGraph.h:388
This is an optimization pass for GlobalISel generic memory operations.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
@ Known
Known to have no common set bits.
@ Define
Register definition.
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Done
Definition Threading.h:60
@ Load
The value being inserted comes from a load (InsertElement only).
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition Error.h:198
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
constexpr T maskLeadingOnes(unsigned N)
Create a bitmask with the N left-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:89
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI void dumpBytes(ArrayRef< uint8_t > Bytes, raw_ostream &OS)
Convert ‘Bytes’ to a hex string and output to ‘OS’.
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition bit.h:362
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
LLVM_ABI bool isBitwiseNot(SDValue V, bool AllowUndefs=false)
Returns true if V is a bitwise not operation.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Success
The lock was released successfully.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
AtomicOrdering
Atomic ordering for LLVM's memory model.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ BeforeLegalizeTypes
Definition DAGCombine.h:16
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
@ Fast
Assign the register banks as fast as possible (default).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
constexpr std::optional< bool > toOptional(BoolOrDefault X)
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
constexpr unsigned BitWidth
ExceptionHandling
Definition CodeGen.h:54
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:572
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:78
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:347
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI bool isAllOnesConstant(SDValue V)
Returns true if V is an integer constant with all bits set.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
#define EQ(a, b)
Definition regexec.c:65
AddressingMode(bool LongDispl, bool IdxReg)
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Extended Value Type.
Definition ValueTypes.h:35
EVT changeVectorElementTypeToInteger() const
Return a vector with the same number of elements as this vector, but with the element type converted ...
Definition ValueTypes.h:90
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:433
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:160
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:170
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:423
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:354
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
Definition ValueTypes.h:419
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:191
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:361
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
bool isRound() const
Return true if the size is a power-of-two number of bytes.
Definition ValueTypes.h:286
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:366
bool isVectorOf(EVT EltVT) const
Return true if this is a vector with matching element type.
Definition ValueTypes.h:196
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:180
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:374
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:175
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition KnownBits.h:325
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getConstantPool(MachineFunction &MF)
Return a MachinePointerInfo record that refers to the constant pool.
MachinePointerInfo getWithOffset(int64_t O) const
static LLVM_ABI MachinePointerInfo getGOT(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a GOT entry.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
SmallVector< unsigned, 2 > OpVals
bool isVectorConstantLegal(const SystemZSubtarget &Subtarget)
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*...
This contains information for each constraint that we are lowering.
This structure contains all information that is necessary for lowering calls.
SmallVector< ISD::InputArg, 32 > Ins
CallLoweringInfo & setDiscardResult(bool Value=true)
CallLoweringInfo & setZExtResult(bool Value=true)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
CallLoweringInfo & setSExtResult(bool Value=true)
CallLoweringInfo & setNoReturn(bool Value=true)
SmallVector< ISD::OutputArg, 32 > Outs
CallLoweringInfo & setChain(SDValue InChain)
CallLoweringInfo & setCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList, AttributeSet ResultAttrs={})
This structure is used to pass arguments to makeLibCall function.