LLVM 19.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"
23#include "llvm/IR/Intrinsics.h"
24#include "llvm/IR/IntrinsicsS390.h"
27#include <cctype>
28#include <optional>
29
30using namespace llvm;
31
32#define DEBUG_TYPE "systemz-lower"
33
34namespace {
35// Represents information about a comparison.
36struct Comparison {
37 Comparison(SDValue Op0In, SDValue Op1In, SDValue ChainIn)
38 : Op0(Op0In), Op1(Op1In), Chain(ChainIn),
39 Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
40
41 // The operands to the comparison.
42 SDValue Op0, Op1;
43
44 // Chain if this is a strict floating-point comparison.
45 SDValue Chain;
46
47 // The opcode that should be used to compare Op0 and Op1.
48 unsigned Opcode;
49
50 // A SystemZICMP value. Only used for integer comparisons.
51 unsigned ICmpType;
52
53 // The mask of CC values that Opcode can produce.
54 unsigned CCValid;
55
56 // The mask of CC values for which the original condition is true.
57 unsigned CCMask;
58};
59} // end anonymous namespace
60
61// Classify VT as either 32 or 64 bit.
62static bool is32Bit(EVT VT) {
63 switch (VT.getSimpleVT().SimpleTy) {
64 case MVT::i32:
65 return true;
66 case MVT::i64:
67 return false;
68 default:
69 llvm_unreachable("Unsupported type");
70 }
71}
72
73// Return a version of MachineOperand that can be safely used before the
74// final use.
76 if (Op.isReg())
77 Op.setIsKill(false);
78 return Op;
79}
80
82 const SystemZSubtarget &STI)
83 : TargetLowering(TM), Subtarget(STI) {
84 MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0));
85
86 auto *Regs = STI.getSpecialRegisters();
87
88 // Set up the register classes.
89 if (Subtarget.hasHighWord())
90 addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
91 else
92 addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
93 addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass);
94 if (!useSoftFloat()) {
95 if (Subtarget.hasVector()) {
96 addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass);
97 addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass);
98 } else {
99 addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass);
100 addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass);
101 }
102 if (Subtarget.hasVectorEnhancements1())
103 addRegisterClass(MVT::f128, &SystemZ::VR128BitRegClass);
104 else
105 addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
106
107 if (Subtarget.hasVector()) {
108 addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass);
109 addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass);
110 addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass);
111 addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass);
112 addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass);
113 addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass);
114 }
115
116 if (Subtarget.hasVector())
117 addRegisterClass(MVT::i128, &SystemZ::VR128BitRegClass);
118 }
119
120 // Compute derived properties from the register classes
122
123 // Set up special registers.
124 setStackPointerRegisterToSaveRestore(Regs->getStackPointerRegister());
125
126 // TODO: It may be better to default to latency-oriented scheduling, however
127 // LLVM's current latency-oriented scheduler can't handle physreg definitions
128 // such as SystemZ has with CC, so set this to the register-pressure
129 // scheduler, because it can.
131
134
136
137 // Instructions are strings of 2-byte aligned 2-byte values.
139 // For performance reasons we prefer 16-byte alignment.
141
142 // Handle operations that are handled in a similar way for all types.
143 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
144 I <= MVT::LAST_FP_VALUETYPE;
145 ++I) {
147 if (isTypeLegal(VT)) {
148 // Lower SET_CC into an IPM-based sequence.
152
153 // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
155
156 // Lower SELECT_CC and BR_CC into separate comparisons and branches.
159 }
160 }
161
162 // Expand jump table branches as address arithmetic followed by an
163 // indirect jump.
165
166 // Expand BRCOND into a BR_CC (see above).
168
169 // Handle integer types except i128.
170 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
171 I <= MVT::LAST_INTEGER_VALUETYPE;
172 ++I) {
174 if (isTypeLegal(VT) && VT != MVT::i128) {
176
177 // Expand individual DIV and REMs into DIVREMs.
184
185 // Support addition/subtraction with overflow.
188
189 // Support addition/subtraction with carry.
192
193 // Support carry in as value rather than glue.
196
197 // Lower ATOMIC_LOAD and ATOMIC_STORE into normal volatile loads and
198 // stores, putting a serialization instruction after the stores.
201
202 // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
203 // available, or if the operand is constant.
205
206 // Use POPCNT on z196 and above.
207 if (Subtarget.hasPopulationCount())
209 else
211
212 // No special instructions for these.
215
216 // Use *MUL_LOHI where possible instead of MULH*.
221
222 // Only z196 and above have native support for conversions to unsigned.
223 // On z10, promoting to i64 doesn't generate an inexact condition for
224 // values that are outside the i32 range but in the i64 range, so use
225 // the default expansion.
226 if (!Subtarget.hasFPExtension())
228
229 // Mirror those settings for STRICT_FP_TO_[SU]INT. Note that these all
230 // default to Expand, so need to be modified to Legal where appropriate.
232 if (Subtarget.hasFPExtension())
234
235 // And similarly for STRICT_[SU]INT_TO_FP.
237 if (Subtarget.hasFPExtension())
239 }
240 }
241
242 // Handle i128 if legal.
243 if (isTypeLegal(MVT::i128)) {
244 // No special instructions for these.
260
261 // Support addition/subtraction with carry.
266
267 // Use VPOPCT and add up partial results.
269
270 // We have to use libcalls for these.
279 }
280
281 // Type legalization will convert 8- and 16-bit atomic operations into
282 // forms that operate on i32s (but still keeping the original memory VT).
283 // Lower them into full i32 operations.
295
296 // Whether or not i128 is not a legal type, we need to custom lower
297 // the atomic operations in order to exploit SystemZ instructions.
300
301 // We can use the CC result of compare-and-swap to implement
302 // the "success" result of ATOMIC_CMP_SWAP_WITH_SUCCESS.
306
308
309 // Traps are legal, as we will convert them to "j .+2".
310 setOperationAction(ISD::TRAP, MVT::Other, Legal);
311
312 // z10 has instructions for signed but not unsigned FP conversion.
313 // Handle unsigned 32-bit types as signed 64-bit types.
314 if (!Subtarget.hasFPExtension()) {
319 }
320
321 // We have native support for a 64-bit CTLZ, via FLOGR.
325
326 // On z15 we have native support for a 64-bit CTPOP.
327 if (Subtarget.hasMiscellaneousExtensions3()) {
330 }
331
332 // Give LowerOperation the chance to replace 64-bit ORs with subregs.
334
335 // Expand 128 bit shifts without using a libcall.
339 setLibcallName(RTLIB::SRL_I128, nullptr);
340 setLibcallName(RTLIB::SHL_I128, nullptr);
341 setLibcallName(RTLIB::SRA_I128, nullptr);
342
343 // Also expand 256 bit shifts if i128 is a legal type.
344 if (isTypeLegal(MVT::i128)) {
348 }
349
350 // Handle bitcast from fp128 to i128.
351 if (!isTypeLegal(MVT::i128))
353
354 // We have native instructions for i8, i16 and i32 extensions, but not i1.
356 for (MVT VT : MVT::integer_valuetypes()) {
360 }
361
362 // Handle the various types of symbolic address.
368
369 // We need to handle dynamic allocations specially because of the
370 // 160-byte area at the bottom of the stack.
373
376
377 // Handle prefetches with PFD or PFDRL.
379
381 // Assume by default that all vector operations need to be expanded.
382 for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
383 if (getOperationAction(Opcode, VT) == Legal)
384 setOperationAction(Opcode, VT, Expand);
385
386 // Likewise all truncating stores and extending loads.
387 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
388 setTruncStoreAction(VT, InnerVT, Expand);
391 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
392 }
393
394 if (isTypeLegal(VT)) {
395 // These operations are legal for anything that can be stored in a
396 // vector register, even if there is no native support for the format
397 // as such. In particular, we can do these for v4f32 even though there
398 // are no specific instructions for that format.
404
405 // Likewise, except that we need to replace the nodes with something
406 // more specific.
409 }
410 }
411
412 // Handle integer vector types.
414 if (isTypeLegal(VT)) {
415 // These operations have direct equivalents.
420 if (VT != MVT::v2i64)
426 if (Subtarget.hasVectorEnhancements1())
428 else
432
433 // Convert a GPR scalar to a vector by inserting it into element 0.
435
436 // Use a series of unpacks for extensions.
439
440 // Detect shifts/rotates by a scalar amount and convert them into
441 // V*_BY_SCALAR.
446
447 // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
448 // and inverting the result as necessary.
450 }
451 }
452
453 if (Subtarget.hasVector()) {
454 // There should be no need to check for float types other than v2f64
455 // since <2 x f32> isn't a legal type.
464
473 }
474
475 if (Subtarget.hasVectorEnhancements2()) {
484
493 }
494
495 // Handle floating-point types.
496 for (unsigned I = MVT::FIRST_FP_VALUETYPE;
497 I <= MVT::LAST_FP_VALUETYPE;
498 ++I) {
500 if (isTypeLegal(VT)) {
501 // We can use FI for FRINT.
503
504 // We can use the extended form of FI for other rounding operations.
505 if (Subtarget.hasFPExtension()) {
511 }
512
513 // No special instructions for these.
519
520 // Special treatment.
522
523 // Handle constrained floating-point operations.
533 if (Subtarget.hasFPExtension()) {
539 }
540 }
541 }
542
543 // Handle floating-point vector types.
544 if (Subtarget.hasVector()) {
545 // Scalar-to-vector conversion is just a subreg.
548
549 // Some insertions and extractions can be done directly but others
550 // need to go via integers.
555
556 // These operations have direct equivalents.
557 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
558 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
559 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
560 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
561 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
562 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
563 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
564 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
565 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
568 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
571
572 // Handle constrained floating-point operations.
585
590 if (Subtarget.hasVectorEnhancements1()) {
593 }
594 }
595
596 // The vector enhancements facility 1 has instructions for these.
597 if (Subtarget.hasVectorEnhancements1()) {
598 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
599 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
600 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
601 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
602 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
603 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
604 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
605 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
606 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
609 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
612
617
622
627
632
637
638 // Handle constrained floating-point operations.
651 for (auto VT : { MVT::f32, MVT::f64, MVT::f128,
652 MVT::v4f32, MVT::v2f64 }) {
657 }
658 }
659
660 // We only have fused f128 multiply-addition on vector registers.
661 if (!Subtarget.hasVectorEnhancements1()) {
664 }
665
666 // We don't have a copysign instruction on vector registers.
667 if (Subtarget.hasVectorEnhancements1())
669
670 // Needed so that we don't try to implement f128 constant loads using
671 // a load-and-extend of a f80 constant (in cases where the constant
672 // would fit in an f80).
673 for (MVT VT : MVT::fp_valuetypes())
674 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
675
676 // We don't have extending load instruction on vector registers.
677 if (Subtarget.hasVectorEnhancements1()) {
678 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
679 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
680 }
681
682 // Floating-point truncation and stores need to be done separately.
683 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
684 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
685 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
686
687 // We have 64-bit FPR<->GPR moves, but need special handling for
688 // 32-bit forms.
689 if (!Subtarget.hasVector()) {
692 }
693
694 // VASTART and VACOPY need to deal with the SystemZ-specific varargs
695 // structure, but VAEND is a no-op.
699
701
702 // Codes for which we want to perform some z-specific combinations.
706 ISD::LOAD,
717 ISD::SDIV,
718 ISD::UDIV,
719 ISD::SREM,
720 ISD::UREM,
723
724 // Handle intrinsics.
727
728 // We want to use MVC in preference to even a single load/store pair.
729 MaxStoresPerMemcpy = Subtarget.hasVector() ? 2 : 0;
731
732 // The main memset sequence is a byte store followed by an MVC.
733 // Two STC or MV..I stores win over that, but the kind of fused stores
734 // generated by target-independent code don't when the byte value is
735 // variable. E.g. "STC <reg>;MHI <reg>,257;STH <reg>" is not better
736 // than "STC;MVC". Handle the choice in target-specific code instead.
737 MaxStoresPerMemset = Subtarget.hasVector() ? 2 : 0;
739
740 // Default to having -disable-strictnode-mutation on
741 IsStrictFPEnabled = true;
742
743 if (Subtarget.isTargetzOS()) {
744 struct RTLibCallMapping {
745 RTLIB::Libcall Code;
746 const char *Name;
747 };
748 static RTLibCallMapping RTLibCallCommon[] = {
749#define HANDLE_LIBCALL(code, name) {RTLIB::code, name},
750#include "ZOSLibcallNames.def"
751 };
752 for (auto &E : RTLibCallCommon)
753 setLibcallName(E.Code, E.Name);
754 }
755}
756
758 return Subtarget.hasSoftFloat();
759}
760
762 LLVMContext &, EVT VT) const {
763 if (!VT.isVector())
764 return MVT::i32;
766}
767
769 const MachineFunction &MF, EVT VT) const {
770 VT = VT.getScalarType();
771
772 if (!VT.isSimple())
773 return false;
774
775 switch (VT.getSimpleVT().SimpleTy) {
776 case MVT::f32:
777 case MVT::f64:
778 return true;
779 case MVT::f128:
780 return Subtarget.hasVectorEnhancements1();
781 default:
782 break;
783 }
784
785 return false;
786}
787
788// Return true if the constant can be generated with a vector instruction,
789// such as VGM, VGMB or VREPI.
791 const SystemZSubtarget &Subtarget) {
792 const SystemZInstrInfo *TII = Subtarget.getInstrInfo();
793 if (!Subtarget.hasVector() ||
794 (isFP128 && !Subtarget.hasVectorEnhancements1()))
795 return false;
796
797 // Try using VECTOR GENERATE BYTE MASK. This is the architecturally-
798 // preferred way of creating all-zero and all-one vectors so give it
799 // priority over other methods below.
800 unsigned Mask = 0;
801 unsigned I = 0;
802 for (; I < SystemZ::VectorBytes; ++I) {
803 uint64_t Byte = IntBits.lshr(I * 8).trunc(8).getZExtValue();
804 if (Byte == 0xff)
805 Mask |= 1ULL << I;
806 else if (Byte != 0)
807 break;
808 }
809 if (I == SystemZ::VectorBytes) {
811 OpVals.push_back(Mask);
813 return true;
814 }
815
816 if (SplatBitSize > 64)
817 return false;
818
819 auto tryValue = [&](uint64_t Value) -> bool {
820 // Try VECTOR REPLICATE IMMEDIATE
821 int64_t SignedValue = SignExtend64(Value, SplatBitSize);
822 if (isInt<16>(SignedValue)) {
823 OpVals.push_back(((unsigned) SignedValue));
826 SystemZ::VectorBits / SplatBitSize);
827 return true;
828 }
829 // Try VECTOR GENERATE MASK
830 unsigned Start, End;
831 if (TII->isRxSBGMask(Value, SplatBitSize, Start, End)) {
832 // isRxSBGMask returns the bit numbers for a full 64-bit value, with 0
833 // denoting 1 << 63 and 63 denoting 1. Convert them to bit numbers for
834 // an SplatBitSize value, so that 0 denotes 1 << (SplatBitSize-1).
835 OpVals.push_back(Start - (64 - SplatBitSize));
836 OpVals.push_back(End - (64 - SplatBitSize));
839 SystemZ::VectorBits / SplatBitSize);
840 return true;
841 }
842 return false;
843 };
844
845 // First try assuming that any undefined bits above the highest set bit
846 // and below the lowest set bit are 1s. This increases the likelihood of
847 // being able to use a sign-extended element value in VECTOR REPLICATE
848 // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
849 uint64_t SplatBitsZ = SplatBits.getZExtValue();
850 uint64_t SplatUndefZ = SplatUndef.getZExtValue();
851 unsigned LowerBits = llvm::countr_zero(SplatBitsZ);
852 unsigned UpperBits = llvm::countl_zero(SplatBitsZ);
853 uint64_t Lower = SplatUndefZ & maskTrailingOnes<uint64_t>(LowerBits);
854 uint64_t Upper = SplatUndefZ & maskLeadingOnes<uint64_t>(UpperBits);
855 if (tryValue(SplatBitsZ | Upper | Lower))
856 return true;
857
858 // Now try assuming that any undefined bits between the first and
859 // last defined set bits are set. This increases the chances of
860 // using a non-wraparound mask.
861 uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
862 return tryValue(SplatBitsZ | Middle);
863}
864
866 if (IntImm.isSingleWord()) {
867 IntBits = APInt(128, IntImm.getZExtValue());
868 IntBits <<= (SystemZ::VectorBits - IntImm.getBitWidth());
869 } else
870 IntBits = IntImm;
871 assert(IntBits.getBitWidth() == 128 && "Unsupported APInt.");
872
873 // Find the smallest splat.
874 SplatBits = IntImm;
875 unsigned Width = SplatBits.getBitWidth();
876 while (Width > 8) {
877 unsigned HalfSize = Width / 2;
878 APInt HighValue = SplatBits.lshr(HalfSize).trunc(HalfSize);
879 APInt LowValue = SplatBits.trunc(HalfSize);
880
881 // If the two halves do not match, stop here.
882 if (HighValue != LowValue || 8 > HalfSize)
883 break;
884
885 SplatBits = HighValue;
886 Width = HalfSize;
887 }
888 SplatUndef = 0;
889 SplatBitSize = Width;
890}
891
893 assert(BVN->isConstant() && "Expected a constant BUILD_VECTOR");
894 bool HasAnyUndefs;
895
896 // Get IntBits by finding the 128 bit splat.
897 BVN->isConstantSplat(IntBits, SplatUndef, SplatBitSize, HasAnyUndefs, 128,
898 true);
899
900 // Get SplatBits by finding the 8 bit or greater splat.
901 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 8,
902 true);
903}
904
906 bool ForCodeSize) const {
907 // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
908 if (Imm.isZero() || Imm.isNegZero())
909 return true;
910
912}
913
914/// Returns true if stack probing through inline assembly is requested.
916 // If the function specifically requests inline stack probes, emit them.
917 if (MF.getFunction().hasFnAttribute("probe-stack"))
918 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
919 "inline-asm";
920 return false;
921}
922
925 // Don't expand subword operations as they require special treatment.
926 if (RMW->getType()->isIntegerTy(8) || RMW->getType()->isIntegerTy(16))
928
929 // Don't expand if there is a target instruction available.
930 if (Subtarget.hasInterlockedAccess1() &&
931 (RMW->getType()->isIntegerTy(32) || RMW->getType()->isIntegerTy(64)) &&
938
940}
941
943 // We can use CGFI or CLGFI.
944 return isInt<32>(Imm) || isUInt<32>(Imm);
945}
946
948 // We can use ALGFI or SLGFI.
949 return isUInt<32>(Imm) || isUInt<32>(-Imm);
950}
951
953 EVT VT, unsigned, Align, MachineMemOperand::Flags, unsigned *Fast) const {
954 // Unaligned accesses should never be slower than the expanded version.
955 // We check specifically for aligned accesses in the few cases where
956 // they are required.
957 if (Fast)
958 *Fast = 1;
959 return true;
960}
961
962// Information about the addressing mode for a memory access.
964 // True if a long displacement is supported.
966
967 // True if use of index register is supported.
969
970 AddressingMode(bool LongDispl, bool IdxReg) :
971 LongDisplacement(LongDispl), IndexReg(IdxReg) {}
972};
973
974// Return the desired addressing mode for a Load which has only one use (in
975// the same block) which is a Store.
977 Type *Ty) {
978 // With vector support a Load->Store combination may be combined to either
979 // an MVC or vector operations and it seems to work best to allow the
980 // vector addressing mode.
981 if (HasVector)
982 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
983
984 // Otherwise only the MVC case is special.
985 bool MVC = Ty->isIntegerTy(8);
986 return AddressingMode(!MVC/*LongDispl*/, !MVC/*IdxReg*/);
987}
988
989// Return the addressing mode which seems most desirable given an LLVM
990// Instruction pointer.
991static AddressingMode
993 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
994 switch (II->getIntrinsicID()) {
995 default: break;
996 case Intrinsic::memset:
997 case Intrinsic::memmove:
998 case Intrinsic::memcpy:
999 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
1000 }
1001 }
1002
1003 if (isa<LoadInst>(I) && I->hasOneUse()) {
1004 auto *SingleUser = cast<Instruction>(*I->user_begin());
1005 if (SingleUser->getParent() == I->getParent()) {
1006 if (isa<ICmpInst>(SingleUser)) {
1007 if (auto *C = dyn_cast<ConstantInt>(SingleUser->getOperand(1)))
1008 if (C->getBitWidth() <= 64 &&
1009 (isInt<16>(C->getSExtValue()) || isUInt<16>(C->getZExtValue())))
1010 // Comparison of memory with 16 bit signed / unsigned immediate
1011 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
1012 } else if (isa<StoreInst>(SingleUser))
1013 // Load->Store
1014 return getLoadStoreAddrMode(HasVector, I->getType());
1015 }
1016 } else if (auto *StoreI = dyn_cast<StoreInst>(I)) {
1017 if (auto *LoadI = dyn_cast<LoadInst>(StoreI->getValueOperand()))
1018 if (LoadI->hasOneUse() && LoadI->getParent() == I->getParent())
1019 // Load->Store
1020 return getLoadStoreAddrMode(HasVector, LoadI->getType());
1021 }
1022
1023 if (HasVector && (isa<LoadInst>(I) || isa<StoreInst>(I))) {
1024
1025 // * Use LDE instead of LE/LEY for z13 to avoid partial register
1026 // dependencies (LDE only supports small offsets).
1027 // * Utilize the vector registers to hold floating point
1028 // values (vector load / store instructions only support small
1029 // offsets).
1030
1031 Type *MemAccessTy = (isa<LoadInst>(I) ? I->getType() :
1032 I->getOperand(0)->getType());
1033 bool IsFPAccess = MemAccessTy->isFloatingPointTy();
1034 bool IsVectorAccess = MemAccessTy->isVectorTy();
1035
1036 // A store of an extracted vector element will be combined into a VSTE type
1037 // instruction.
1038 if (!IsVectorAccess && isa<StoreInst>(I)) {
1039 Value *DataOp = I->getOperand(0);
1040 if (isa<ExtractElementInst>(DataOp))
1041 IsVectorAccess = true;
1042 }
1043
1044 // A load which gets inserted into a vector element will be combined into a
1045 // VLE type instruction.
1046 if (!IsVectorAccess && isa<LoadInst>(I) && I->hasOneUse()) {
1047 User *LoadUser = *I->user_begin();
1048 if (isa<InsertElementInst>(LoadUser))
1049 IsVectorAccess = true;
1050 }
1051
1052 if (IsFPAccess || IsVectorAccess)
1053 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
1054 }
1055
1056 return AddressingMode(true/*LongDispl*/, true/*IdxReg*/);
1057}
1058
1060 const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I) const {
1061 // Punt on globals for now, although they can be used in limited
1062 // RELATIVE LONG cases.
1063 if (AM.BaseGV)
1064 return false;
1065
1066 // Require a 20-bit signed offset.
1067 if (!isInt<20>(AM.BaseOffs))
1068 return false;
1069
1070 bool RequireD12 =
1071 Subtarget.hasVector() && (Ty->isVectorTy() || Ty->isIntegerTy(128));
1072 AddressingMode SupportedAM(!RequireD12, true);
1073 if (I != nullptr)
1074 SupportedAM = supportedAddressingMode(I, Subtarget.hasVector());
1075
1076 if (!SupportedAM.LongDisplacement && !isUInt<12>(AM.BaseOffs))
1077 return false;
1078
1079 if (!SupportedAM.IndexReg)
1080 // No indexing allowed.
1081 return AM.Scale == 0;
1082 else
1083 // Indexing is OK but no scale factor can be applied.
1084 return AM.Scale == 0 || AM.Scale == 1;
1085}
1086
1088 std::vector<EVT> &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS,
1089 unsigned SrcAS, const AttributeList &FuncAttributes) const {
1090 const int MVCFastLen = 16;
1091
1092 if (Limit != ~unsigned(0)) {
1093 // Don't expand Op into scalar loads/stores in these cases:
1094 if (Op.isMemcpy() && Op.allowOverlap() && Op.size() <= MVCFastLen)
1095 return false; // Small memcpy: Use MVC
1096 if (Op.isMemset() && Op.size() - 1 <= MVCFastLen)
1097 return false; // Small memset (first byte with STC/MVI): Use MVC
1098 if (Op.isZeroMemset())
1099 return false; // Memset zero: Use XC
1100 }
1101
1102 return TargetLowering::findOptimalMemOpLowering(MemOps, Limit, Op, DstAS,
1103 SrcAS, FuncAttributes);
1104}
1105
1107 const AttributeList &FuncAttributes) const {
1108 return Subtarget.hasVector() ? MVT::v2i64 : MVT::Other;
1109}
1110
1111bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
1112 if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
1113 return false;
1114 unsigned FromBits = FromType->getPrimitiveSizeInBits().getFixedValue();
1115 unsigned ToBits = ToType->getPrimitiveSizeInBits().getFixedValue();
1116 return FromBits > ToBits;
1117}
1118
1120 if (!FromVT.isInteger() || !ToVT.isInteger())
1121 return false;
1122 unsigned FromBits = FromVT.getFixedSizeInBits();
1123 unsigned ToBits = ToVT.getFixedSizeInBits();
1124 return FromBits > ToBits;
1125}
1126
1127//===----------------------------------------------------------------------===//
1128// Inline asm support
1129//===----------------------------------------------------------------------===//
1130
1133 if (Constraint.size() == 1) {
1134 switch (Constraint[0]) {
1135 case 'a': // Address register
1136 case 'd': // Data register (equivalent to 'r')
1137 case 'f': // Floating-point register
1138 case 'h': // High-part register
1139 case 'r': // General-purpose register
1140 case 'v': // Vector register
1141 return C_RegisterClass;
1142
1143 case 'Q': // Memory with base and unsigned 12-bit displacement
1144 case 'R': // Likewise, plus an index
1145 case 'S': // Memory with base and signed 20-bit displacement
1146 case 'T': // Likewise, plus an index
1147 case 'm': // Equivalent to 'T'.
1148 return C_Memory;
1149
1150 case 'I': // Unsigned 8-bit constant
1151 case 'J': // Unsigned 12-bit constant
1152 case 'K': // Signed 16-bit constant
1153 case 'L': // Signed 20-bit displacement (on all targets we support)
1154 case 'M': // 0x7fffffff
1155 return C_Immediate;
1156
1157 default:
1158 break;
1159 }
1160 } else if (Constraint.size() == 2 && Constraint[0] == 'Z') {
1161 switch (Constraint[1]) {
1162 case 'Q': // Address with base and unsigned 12-bit displacement
1163 case 'R': // Likewise, plus an index
1164 case 'S': // Address with base and signed 20-bit displacement
1165 case 'T': // Likewise, plus an index
1166 return C_Address;
1167
1168 default:
1169 break;
1170 }
1171 }
1172 return TargetLowering::getConstraintType(Constraint);
1173}
1174
1177 const char *constraint) const {
1179 Value *CallOperandVal = info.CallOperandVal;
1180 // If we don't have a value, we can't do a match,
1181 // but allow it at the lowest weight.
1182 if (!CallOperandVal)
1183 return CW_Default;
1184 Type *type = CallOperandVal->getType();
1185 // Look at the constraint type.
1186 switch (*constraint) {
1187 default:
1189 break;
1190
1191 case 'a': // Address register
1192 case 'd': // Data register (equivalent to 'r')
1193 case 'h': // High-part register
1194 case 'r': // General-purpose register
1195 weight = CallOperandVal->getType()->isIntegerTy() ? CW_Register : CW_Default;
1196 break;
1197
1198 case 'f': // Floating-point register
1199 if (!useSoftFloat())
1200 weight = type->isFloatingPointTy() ? CW_Register : CW_Default;
1201 break;
1202
1203 case 'v': // Vector register
1204 if (Subtarget.hasVector())
1205 weight = (type->isVectorTy() || type->isFloatingPointTy()) ? CW_Register
1206 : CW_Default;
1207 break;
1208
1209 case 'I': // Unsigned 8-bit constant
1210 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1211 if (isUInt<8>(C->getZExtValue()))
1212 weight = CW_Constant;
1213 break;
1214
1215 case 'J': // Unsigned 12-bit constant
1216 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1217 if (isUInt<12>(C->getZExtValue()))
1218 weight = CW_Constant;
1219 break;
1220
1221 case 'K': // Signed 16-bit constant
1222 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1223 if (isInt<16>(C->getSExtValue()))
1224 weight = CW_Constant;
1225 break;
1226
1227 case 'L': // Signed 20-bit displacement (on all targets we support)
1228 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1229 if (isInt<20>(C->getSExtValue()))
1230 weight = CW_Constant;
1231 break;
1232
1233 case 'M': // 0x7fffffff
1234 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1235 if (C->getZExtValue() == 0x7fffffff)
1236 weight = CW_Constant;
1237 break;
1238 }
1239 return weight;
1240}
1241
1242// Parse a "{tNNN}" register constraint for which the register type "t"
1243// has already been verified. MC is the class associated with "t" and
1244// Map maps 0-based register numbers to LLVM register numbers.
1245static std::pair<unsigned, const TargetRegisterClass *>
1247 const unsigned *Map, unsigned Size) {
1248 assert(*(Constraint.end()-1) == '}' && "Missing '}'");
1249 if (isdigit(Constraint[2])) {
1250 unsigned Index;
1251 bool Failed =
1252 Constraint.slice(2, Constraint.size() - 1).getAsInteger(10, Index);
1253 if (!Failed && Index < Size && Map[Index])
1254 return std::make_pair(Map[Index], RC);
1255 }
1256 return std::make_pair(0U, nullptr);
1257}
1258
1259std::pair<unsigned, const TargetRegisterClass *>
1261 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
1262 if (Constraint.size() == 1) {
1263 // GCC Constraint Letters
1264 switch (Constraint[0]) {
1265 default: break;
1266 case 'd': // Data register (equivalent to 'r')
1267 case 'r': // General-purpose register
1268 if (VT.getSizeInBits() == 64)
1269 return std::make_pair(0U, &SystemZ::GR64BitRegClass);
1270 else if (VT.getSizeInBits() == 128)
1271 return std::make_pair(0U, &SystemZ::GR128BitRegClass);
1272 return std::make_pair(0U, &SystemZ::GR32BitRegClass);
1273
1274 case 'a': // Address register
1275 if (VT == MVT::i64)
1276 return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
1277 else if (VT == MVT::i128)
1278 return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
1279 return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
1280
1281 case 'h': // High-part register (an LLVM extension)
1282 return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
1283
1284 case 'f': // Floating-point register
1285 if (!useSoftFloat()) {
1286 if (VT.getSizeInBits() == 64)
1287 return std::make_pair(0U, &SystemZ::FP64BitRegClass);
1288 else if (VT.getSizeInBits() == 128)
1289 return std::make_pair(0U, &SystemZ::FP128BitRegClass);
1290 return std::make_pair(0U, &SystemZ::FP32BitRegClass);
1291 }
1292 break;
1293
1294 case 'v': // Vector register
1295 if (Subtarget.hasVector()) {
1296 if (VT.getSizeInBits() == 32)
1297 return std::make_pair(0U, &SystemZ::VR32BitRegClass);
1298 if (VT.getSizeInBits() == 64)
1299 return std::make_pair(0U, &SystemZ::VR64BitRegClass);
1300 return std::make_pair(0U, &SystemZ::VR128BitRegClass);
1301 }
1302 break;
1303 }
1304 }
1305 if (Constraint.starts_with("{")) {
1306
1307 // A clobber constraint (e.g. ~{f0}) will have MVT::Other which is illegal
1308 // to check the size on.
1309 auto getVTSizeInBits = [&VT]() {
1310 return VT == MVT::Other ? 0 : VT.getSizeInBits();
1311 };
1312
1313 // We need to override the default register parsing for GPRs and FPRs
1314 // because the interpretation depends on VT. The internal names of
1315 // the registers are also different from the external names
1316 // (F0D and F0S instead of F0, etc.).
1317 if (Constraint[1] == 'r') {
1318 if (getVTSizeInBits() == 32)
1319 return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
1321 if (getVTSizeInBits() == 128)
1322 return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
1324 return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
1326 }
1327 if (Constraint[1] == 'f') {
1328 if (useSoftFloat())
1329 return std::make_pair(
1330 0u, static_cast<const TargetRegisterClass *>(nullptr));
1331 if (getVTSizeInBits() == 32)
1332 return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
1334 if (getVTSizeInBits() == 128)
1335 return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
1337 return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
1339 }
1340 if (Constraint[1] == 'v') {
1341 if (!Subtarget.hasVector())
1342 return std::make_pair(
1343 0u, static_cast<const TargetRegisterClass *>(nullptr));
1344 if (getVTSizeInBits() == 32)
1345 return parseRegisterNumber(Constraint, &SystemZ::VR32BitRegClass,
1347 if (getVTSizeInBits() == 64)
1348 return parseRegisterNumber(Constraint, &SystemZ::VR64BitRegClass,
1350 return parseRegisterNumber(Constraint, &SystemZ::VR128BitRegClass,
1352 }
1353 }
1354 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1355}
1356
1357// FIXME? Maybe this could be a TableGen attribute on some registers and
1358// this table could be generated automatically from RegInfo.
1361 const MachineFunction &MF) const {
1362 Register Reg =
1364 .Case("r4", Subtarget.isTargetXPLINK64() ? SystemZ::R4D : 0)
1365 .Case("r15", Subtarget.isTargetELF() ? SystemZ::R15D : 0)
1366 .Default(0);
1367
1368 if (Reg)
1369 return Reg;
1370 report_fatal_error("Invalid register name global variable");
1371}
1372
1374 const Constant *PersonalityFn) const {
1375 return Subtarget.isTargetXPLINK64() ? SystemZ::R1D : SystemZ::R6D;
1376}
1377
1379 const Constant *PersonalityFn) const {
1380 return Subtarget.isTargetXPLINK64() ? SystemZ::R2D : SystemZ::R7D;
1381}
1382
1384 SDValue Op, StringRef Constraint, std::vector<SDValue> &Ops,
1385 SelectionDAG &DAG) const {
1386 // Only support length 1 constraints for now.
1387 if (Constraint.size() == 1) {
1388 switch (Constraint[0]) {
1389 case 'I': // Unsigned 8-bit constant
1390 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1391 if (isUInt<8>(C->getZExtValue()))
1392 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1393 Op.getValueType()));
1394 return;
1395
1396 case 'J': // Unsigned 12-bit constant
1397 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1398 if (isUInt<12>(C->getZExtValue()))
1399 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1400 Op.getValueType()));
1401 return;
1402
1403 case 'K': // Signed 16-bit constant
1404 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1405 if (isInt<16>(C->getSExtValue()))
1406 Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
1407 Op.getValueType()));
1408 return;
1409
1410 case 'L': // Signed 20-bit displacement (on all targets we support)
1411 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1412 if (isInt<20>(C->getSExtValue()))
1413 Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
1414 Op.getValueType()));
1415 return;
1416
1417 case 'M': // 0x7fffffff
1418 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1419 if (C->getZExtValue() == 0x7fffffff)
1420 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1421 Op.getValueType()));
1422 return;
1423 }
1424 }
1425 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
1426}
1427
1428//===----------------------------------------------------------------------===//
1429// Calling conventions
1430//===----------------------------------------------------------------------===//
1431
1432#include "SystemZGenCallingConv.inc"
1433
1435 CallingConv::ID) const {
1436 static const MCPhysReg ScratchRegs[] = { SystemZ::R0D, SystemZ::R1D,
1437 SystemZ::R14D, 0 };
1438 return ScratchRegs;
1439}
1440
1442 Type *ToType) const {
1443 return isTruncateFree(FromType, ToType);
1444}
1445
1447 return CI->isTailCall();
1448}
1449
1450// Value is a value that has been passed to us in the location described by VA
1451// (and so has type VA.getLocVT()). Convert Value to VA.getValVT(), chaining
1452// any loads onto Chain.
1454 CCValAssign &VA, SDValue Chain,
1455 SDValue Value) {
1456 // If the argument has been promoted from a smaller type, insert an
1457 // assertion to capture this.
1458 if (VA.getLocInfo() == CCValAssign::SExt)
1460 DAG.getValueType(VA.getValVT()));
1461 else if (VA.getLocInfo() == CCValAssign::ZExt)
1463 DAG.getValueType(VA.getValVT()));
1464
1465 if (VA.isExtInLoc())
1466 Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
1467 else if (VA.getLocInfo() == CCValAssign::BCvt) {
1468 // If this is a short vector argument loaded from the stack,
1469 // extend from i64 to full vector size and then bitcast.
1470 assert(VA.getLocVT() == MVT::i64);
1471 assert(VA.getValVT().isVector());
1472 Value = DAG.getBuildVector(MVT::v2i64, DL, {Value, DAG.getUNDEF(MVT::i64)});
1473 Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
1474 } else
1475 assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
1476 return Value;
1477}
1478
1479// Value is a value of type VA.getValVT() that we need to copy into
1480// the location described by VA. Return a copy of Value converted to
1481// VA.getValVT(). The caller is responsible for handling indirect values.
1483 CCValAssign &VA, SDValue Value) {
1484 switch (VA.getLocInfo()) {
1485 case CCValAssign::SExt:
1486 return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
1487 case CCValAssign::ZExt:
1488 return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
1489 case CCValAssign::AExt:
1490 return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
1491 case CCValAssign::BCvt: {
1492 assert(VA.getLocVT() == MVT::i64 || VA.getLocVT() == MVT::i128);
1493 assert(VA.getValVT().isVector() || VA.getValVT() == MVT::f32 ||
1494 VA.getValVT() == MVT::f64 || VA.getValVT() == MVT::f128);
1495 // For an f32 vararg we need to first promote it to an f64 and then
1496 // bitcast it to an i64.
1497 if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i64)
1498 Value = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f64, Value);
1499 MVT BitCastToType = VA.getValVT().isVector() && VA.getLocVT() == MVT::i64
1500 ? MVT::v2i64
1501 : VA.getLocVT();
1502 Value = DAG.getNode(ISD::BITCAST, DL, BitCastToType, Value);
1503 // For ELF, this is a short vector argument to be stored to the stack,
1504 // bitcast to v2i64 and then extract first element.
1505 if (BitCastToType == MVT::v2i64)
1506 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
1507 DAG.getConstant(0, DL, MVT::i32));
1508 return Value;
1509 }
1510 case CCValAssign::Full:
1511 return Value;
1512 default:
1513 llvm_unreachable("Unhandled getLocInfo()");
1514 }
1515}
1516
1518 SDLoc DL(In);
1519 SDValue Lo, Hi;
1520 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128)) {
1521 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, In);
1522 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
1523 DAG.getNode(ISD::SRL, DL, MVT::i128, In,
1524 DAG.getConstant(64, DL, MVT::i32)));
1525 } else {
1526 std::tie(Lo, Hi) = DAG.SplitScalar(In, DL, MVT::i64, MVT::i64);
1527 }
1528
1529 SDNode *Pair = DAG.getMachineNode(SystemZ::PAIR128, DL,
1530 MVT::Untyped, Hi, Lo);
1531 return SDValue(Pair, 0);
1532}
1533
1535 SDLoc DL(In);
1536 SDValue Hi = DAG.getTargetExtractSubreg(SystemZ::subreg_h64,
1537 DL, MVT::i64, In);
1538 SDValue Lo = DAG.getTargetExtractSubreg(SystemZ::subreg_l64,
1539 DL, MVT::i64, In);
1540
1541 if (DAG.getTargetLoweringInfo().isTypeLegal(MVT::i128)) {
1542 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, Lo);
1543 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, Hi);
1544 Hi = DAG.getNode(ISD::SHL, DL, MVT::i128, Hi,
1545 DAG.getConstant(64, DL, MVT::i32));
1546 return DAG.getNode(ISD::OR, DL, MVT::i128, Lo, Hi);
1547 } else {
1548 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128, Lo, Hi);
1549 }
1550}
1551
1553 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
1554 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
1555 EVT ValueVT = Val.getValueType();
1556 if (ValueVT.getSizeInBits() == 128 && NumParts == 1 && PartVT == MVT::Untyped) {
1557 // Inline assembly operand.
1558 Parts[0] = lowerI128ToGR128(DAG, DAG.getBitcast(MVT::i128, Val));
1559 return true;
1560 }
1561
1562 return false;
1563}
1564
1566 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
1567 MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const {
1568 if (ValueVT.getSizeInBits() == 128 && NumParts == 1 && PartVT == MVT::Untyped) {
1569 // Inline assembly operand.
1570 SDValue Res = lowerGR128ToI128(DAG, Parts[0]);
1571 return DAG.getBitcast(ValueVT, Res);
1572 }
1573
1574 return SDValue();
1575}
1576
1578 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
1579 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1580 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1582 MachineFrameInfo &MFI = MF.getFrameInfo();
1584 SystemZMachineFunctionInfo *FuncInfo =
1586 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>();
1587 EVT PtrVT = getPointerTy(DAG.getDataLayout());
1588
1589 // Assign locations to all of the incoming arguments.
1591 SystemZCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1592 CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
1593 FuncInfo->setSizeOfFnParams(CCInfo.getStackSize());
1594
1595 unsigned NumFixedGPRs = 0;
1596 unsigned NumFixedFPRs = 0;
1597 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1598 SDValue ArgValue;
1599 CCValAssign &VA = ArgLocs[I];
1600 EVT LocVT = VA.getLocVT();
1601 if (VA.isRegLoc()) {
1602 // Arguments passed in registers
1603 const TargetRegisterClass *RC;
1604 switch (LocVT.getSimpleVT().SimpleTy) {
1605 default:
1606 // Integers smaller than i64 should be promoted to i64.
1607 llvm_unreachable("Unexpected argument type");
1608 case MVT::i32:
1609 NumFixedGPRs += 1;
1610 RC = &SystemZ::GR32BitRegClass;
1611 break;
1612 case MVT::i64:
1613 NumFixedGPRs += 1;
1614 RC = &SystemZ::GR64BitRegClass;
1615 break;
1616 case MVT::f32:
1617 NumFixedFPRs += 1;
1618 RC = &SystemZ::FP32BitRegClass;
1619 break;
1620 case MVT::f64:
1621 NumFixedFPRs += 1;
1622 RC = &SystemZ::FP64BitRegClass;
1623 break;
1624 case MVT::f128:
1625 NumFixedFPRs += 2;
1626 RC = &SystemZ::FP128BitRegClass;
1627 break;
1628 case MVT::v16i8:
1629 case MVT::v8i16:
1630 case MVT::v4i32:
1631 case MVT::v2i64:
1632 case MVT::v4f32:
1633 case MVT::v2f64:
1634 RC = &SystemZ::VR128BitRegClass;
1635 break;
1636 }
1637
1638 Register VReg = MRI.createVirtualRegister(RC);
1639 MRI.addLiveIn(VA.getLocReg(), VReg);
1640 ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
1641 } else {
1642 assert(VA.isMemLoc() && "Argument not register or memory");
1643
1644 // Create the frame index object for this incoming parameter.
1645 // FIXME: Pre-include call frame size in the offset, should not
1646 // need to manually add it here.
1647 int64_t ArgSPOffset = VA.getLocMemOffset();
1648 if (Subtarget.isTargetXPLINK64()) {
1649 auto &XPRegs =
1651 ArgSPOffset += XPRegs.getCallFrameSize();
1652 }
1653 int FI =
1654 MFI.CreateFixedObject(LocVT.getSizeInBits() / 8, ArgSPOffset, true);
1655
1656 // Create the SelectionDAG nodes corresponding to a load
1657 // from this parameter. Unpromoted ints and floats are
1658 // passed as right-justified 8-byte values.
1659 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1660 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1661 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
1662 DAG.getIntPtrConstant(4, DL));
1663 ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
1665 }
1666
1667 // Convert the value of the argument register into the value that's
1668 // being passed.
1669 if (VA.getLocInfo() == CCValAssign::Indirect) {
1670 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
1672 // If the original argument was split (e.g. i128), we need
1673 // to load all parts of it here (using the same address).
1674 unsigned ArgIndex = Ins[I].OrigArgIndex;
1675 assert (Ins[I].PartOffset == 0);
1676 while (I + 1 != E && Ins[I + 1].OrigArgIndex == ArgIndex) {
1677 CCValAssign &PartVA = ArgLocs[I + 1];
1678 unsigned PartOffset = Ins[I + 1].PartOffset;
1679 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
1680 DAG.getIntPtrConstant(PartOffset, DL));
1681 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
1683 ++I;
1684 }
1685 } else
1686 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
1687 }
1688
1689 if (IsVarArg && Subtarget.isTargetXPLINK64()) {
1690 // Save the number of non-varargs registers for later use by va_start, etc.
1691 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
1692 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
1693
1694 auto *Regs = static_cast<SystemZXPLINK64Registers *>(
1695 Subtarget.getSpecialRegisters());
1696
1697 // Likewise the address (in the form of a frame index) of where the
1698 // first stack vararg would be. The 1-byte size here is arbitrary.
1699 // FIXME: Pre-include call frame size in the offset, should not
1700 // need to manually add it here.
1701 int64_t VarArgOffset = CCInfo.getStackSize() + Regs->getCallFrameSize();
1702 int FI = MFI.CreateFixedObject(1, VarArgOffset, true);
1703 FuncInfo->setVarArgsFrameIndex(FI);
1704 }
1705
1706 if (IsVarArg && Subtarget.isTargetELF()) {
1707 // Save the number of non-varargs registers for later use by va_start, etc.
1708 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
1709 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
1710
1711 // Likewise the address (in the form of a frame index) of where the
1712 // first stack vararg would be. The 1-byte size here is arbitrary.
1713 int64_t VarArgsOffset = CCInfo.getStackSize();
1714 FuncInfo->setVarArgsFrameIndex(
1715 MFI.CreateFixedObject(1, VarArgsOffset, true));
1716
1717 // ...and a similar frame index for the caller-allocated save area
1718 // that will be used to store the incoming registers.
1719 int64_t RegSaveOffset =
1720 -SystemZMC::ELFCallFrameSize + TFL->getRegSpillOffset(MF, SystemZ::R2D) - 16;
1721 unsigned RegSaveIndex = MFI.CreateFixedObject(1, RegSaveOffset, true);
1722 FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
1723
1724 // Store the FPR varargs in the reserved frame slots. (We store the
1725 // GPRs as part of the prologue.)
1726 if (NumFixedFPRs < SystemZ::ELFNumArgFPRs && !useSoftFloat()) {
1728 for (unsigned I = NumFixedFPRs; I < SystemZ::ELFNumArgFPRs; ++I) {
1729 unsigned Offset = TFL->getRegSpillOffset(MF, SystemZ::ELFArgFPRs[I]);
1730 int FI =
1732 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1734 &SystemZ::FP64BitRegClass);
1735 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
1736 MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
1738 }
1739 // Join the stores, which are independent of one another.
1740 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
1741 ArrayRef(&MemOps[NumFixedFPRs],
1742 SystemZ::ELFNumArgFPRs - NumFixedFPRs));
1743 }
1744 }
1745
1746 if (Subtarget.isTargetXPLINK64()) {
1747 // Create virual register for handling incoming "ADA" special register (R5)
1748 const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
1749 Register ADAvReg = MRI.createVirtualRegister(RC);
1750 auto *Regs = static_cast<SystemZXPLINK64Registers *>(
1751 Subtarget.getSpecialRegisters());
1752 MRI.addLiveIn(Regs->getADARegister(), ADAvReg);
1753 FuncInfo->setADAVirtualRegister(ADAvReg);
1754 }
1755 return Chain;
1756}
1757
1758static bool canUseSiblingCall(const CCState &ArgCCInfo,
1761 // Punt if there are any indirect or stack arguments, or if the call
1762 // needs the callee-saved argument register R6, or if the call uses
1763 // the callee-saved register arguments SwiftSelf and SwiftError.
1764 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1765 CCValAssign &VA = ArgLocs[I];
1767 return false;
1768 if (!VA.isRegLoc())
1769 return false;
1770 Register Reg = VA.getLocReg();
1771 if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
1772 return false;
1773 if (Outs[I].Flags.isSwiftSelf() || Outs[I].Flags.isSwiftError())
1774 return false;
1775 }
1776 return true;
1777}
1778
1780 unsigned Offset, bool LoadAdr = false) {
1783 unsigned ADAvReg = MFI->getADAVirtualRegister();
1785
1786 SDValue Reg = DAG.getRegister(ADAvReg, PtrVT);
1787 SDValue Ofs = DAG.getTargetConstant(Offset, DL, PtrVT);
1788
1789 SDValue Result = DAG.getNode(SystemZISD::ADA_ENTRY, DL, PtrVT, Val, Reg, Ofs);
1790 if (!LoadAdr)
1791 Result = DAG.getLoad(
1792 PtrVT, DL, DAG.getEntryNode(), Result, MachinePointerInfo(), Align(8),
1794
1795 return Result;
1796}
1797
1798// ADA access using Global value
1799// Note: for functions, address of descriptor is returned
1801 EVT PtrVT) {
1802 unsigned ADAtype;
1803 bool LoadAddr = false;
1804 const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV);
1805 bool IsFunction =
1806 (isa<Function>(GV)) || (GA && isa<Function>(GA->getAliaseeObject()));
1807 bool IsInternal = (GV->hasInternalLinkage() || GV->hasPrivateLinkage());
1808
1809 if (IsFunction) {
1810 if (IsInternal) {
1812 LoadAddr = true;
1813 } else
1815 } else {
1817 }
1818 SDValue Val = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ADAtype);
1819
1820 return getADAEntry(DAG, Val, DL, 0, LoadAddr);
1821}
1822
1823static bool getzOSCalleeAndADA(SelectionDAG &DAG, SDValue &Callee, SDValue &ADA,
1824 SDLoc &DL, SDValue &Chain) {
1825 unsigned ADADelta = 0; // ADA offset in desc.
1826 unsigned EPADelta = 8; // EPA offset in desc.
1829
1830 // XPLink calling convention.
1831 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1832 bool IsInternal = (G->getGlobal()->hasInternalLinkage() ||
1833 G->getGlobal()->hasPrivateLinkage());
1834 if (IsInternal) {
1837 unsigned ADAvReg = MFI->getADAVirtualRegister();
1838 ADA = DAG.getCopyFromReg(Chain, DL, ADAvReg, PtrVT);
1839 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
1840 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1841 return true;
1842 } else {
1844 G->getGlobal(), DL, PtrVT, 0, SystemZII::MO_ADA_DIRECT_FUNC_DESC);
1845 ADA = getADAEntry(DAG, GA, DL, ADADelta);
1846 Callee = getADAEntry(DAG, GA, DL, EPADelta);
1847 }
1848 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1850 E->getSymbol(), PtrVT, SystemZII::MO_ADA_DIRECT_FUNC_DESC);
1851 ADA = getADAEntry(DAG, ES, DL, ADADelta);
1852 Callee = getADAEntry(DAG, ES, DL, EPADelta);
1853 } else {
1854 // Function pointer case
1855 ADA = DAG.getNode(ISD::ADD, DL, PtrVT, Callee,
1856 DAG.getConstant(ADADelta, DL, PtrVT));
1857 ADA = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), ADA,
1859 Callee = DAG.getNode(ISD::ADD, DL, PtrVT, Callee,
1860 DAG.getConstant(EPADelta, DL, PtrVT));
1861 Callee = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Callee,
1863 }
1864 return false;
1865}
1866
1867SDValue
1869 SmallVectorImpl<SDValue> &InVals) const {
1870 SelectionDAG &DAG = CLI.DAG;
1871 SDLoc &DL = CLI.DL;
1873 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1875 SDValue Chain = CLI.Chain;
1876 SDValue Callee = CLI.Callee;
1877 bool &IsTailCall = CLI.IsTailCall;
1878 CallingConv::ID CallConv = CLI.CallConv;
1879 bool IsVarArg = CLI.IsVarArg;
1881 EVT PtrVT = getPointerTy(MF.getDataLayout());
1882 LLVMContext &Ctx = *DAG.getContext();
1884
1885 // FIXME: z/OS support to be added in later.
1886 if (Subtarget.isTargetXPLINK64())
1887 IsTailCall = false;
1888
1889 // Analyze the operands of the call, assigning locations to each operand.
1891 SystemZCCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, Ctx);
1892 ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
1893
1894 // We don't support GuaranteedTailCallOpt, only automatically-detected
1895 // sibling calls.
1896 if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs, Outs))
1897 IsTailCall = false;
1898
1899 // Get a count of how many bytes are to be pushed on the stack.
1900 unsigned NumBytes = ArgCCInfo.getStackSize();
1901
1902 // Mark the start of the call.
1903 if (!IsTailCall)
1904 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
1905
1906 // Copy argument values to their designated locations.
1908 SmallVector<SDValue, 8> MemOpChains;
1909 SDValue StackPtr;
1910 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1911 CCValAssign &VA = ArgLocs[I];
1912 SDValue ArgValue = OutVals[I];
1913
1914 if (VA.getLocInfo() == CCValAssign::Indirect) {
1915 // Store the argument in a stack slot and pass its address.
1916 unsigned ArgIndex = Outs[I].OrigArgIndex;
1917 EVT SlotVT;
1918 if (I + 1 != E && Outs[I + 1].OrigArgIndex == ArgIndex) {
1919 // Allocate the full stack space for a promoted (and split) argument.
1920 Type *OrigArgType = CLI.Args[Outs[I].OrigArgIndex].Ty;
1921 EVT OrigArgVT = getValueType(MF.getDataLayout(), OrigArgType);
1922 MVT PartVT = getRegisterTypeForCallingConv(Ctx, CLI.CallConv, OrigArgVT);
1923 unsigned N = getNumRegistersForCallingConv(Ctx, CLI.CallConv, OrigArgVT);
1924 SlotVT = EVT::getIntegerVT(Ctx, PartVT.getSizeInBits() * N);
1925 } else {
1926 SlotVT = Outs[I].VT;
1927 }
1928 SDValue SpillSlot = DAG.CreateStackTemporary(SlotVT);
1929 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1930 MemOpChains.push_back(
1931 DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1933 // If the original argument was split (e.g. i128), we need
1934 // to store all parts of it here (and pass just one address).
1935 assert (Outs[I].PartOffset == 0);
1936 while (I + 1 != E && Outs[I + 1].OrigArgIndex == ArgIndex) {
1937 SDValue PartValue = OutVals[I + 1];
1938 unsigned PartOffset = Outs[I + 1].PartOffset;
1939 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
1940 DAG.getIntPtrConstant(PartOffset, DL));
1941 MemOpChains.push_back(
1942 DAG.getStore(Chain, DL, PartValue, Address,
1944 assert((PartOffset + PartValue.getValueType().getStoreSize() <=
1945 SlotVT.getStoreSize()) && "Not enough space for argument part!");
1946 ++I;
1947 }
1948 ArgValue = SpillSlot;
1949 } else
1950 ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
1951
1952 if (VA.isRegLoc()) {
1953 // In XPLINK64, for the 128-bit vararg case, ArgValue is bitcasted to a
1954 // MVT::i128 type. We decompose the 128-bit type to a pair of its high
1955 // and low values.
1956 if (VA.getLocVT() == MVT::i128)
1957 ArgValue = lowerI128ToGR128(DAG, ArgValue);
1958 // Queue up the argument copies and emit them at the end.
1959 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1960 } else {
1961 assert(VA.isMemLoc() && "Argument not register or memory");
1962
1963 // Work out the address of the stack slot. Unpromoted ints and
1964 // floats are passed as right-justified 8-byte values.
1965 if (!StackPtr.getNode())
1966 StackPtr = DAG.getCopyFromReg(Chain, DL,
1967 Regs->getStackPointerRegister(), PtrVT);
1968 unsigned Offset = Regs->getStackPointerBias() + Regs->getCallFrameSize() +
1969 VA.getLocMemOffset();
1970 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1971 Offset += 4;
1972 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1974
1975 // Emit the store.
1976 MemOpChains.push_back(
1977 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
1978
1979 // Although long doubles or vectors are passed through the stack when
1980 // they are vararg (non-fixed arguments), if a long double or vector
1981 // occupies the third and fourth slot of the argument list GPR3 should
1982 // still shadow the third slot of the argument list.
1983 if (Subtarget.isTargetXPLINK64() && VA.needsCustom()) {
1984 SDValue ShadowArgValue =
1985 DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, ArgValue,
1986 DAG.getIntPtrConstant(1, DL));
1987 RegsToPass.push_back(std::make_pair(SystemZ::R3D, ShadowArgValue));
1988 }
1989 }
1990 }
1991
1992 // Join the stores, which are independent of one another.
1993 if (!MemOpChains.empty())
1994 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1995
1996 // Accept direct calls by converting symbolic call addresses to the
1997 // associated Target* opcodes. Force %r1 to be used for indirect
1998 // tail calls.
1999 SDValue Glue;
2000
2001 if (Subtarget.isTargetXPLINK64()) {
2002 SDValue ADA;
2003 bool IsBRASL = getzOSCalleeAndADA(DAG, Callee, ADA, DL, Chain);
2004 if (!IsBRASL) {
2005 unsigned CalleeReg = static_cast<SystemZXPLINK64Registers *>(Regs)
2006 ->getAddressOfCalleeRegister();
2007 Chain = DAG.getCopyToReg(Chain, DL, CalleeReg, Callee, Glue);
2008 Glue = Chain.getValue(1);
2009 Callee = DAG.getRegister(CalleeReg, Callee.getValueType());
2010 }
2011 RegsToPass.push_back(std::make_pair(
2012 static_cast<SystemZXPLINK64Registers *>(Regs)->getADARegister(), ADA));
2013 } else {
2014 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2015 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
2016 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2017 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2018 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
2019 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
2020 } else if (IsTailCall) {
2021 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
2022 Glue = Chain.getValue(1);
2023 Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
2024 }
2025 }
2026
2027 // Build a sequence of copy-to-reg nodes, chained and glued together.
2028 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
2029 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
2030 RegsToPass[I].second, Glue);
2031 Glue = Chain.getValue(1);
2032 }
2033
2034 // The first call operand is the chain and the second is the target address.
2036 Ops.push_back(Chain);
2037 Ops.push_back(Callee);
2038
2039 // Add argument registers to the end of the list so that they are
2040 // known live into the call.
2041 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
2042 Ops.push_back(DAG.getRegister(RegsToPass[I].first,
2043 RegsToPass[I].second.getValueType()));
2044
2045 // Add a register mask operand representing the call-preserved registers.
2046 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2047 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2048 assert(Mask && "Missing call preserved mask for calling convention");
2049 Ops.push_back(DAG.getRegisterMask(Mask));
2050
2051 // Glue the call to the argument copies, if any.
2052 if (Glue.getNode())
2053 Ops.push_back(Glue);
2054
2055 // Emit the call.
2056 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2057 if (IsTailCall) {
2058 SDValue Ret = DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
2059 DAG.addNoMergeSiteInfo(Ret.getNode(), CLI.NoMerge);
2060 return Ret;
2061 }
2062 Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
2063 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2064 Glue = Chain.getValue(1);
2065
2066 // Mark the end of the call, which is glued to the call itself.
2067 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, Glue, DL);
2068 Glue = Chain.getValue(1);
2069
2070 // Assign locations to each value returned by this call.
2072 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, Ctx);
2073 RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
2074
2075 // Copy all of the result registers out of their specified physreg.
2076 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
2077 CCValAssign &VA = RetLocs[I];
2078
2079 // Copy the value out, gluing the copy to the end of the call sequence.
2080 SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
2081 VA.getLocVT(), Glue);
2082 Chain = RetValue.getValue(1);
2083 Glue = RetValue.getValue(2);
2084
2085 // Convert the value of the return register into the value that's
2086 // being returned.
2087 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
2088 }
2089
2090 return Chain;
2091}
2092
2093// Generate a call taking the given operands as arguments and returning a
2094// result of type RetVT.
2096 SDValue Chain, SelectionDAG &DAG, const char *CalleeName, EVT RetVT,
2097 ArrayRef<SDValue> Ops, CallingConv::ID CallConv, bool IsSigned, SDLoc DL,
2098 bool DoesNotReturn, bool IsReturnValueUsed) const {
2100 Args.reserve(Ops.size());
2101
2103 for (SDValue Op : Ops) {
2104 Entry.Node = Op;
2105 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
2106 Entry.IsSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), IsSigned);
2107 Entry.IsZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), IsSigned);
2108 Args.push_back(Entry);
2109 }
2110
2111 SDValue Callee =
2112 DAG.getExternalSymbol(CalleeName, getPointerTy(DAG.getDataLayout()));
2113
2114 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2116 bool SignExtend = shouldSignExtendTypeInLibCall(RetVT, IsSigned);
2117 CLI.setDebugLoc(DL)
2118 .setChain(Chain)
2119 .setCallee(CallConv, RetTy, Callee, std::move(Args))
2120 .setNoReturn(DoesNotReturn)
2121 .setDiscardResult(!IsReturnValueUsed)
2122 .setSExtResult(SignExtend)
2123 .setZExtResult(!SignExtend);
2124 return LowerCallTo(CLI);
2125}
2126
2129 MachineFunction &MF, bool isVarArg,
2131 LLVMContext &Context) const {
2132 // Special case that we cannot easily detect in RetCC_SystemZ since
2133 // i128 may not be a legal type.
2134 for (auto &Out : Outs)
2135 if (Out.ArgVT == MVT::i128)
2136 return false;
2137
2139 CCState RetCCInfo(CallConv, isVarArg, MF, RetLocs, Context);
2140 return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ);
2141}
2142
2143SDValue
2145 bool IsVarArg,
2147 const SmallVectorImpl<SDValue> &OutVals,
2148 const SDLoc &DL, SelectionDAG &DAG) const {
2150
2151 // Assign locations to each returned value.
2153 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
2154 RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
2155
2156 // Quick exit for void returns
2157 if (RetLocs.empty())
2158 return DAG.getNode(SystemZISD::RET_GLUE, DL, MVT::Other, Chain);
2159
2160 if (CallConv == CallingConv::GHC)
2161 report_fatal_error("GHC functions return void only");
2162
2163 // Copy the result values into the output registers.
2164 SDValue Glue;
2166 RetOps.push_back(Chain);
2167 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
2168 CCValAssign &VA = RetLocs[I];
2169 SDValue RetValue = OutVals[I];
2170
2171 // Make the return register live on exit.
2172 assert(VA.isRegLoc() && "Can only return in registers!");
2173
2174 // Promote the value as required.
2175 RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
2176
2177 // Chain and glue the copies together.
2178 Register Reg = VA.getLocReg();
2179 Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
2180 Glue = Chain.getValue(1);
2181 RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
2182 }
2183
2184 // Update chain and glue.
2185 RetOps[0] = Chain;
2186 if (Glue.getNode())
2187 RetOps.push_back(Glue);
2188
2189 return DAG.getNode(SystemZISD::RET_GLUE, DL, MVT::Other, RetOps);
2190}
2191
2192// Return true if Op is an intrinsic node with chain that returns the CC value
2193// as its only (other) argument. Provide the associated SystemZISD opcode and
2194// the mask of valid CC values if so.
2195static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
2196 unsigned &CCValid) {
2197 unsigned Id = Op.getConstantOperandVal(1);
2198 switch (Id) {
2199 case Intrinsic::s390_tbegin:
2200 Opcode = SystemZISD::TBEGIN;
2201 CCValid = SystemZ::CCMASK_TBEGIN;
2202 return true;
2203
2204 case Intrinsic::s390_tbegin_nofloat:
2206 CCValid = SystemZ::CCMASK_TBEGIN;
2207 return true;
2208
2209 case Intrinsic::s390_tend:
2210 Opcode = SystemZISD::TEND;
2211 CCValid = SystemZ::CCMASK_TEND;
2212 return true;
2213
2214 default:
2215 return false;
2216 }
2217}
2218
2219// Return true if Op is an intrinsic node without chain that returns the
2220// CC value as its final argument. Provide the associated SystemZISD
2221// opcode and the mask of valid CC values if so.
2222static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) {
2223 unsigned Id = Op.getConstantOperandVal(0);
2224 switch (Id) {
2225 case Intrinsic::s390_vpkshs:
2226 case Intrinsic::s390_vpksfs:
2227 case Intrinsic::s390_vpksgs:
2228 Opcode = SystemZISD::PACKS_CC;
2229 CCValid = SystemZ::CCMASK_VCMP;
2230 return true;
2231
2232 case Intrinsic::s390_vpklshs:
2233 case Intrinsic::s390_vpklsfs:
2234 case Intrinsic::s390_vpklsgs:
2235 Opcode = SystemZISD::PACKLS_CC;
2236 CCValid = SystemZ::CCMASK_VCMP;
2237 return true;
2238
2239 case Intrinsic::s390_vceqbs:
2240 case Intrinsic::s390_vceqhs:
2241 case Intrinsic::s390_vceqfs:
2242 case Intrinsic::s390_vceqgs:
2243 Opcode = SystemZISD::VICMPES;
2244 CCValid = SystemZ::CCMASK_VCMP;
2245 return true;
2246
2247 case Intrinsic::s390_vchbs:
2248 case Intrinsic::s390_vchhs:
2249 case Intrinsic::s390_vchfs:
2250 case Intrinsic::s390_vchgs:
2251 Opcode = SystemZISD::VICMPHS;
2252 CCValid = SystemZ::CCMASK_VCMP;
2253 return true;
2254
2255 case Intrinsic::s390_vchlbs:
2256 case Intrinsic::s390_vchlhs:
2257 case Intrinsic::s390_vchlfs:
2258 case Intrinsic::s390_vchlgs:
2259 Opcode = SystemZISD::VICMPHLS;
2260 CCValid = SystemZ::CCMASK_VCMP;
2261 return true;
2262
2263 case Intrinsic::s390_vtm:
2264 Opcode = SystemZISD::VTM;
2265 CCValid = SystemZ::CCMASK_VCMP;
2266 return true;
2267
2268 case Intrinsic::s390_vfaebs:
2269 case Intrinsic::s390_vfaehs:
2270 case Intrinsic::s390_vfaefs:
2271 Opcode = SystemZISD::VFAE_CC;
2272 CCValid = SystemZ::CCMASK_ANY;
2273 return true;
2274
2275 case Intrinsic::s390_vfaezbs:
2276 case Intrinsic::s390_vfaezhs:
2277 case Intrinsic::s390_vfaezfs:
2278 Opcode = SystemZISD::VFAEZ_CC;
2279 CCValid = SystemZ::CCMASK_ANY;
2280 return true;
2281
2282 case Intrinsic::s390_vfeebs:
2283 case Intrinsic::s390_vfeehs:
2284 case Intrinsic::s390_vfeefs:
2285 Opcode = SystemZISD::VFEE_CC;
2286 CCValid = SystemZ::CCMASK_ANY;
2287 return true;
2288
2289 case Intrinsic::s390_vfeezbs:
2290 case Intrinsic::s390_vfeezhs:
2291 case Intrinsic::s390_vfeezfs:
2292 Opcode = SystemZISD::VFEEZ_CC;
2293 CCValid = SystemZ::CCMASK_ANY;
2294 return true;
2295
2296 case Intrinsic::s390_vfenebs:
2297 case Intrinsic::s390_vfenehs:
2298 case Intrinsic::s390_vfenefs:
2299 Opcode = SystemZISD::VFENE_CC;
2300 CCValid = SystemZ::CCMASK_ANY;
2301 return true;
2302
2303 case Intrinsic::s390_vfenezbs:
2304 case Intrinsic::s390_vfenezhs:
2305 case Intrinsic::s390_vfenezfs:
2306 Opcode = SystemZISD::VFENEZ_CC;
2307 CCValid = SystemZ::CCMASK_ANY;
2308 return true;
2309
2310 case Intrinsic::s390_vistrbs:
2311 case Intrinsic::s390_vistrhs:
2312 case Intrinsic::s390_vistrfs:
2313 Opcode = SystemZISD::VISTR_CC;
2315 return true;
2316
2317 case Intrinsic::s390_vstrcbs:
2318 case Intrinsic::s390_vstrchs:
2319 case Intrinsic::s390_vstrcfs:
2320 Opcode = SystemZISD::VSTRC_CC;
2321 CCValid = SystemZ::CCMASK_ANY;
2322 return true;
2323
2324 case Intrinsic::s390_vstrczbs:
2325 case Intrinsic::s390_vstrczhs:
2326 case Intrinsic::s390_vstrczfs:
2327 Opcode = SystemZISD::VSTRCZ_CC;
2328 CCValid = SystemZ::CCMASK_ANY;
2329 return true;
2330
2331 case Intrinsic::s390_vstrsb:
2332 case Intrinsic::s390_vstrsh:
2333 case Intrinsic::s390_vstrsf:
2334 Opcode = SystemZISD::VSTRS_CC;
2335 CCValid = SystemZ::CCMASK_ANY;
2336 return true;
2337
2338 case Intrinsic::s390_vstrszb:
2339 case Intrinsic::s390_vstrszh:
2340 case Intrinsic::s390_vstrszf:
2341 Opcode = SystemZISD::VSTRSZ_CC;
2342 CCValid = SystemZ::CCMASK_ANY;
2343 return true;
2344
2345 case Intrinsic::s390_vfcedbs:
2346 case Intrinsic::s390_vfcesbs:
2347 Opcode = SystemZISD::VFCMPES;
2348 CCValid = SystemZ::CCMASK_VCMP;
2349 return true;
2350
2351 case Intrinsic::s390_vfchdbs:
2352 case Intrinsic::s390_vfchsbs:
2353 Opcode = SystemZISD::VFCMPHS;
2354 CCValid = SystemZ::CCMASK_VCMP;
2355 return true;
2356
2357 case Intrinsic::s390_vfchedbs:
2358 case Intrinsic::s390_vfchesbs:
2359 Opcode = SystemZISD::VFCMPHES;
2360 CCValid = SystemZ::CCMASK_VCMP;
2361 return true;
2362
2363 case Intrinsic::s390_vftcidb:
2364 case Intrinsic::s390_vftcisb:
2365 Opcode = SystemZISD::VFTCI;
2366 CCValid = SystemZ::CCMASK_VCMP;
2367 return true;
2368
2369 case Intrinsic::s390_tdc:
2370 Opcode = SystemZISD::TDC;
2371 CCValid = SystemZ::CCMASK_TDC;
2372 return true;
2373
2374 default:
2375 return false;
2376 }
2377}
2378
2379// Emit an intrinsic with chain and an explicit CC register result.
2381 unsigned Opcode) {
2382 // Copy all operands except the intrinsic ID.
2383 unsigned NumOps = Op.getNumOperands();
2385 Ops.reserve(NumOps - 1);
2386 Ops.push_back(Op.getOperand(0));
2387 for (unsigned I = 2; I < NumOps; ++I)
2388 Ops.push_back(Op.getOperand(I));
2389
2390 assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
2391 SDVTList RawVTs = DAG.getVTList(MVT::i32, MVT::Other);
2392 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
2393 SDValue OldChain = SDValue(Op.getNode(), 1);
2394 SDValue NewChain = SDValue(Intr.getNode(), 1);
2395 DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
2396 return Intr.getNode();
2397}
2398
2399// Emit an intrinsic with an explicit CC register result.
2401 unsigned Opcode) {
2402 // Copy all operands except the intrinsic ID.
2403 unsigned NumOps = Op.getNumOperands();
2405 Ops.reserve(NumOps - 1);
2406 for (unsigned I = 1; I < NumOps; ++I)
2407 Ops.push_back(Op.getOperand(I));
2408
2409 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), Op->getVTList(), Ops);
2410 return Intr.getNode();
2411}
2412
2413// CC is a comparison that will be implemented using an integer or
2414// floating-point comparison. Return the condition code mask for
2415// a branch on true. In the integer case, CCMASK_CMP_UO is set for
2416// unsigned comparisons and clear for signed ones. In the floating-point
2417// case, CCMASK_CMP_UO has its normal mask meaning (unordered).
2419#define CONV(X) \
2420 case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
2421 case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
2422 case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
2423
2424 switch (CC) {
2425 default:
2426 llvm_unreachable("Invalid integer condition!");
2427
2428 CONV(EQ);
2429 CONV(NE);
2430 CONV(GT);
2431 CONV(GE);
2432 CONV(LT);
2433 CONV(LE);
2434
2435 case ISD::SETO: return SystemZ::CCMASK_CMP_O;
2437 }
2438#undef CONV
2439}
2440
2441// If C can be converted to a comparison against zero, adjust the operands
2442// as necessary.
2443static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
2444 if (C.ICmpType == SystemZICMP::UnsignedOnly)
2445 return;
2446
2447 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
2448 if (!ConstOp1 || ConstOp1->getValueSizeInBits(0) > 64)
2449 return;
2450
2451 int64_t Value = ConstOp1->getSExtValue();
2452 if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
2453 (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
2454 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
2455 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
2456 C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
2457 C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
2458 }
2459}
2460
2461// If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
2462// adjust the operands as necessary.
2463static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL,
2464 Comparison &C) {
2465 // For us to make any changes, it must a comparison between a single-use
2466 // load and a constant.
2467 if (!C.Op0.hasOneUse() ||
2468 C.Op0.getOpcode() != ISD::LOAD ||
2469 C.Op1.getOpcode() != ISD::Constant)
2470 return;
2471
2472 // We must have an 8- or 16-bit load.
2473 auto *Load = cast<LoadSDNode>(C.Op0);
2474 unsigned NumBits = Load->getMemoryVT().getSizeInBits();
2475 if ((NumBits != 8 && NumBits != 16) ||
2476 NumBits != Load->getMemoryVT().getStoreSizeInBits())
2477 return;
2478
2479 // The load must be an extending one and the constant must be within the
2480 // range of the unextended value.
2481 auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
2482 if (!ConstOp1 || ConstOp1->getValueSizeInBits(0) > 64)
2483 return;
2484 uint64_t Value = ConstOp1->getZExtValue();
2485 uint64_t Mask = (1 << NumBits) - 1;
2486 if (Load->getExtensionType() == ISD::SEXTLOAD) {
2487 // Make sure that ConstOp1 is in range of C.Op0.
2488 int64_t SignedValue = ConstOp1->getSExtValue();
2489 if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
2490 return;
2491 if (C.ICmpType != SystemZICMP::SignedOnly) {
2492 // Unsigned comparison between two sign-extended values is equivalent
2493 // to unsigned comparison between two zero-extended values.
2494 Value &= Mask;
2495 } else if (NumBits == 8) {
2496 // Try to treat the comparison as unsigned, so that we can use CLI.
2497 // Adjust CCMask and Value as necessary.
2498 if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
2499 // Test whether the high bit of the byte is set.
2500 Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
2501 else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
2502 // Test whether the high bit of the byte is clear.
2503 Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
2504 else
2505 // No instruction exists for this combination.
2506 return;
2507 C.ICmpType = SystemZICMP::UnsignedOnly;
2508 }
2509 } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
2510 if (Value > Mask)
2511 return;
2512 // If the constant is in range, we can use any comparison.
2513 C.ICmpType = SystemZICMP::Any;
2514 } else
2515 return;
2516
2517 // Make sure that the first operand is an i32 of the right extension type.
2518 ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
2521 if (C.Op0.getValueType() != MVT::i32 ||
2522 Load->getExtensionType() != ExtType) {
2523 C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32, Load->getChain(),
2524 Load->getBasePtr(), Load->getPointerInfo(),
2525 Load->getMemoryVT(), Load->getAlign(),
2526 Load->getMemOperand()->getFlags());
2527 // Update the chain uses.
2528 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), C.Op0.getValue(1));
2529 }
2530
2531 // Make sure that the second operand is an i32 with the right value.
2532 if (C.Op1.getValueType() != MVT::i32 ||
2533 Value != ConstOp1->getZExtValue())
2534 C.Op1 = DAG.getConstant(Value, DL, MVT::i32);
2535}
2536
2537// Return true if Op is either an unextended load, or a load suitable
2538// for integer register-memory comparisons of type ICmpType.
2539static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
2540 auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
2541 if (Load) {
2542 // There are no instructions to compare a register with a memory byte.
2543 if (Load->getMemoryVT() == MVT::i8)
2544 return false;
2545 // Otherwise decide on extension type.
2546 switch (Load->getExtensionType()) {
2547 case ISD::NON_EXTLOAD:
2548 return true;
2549 case ISD::SEXTLOAD:
2550 return ICmpType != SystemZICMP::UnsignedOnly;
2551 case ISD::ZEXTLOAD:
2552 return ICmpType != SystemZICMP::SignedOnly;
2553 default:
2554 break;
2555 }
2556 }
2557 return false;
2558}
2559
2560// Return true if it is better to swap the operands of C.
2561static bool shouldSwapCmpOperands(const Comparison &C) {
2562 // Leave i128 and f128 comparisons alone, since they have no memory forms.
2563 if (C.Op0.getValueType() == MVT::i128)
2564 return false;
2565 if (C.Op0.getValueType() == MVT::f128)
2566 return false;
2567
2568 // Always keep a floating-point constant second, since comparisons with
2569 // zero can use LOAD TEST and comparisons with other constants make a
2570 // natural memory operand.
2571 if (isa<ConstantFPSDNode>(C.Op1))
2572 return false;
2573
2574 // Never swap comparisons with zero since there are many ways to optimize
2575 // those later.
2576 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
2577 if (ConstOp1 && ConstOp1->getZExtValue() == 0)
2578 return false;
2579
2580 // Also keep natural memory operands second if the loaded value is
2581 // only used here. Several comparisons have memory forms.
2582 if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
2583 return false;
2584
2585 // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
2586 // In that case we generally prefer the memory to be second.
2587 if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
2588 // The only exceptions are when the second operand is a constant and
2589 // we can use things like CHHSI.
2590 if (!ConstOp1)
2591 return true;
2592 // The unsigned memory-immediate instructions can handle 16-bit
2593 // unsigned integers.
2594 if (C.ICmpType != SystemZICMP::SignedOnly &&
2595 isUInt<16>(ConstOp1->getZExtValue()))
2596 return false;
2597 // The signed memory-immediate instructions can handle 16-bit
2598 // signed integers.
2599 if (C.ICmpType != SystemZICMP::UnsignedOnly &&
2600 isInt<16>(ConstOp1->getSExtValue()))
2601 return false;
2602 return true;
2603 }
2604
2605 // Try to promote the use of CGFR and CLGFR.
2606 unsigned Opcode0 = C.Op0.getOpcode();
2607 if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
2608 return true;
2609 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
2610 return true;
2611 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::AND &&
2612 C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
2613 C.Op0.getConstantOperandVal(1) == 0xffffffff)
2614 return true;
2615
2616 return false;
2617}
2618
2619// Check whether C tests for equality between X and Y and whether X - Y
2620// or Y - X is also computed. In that case it's better to compare the
2621// result of the subtraction against zero.
2623 Comparison &C) {
2624 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
2625 C.CCMask == SystemZ::CCMASK_CMP_NE) {
2626 for (SDNode *N : C.Op0->uses()) {
2627 if (N->getOpcode() == ISD::SUB &&
2628 ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
2629 (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
2630 // Disable the nsw and nuw flags: the backend needs to handle
2631 // overflow as well during comparison elimination.
2632 SDNodeFlags Flags = N->getFlags();
2633 Flags.setNoSignedWrap(false);
2634 Flags.setNoUnsignedWrap(false);
2635 N->setFlags(Flags);
2636 C.Op0 = SDValue(N, 0);
2637 C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
2638 return;
2639 }
2640 }
2641 }
2642}
2643
2644// Check whether C compares a floating-point value with zero and if that
2645// floating-point value is also negated. In this case we can use the
2646// negation to set CC, so avoiding separate LOAD AND TEST and
2647// LOAD (NEGATIVE/COMPLEMENT) instructions.
2648static void adjustForFNeg(Comparison &C) {
2649 // This optimization is invalid for strict comparisons, since FNEG
2650 // does not raise any exceptions.
2651 if (C.Chain)
2652 return;
2653 auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
2654 if (C1 && C1->isZero()) {
2655 for (SDNode *N : C.Op0->uses()) {
2656 if (N->getOpcode() == ISD::FNEG) {
2657 C.Op0 = SDValue(N, 0);
2658 C.CCMask = SystemZ::reverseCCMask(C.CCMask);
2659 return;
2660 }
2661 }
2662 }
2663}
2664
2665// Check whether C compares (shl X, 32) with 0 and whether X is
2666// also sign-extended. In that case it is better to test the result
2667// of the sign extension using LTGFR.
2668//
2669// This case is important because InstCombine transforms a comparison
2670// with (sext (trunc X)) into a comparison with (shl X, 32).
2671static void adjustForLTGFR(Comparison &C) {
2672 // Check for a comparison between (shl X, 32) and 0.
2673 if (C.Op0.getOpcode() == ISD::SHL && C.Op0.getValueType() == MVT::i64 &&
2674 C.Op1.getOpcode() == ISD::Constant && C.Op1->getAsZExtVal() == 0) {
2675 auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
2676 if (C1 && C1->getZExtValue() == 32) {
2677 SDValue ShlOp0 = C.Op0.getOperand(0);
2678 // See whether X has any SIGN_EXTEND_INREG uses.
2679 for (SDNode *N : ShlOp0->uses()) {
2680 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
2681 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
2682 C.Op0 = SDValue(N, 0);
2683 return;
2684 }
2685 }
2686 }
2687 }
2688}
2689
2690// If C compares the truncation of an extending load, try to compare
2691// the untruncated value instead. This exposes more opportunities to
2692// reuse CC.
2693static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL,
2694 Comparison &C) {
2695 if (C.Op0.getOpcode() == ISD::TRUNCATE &&
2696 C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
2697 C.Op1.getOpcode() == ISD::Constant &&
2698 cast<ConstantSDNode>(C.Op1)->getValueSizeInBits(0) <= 64 &&
2699 C.Op1->getAsZExtVal() == 0) {
2700 auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
2701 if (L->getMemoryVT().getStoreSizeInBits().getFixedValue() <=
2702 C.Op0.getValueSizeInBits().getFixedValue()) {
2703 unsigned Type = L->getExtensionType();
2704 if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
2705 (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
2706 C.Op0 = C.Op0.getOperand(0);
2707 C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
2708 }
2709 }
2710 }
2711}
2712
2713// Return true if shift operation N has an in-range constant shift value.
2714// Store it in ShiftVal if so.
2715static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
2716 auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
2717 if (!Shift)
2718 return false;
2719
2720 uint64_t Amount = Shift->getZExtValue();
2721 if (Amount >= N.getValueSizeInBits())
2722 return false;
2723
2724 ShiftVal = Amount;
2725 return true;
2726}
2727
2728// Check whether an AND with Mask is suitable for a TEST UNDER MASK
2729// instruction and whether the CC value is descriptive enough to handle
2730// a comparison of type Opcode between the AND result and CmpVal.
2731// CCMask says which comparison result is being tested and BitSize is
2732// the number of bits in the operands. If TEST UNDER MASK can be used,
2733// return the corresponding CC mask, otherwise return 0.
2734static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
2735 uint64_t Mask, uint64_t CmpVal,
2736 unsigned ICmpType) {
2737 assert(Mask != 0 && "ANDs with zero should have been removed by now");
2738
2739 // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
2740 if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
2741 !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
2742 return 0;
2743
2744 // Work out the masks for the lowest and highest bits.
2746 uint64_t Low = uint64_t(1) << llvm::countr_zero(Mask);
2747
2748 // Signed ordered comparisons are effectively unsigned if the sign
2749 // bit is dropped.
2750 bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
2751
2752 // Check for equality comparisons with 0, or the equivalent.
2753 if (CmpVal == 0) {
2754 if (CCMask == SystemZ::CCMASK_CMP_EQ)
2756 if (CCMask == SystemZ::CCMASK_CMP_NE)
2758 }
2759 if (EffectivelyUnsigned && CmpVal > 0 && CmpVal <= Low) {
2760 if (CCMask == SystemZ::CCMASK_CMP_LT)
2762 if (CCMask == SystemZ::CCMASK_CMP_GE)
2764 }
2765 if (EffectivelyUnsigned && CmpVal < Low) {
2766 if (CCMask == SystemZ::CCMASK_CMP_LE)
2768 if (CCMask == SystemZ::CCMASK_CMP_GT)
2770 }
2771
2772 // Check for equality comparisons with the mask, or the equivalent.
2773 if (CmpVal == Mask) {
2774 if (CCMask == SystemZ::CCMASK_CMP_EQ)
2776 if (CCMask == SystemZ::CCMASK_CMP_NE)
2778 }
2779 if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
2780 if (CCMask == SystemZ::CCMASK_CMP_GT)
2782 if (CCMask == SystemZ::CCMASK_CMP_LE)
2784 }
2785 if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
2786 if (CCMask == SystemZ::CCMASK_CMP_GE)
2788 if (CCMask == SystemZ::CCMASK_CMP_LT)
2790 }
2791
2792 // Check for ordered comparisons with the top bit.
2793 if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
2794 if (CCMask == SystemZ::CCMASK_CMP_LE)
2796 if (CCMask == SystemZ::CCMASK_CMP_GT)
2798 }
2799 if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
2800 if (CCMask == SystemZ::CCMASK_CMP_LT)
2802 if (CCMask == SystemZ::CCMASK_CMP_GE)
2804 }
2805
2806 // If there are just two bits, we can do equality checks for Low and High
2807 // as well.
2808 if (Mask == Low + High) {
2809 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
2811 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
2813 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
2815 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
2817 }
2818
2819 // Looks like we've exhausted our options.
2820 return 0;
2821}
2822
2823// See whether C can be implemented as a TEST UNDER MASK instruction.
2824// Update the arguments with the TM version if so.
2826 Comparison &C) {
2827 // Use VECTOR TEST UNDER MASK for i128 operations.
2828 if (C.Op0.getValueType() == MVT::i128) {
2829 // We can use VTM for EQ/NE comparisons of x & y against 0.
2830 if (C.Op0.getOpcode() == ISD::AND &&
2831 (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
2832 C.CCMask == SystemZ::CCMASK_CMP_NE)) {
2833 auto *Mask = dyn_cast<ConstantSDNode>(C.Op1);
2834 if (Mask && Mask->getAPIntValue() == 0) {
2835 C.Opcode = SystemZISD::VTM;
2836 C.Op1 = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, C.Op0.getOperand(1));
2837 C.Op0 = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, C.Op0.getOperand(0));
2838 C.CCValid = SystemZ::CCMASK_VCMP;
2839 if (C.CCMask == SystemZ::CCMASK_CMP_EQ)
2840 C.CCMask = SystemZ::CCMASK_VCMP_ALL;
2841 else
2842 C.CCMask = SystemZ::CCMASK_VCMP_ALL ^ C.CCValid;
2843 }
2844 }
2845 return;
2846 }
2847
2848 // Check that we have a comparison with a constant.
2849 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
2850 if (!ConstOp1)
2851 return;
2852 uint64_t CmpVal = ConstOp1->getZExtValue();
2853
2854 // Check whether the nonconstant input is an AND with a constant mask.
2855 Comparison NewC(C);
2856 uint64_t MaskVal;
2857 ConstantSDNode *Mask = nullptr;
2858 if (C.Op0.getOpcode() == ISD::AND) {
2859 NewC.Op0 = C.Op0.getOperand(0);
2860 NewC.Op1 = C.Op0.getOperand(1);
2861 Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
2862 if (!Mask)
2863 return;
2864 MaskVal = Mask->getZExtValue();
2865 } else {
2866 // There is no instruction to compare with a 64-bit immediate
2867 // so use TMHH instead if possible. We need an unsigned ordered
2868 // comparison with an i64 immediate.
2869 if (NewC.Op0.getValueType() != MVT::i64 ||
2870 NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
2871 NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
2872 NewC.ICmpType == SystemZICMP::SignedOnly)
2873 return;
2874 // Convert LE and GT comparisons into LT and GE.
2875 if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
2876 NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
2877 if (CmpVal == uint64_t(-1))
2878 return;
2879 CmpVal += 1;
2880 NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
2881 }
2882 // If the low N bits of Op1 are zero than the low N bits of Op0 can
2883 // be masked off without changing the result.
2884 MaskVal = -(CmpVal & -CmpVal);
2885 NewC.ICmpType = SystemZICMP::UnsignedOnly;
2886 }
2887 if (!MaskVal)
2888 return;
2889
2890 // Check whether the combination of mask, comparison value and comparison
2891 // type are suitable.
2892 unsigned BitSize = NewC.Op0.getValueSizeInBits();
2893 unsigned NewCCMask, ShiftVal;
2894 if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2895 NewC.Op0.getOpcode() == ISD::SHL &&
2896 isSimpleShift(NewC.Op0, ShiftVal) &&
2897 (MaskVal >> ShiftVal != 0) &&
2898 ((CmpVal >> ShiftVal) << ShiftVal) == CmpVal &&
2899 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2900 MaskVal >> ShiftVal,
2901 CmpVal >> ShiftVal,
2902 SystemZICMP::Any))) {
2903 NewC.Op0 = NewC.Op0.getOperand(0);
2904 MaskVal >>= ShiftVal;
2905 } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2906 NewC.Op0.getOpcode() == ISD::SRL &&
2907 isSimpleShift(NewC.Op0, ShiftVal) &&
2908 (MaskVal << ShiftVal != 0) &&
2909 ((CmpVal << ShiftVal) >> ShiftVal) == CmpVal &&
2910 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2911 MaskVal << ShiftVal,
2912 CmpVal << ShiftVal,
2914 NewC.Op0 = NewC.Op0.getOperand(0);
2915 MaskVal <<= ShiftVal;
2916 } else {
2917 NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
2918 NewC.ICmpType);
2919 if (!NewCCMask)
2920 return;
2921 }
2922
2923 // Go ahead and make the change.
2924 C.Opcode = SystemZISD::TM;
2925 C.Op0 = NewC.Op0;
2926 if (Mask && Mask->getZExtValue() == MaskVal)
2927 C.Op1 = SDValue(Mask, 0);
2928 else
2929 C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
2930 C.CCValid = SystemZ::CCMASK_TM;
2931 C.CCMask = NewCCMask;
2932}
2933
2934// Implement i128 comparison in vector registers.
2935static void adjustICmp128(SelectionDAG &DAG, const SDLoc &DL,
2936 Comparison &C) {
2937 if (C.Opcode != SystemZISD::ICMP)
2938 return;
2939 if (C.Op0.getValueType() != MVT::i128)
2940 return;
2941
2942 // (In-)Equality comparisons can be implemented via VCEQGS.
2943 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
2944 C.CCMask == SystemZ::CCMASK_CMP_NE) {
2945 C.Opcode = SystemZISD::VICMPES;
2946 C.Op0 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, C.Op0);
2947 C.Op1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, C.Op1);
2948 C.CCValid = SystemZ::CCMASK_VCMP;
2949 if (C.CCMask == SystemZ::CCMASK_CMP_EQ)
2950 C.CCMask = SystemZ::CCMASK_VCMP_ALL;
2951 else
2952 C.CCMask = SystemZ::CCMASK_VCMP_ALL ^ C.CCValid;
2953 return;
2954 }
2955
2956 // Normalize other comparisons to GT.
2957 bool Swap = false, Invert = false;
2958 switch (C.CCMask) {
2959 case SystemZ::CCMASK_CMP_GT: break;
2960 case SystemZ::CCMASK_CMP_LT: Swap = true; break;
2961 case SystemZ::CCMASK_CMP_LE: Invert = true; break;
2962 case SystemZ::CCMASK_CMP_GE: Swap = Invert = true; break;
2963 default: llvm_unreachable("Invalid integer condition!");
2964 }
2965 if (Swap)
2966 std::swap(C.Op0, C.Op1);
2967
2968 if (C.ICmpType == SystemZICMP::UnsignedOnly)
2969 C.Opcode = SystemZISD::UCMP128HI;
2970 else
2971 C.Opcode = SystemZISD::SCMP128HI;
2972 C.CCValid = SystemZ::CCMASK_ANY;
2973 C.CCMask = SystemZ::CCMASK_1;
2974
2975 if (Invert)
2976 C.CCMask ^= C.CCValid;
2977}
2978
2979// See whether the comparison argument contains a redundant AND
2980// and remove it if so. This sometimes happens due to the generic
2981// BRCOND expansion.
2983 Comparison &C) {
2984 if (C.Op0.getOpcode() != ISD::AND)
2985 return;
2986 auto *Mask = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
2987 if (!Mask || Mask->getValueSizeInBits(0) > 64)
2988 return;
2989 KnownBits Known = DAG.computeKnownBits(C.Op0.getOperand(0));
2990 if ((~Known.Zero).getZExtValue() & ~Mask->getZExtValue())
2991 return;
2992
2993 C.Op0 = C.Op0.getOperand(0);
2994}
2995
2996// Return a Comparison that tests the condition-code result of intrinsic
2997// node Call against constant integer CC using comparison code Cond.
2998// Opcode is the opcode of the SystemZISD operation for the intrinsic
2999// and CCValid is the set of possible condition-code results.
3000static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
3001 SDValue Call, unsigned CCValid, uint64_t CC,
3003 Comparison C(Call, SDValue(), SDValue());
3004 C.Opcode = Opcode;
3005 C.CCValid = CCValid;
3006 if (Cond == ISD::SETEQ)
3007 // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
3008 C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
3009 else if (Cond == ISD::SETNE)
3010 // ...and the inverse of that.
3011 C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
3012 else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
3013 // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
3014 // always true for CC>3.
3015 C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1;
3016 else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
3017 // ...and the inverse of that.
3018 C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0;
3019 else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
3020 // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
3021 // always true for CC>3.
3022 C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1;
3023 else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
3024 // ...and the inverse of that.
3025 C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0;
3026 else
3027 llvm_unreachable("Unexpected integer comparison type");
3028 C.CCMask &= CCValid;
3029 return C;
3030}
3031
3032// Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
3033static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
3034 ISD::CondCode Cond, const SDLoc &DL,
3035 SDValue Chain = SDValue(),
3036 bool IsSignaling = false) {
3037 if (CmpOp1.getOpcode() == ISD::Constant) {
3038 assert(!Chain);
3039 unsigned Opcode, CCValid;
3040 if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
3041 CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
3042 isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
3043 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid,
3044 CmpOp1->getAsZExtVal(), Cond);
3045 if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
3046 CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 &&
3047 isIntrinsicWithCC(CmpOp0, Opcode, CCValid))
3048 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid,
3049 CmpOp1->getAsZExtVal(), Cond);
3050 }
3051 Comparison C(CmpOp0, CmpOp1, Chain);
3052 C.CCMask = CCMaskForCondCode(Cond);
3053 if (C.Op0.getValueType().isFloatingPoint()) {
3054 C.CCValid = SystemZ::CCMASK_FCMP;
3055 if (!C.Chain)
3056 C.Opcode = SystemZISD::FCMP;
3057 else if (!IsSignaling)
3058 C.Opcode = SystemZISD::STRICT_FCMP;
3059 else
3060 C.Opcode = SystemZISD::STRICT_FCMPS;
3062 } else {
3063 assert(!C.Chain);
3064 C.CCValid = SystemZ::CCMASK_ICMP;
3065 C.Opcode = SystemZISD::ICMP;
3066 // Choose the type of comparison. Equality and inequality tests can
3067 // use either signed or unsigned comparisons. The choice also doesn't
3068 // matter if both sign bits are known to be clear. In those cases we
3069 // want to give the main isel code the freedom to choose whichever
3070 // form fits best.
3071 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
3072 C.CCMask == SystemZ::CCMASK_CMP_NE ||
3073 (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
3074 C.ICmpType = SystemZICMP::Any;
3075 else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
3076 C.ICmpType = SystemZICMP::UnsignedOnly;
3077 else
3078 C.ICmpType = SystemZICMP::SignedOnly;
3079 C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
3080 adjustForRedundantAnd(DAG, DL, C);
3081 adjustZeroCmp(DAG, DL, C);
3082 adjustSubwordCmp(DAG, DL, C);
3083 adjustForSubtraction(DAG, DL, C);
3085 adjustICmpTruncate(DAG, DL, C);
3086 }
3087
3088 if (shouldSwapCmpOperands(C)) {
3089 std::swap(C.Op0, C.Op1);
3090 C.CCMask = SystemZ::reverseCCMask(C.CCMask);
3091 }
3092
3094 adjustICmp128(DAG, DL, C);
3095 return C;
3096}
3097
3098// Emit the comparison instruction described by C.
3099static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
3100 if (!C.Op1.getNode()) {
3101 SDNode *Node;
3102 switch (C.Op0.getOpcode()) {
3104 Node = emitIntrinsicWithCCAndChain(DAG, C.Op0, C.Opcode);
3105 return SDValue(Node, 0);
3107 Node = emitIntrinsicWithCC(DAG, C.Op0, C.Opcode);
3108 return SDValue(Node, Node->getNumValues() - 1);
3109 default:
3110 llvm_unreachable("Invalid comparison operands");
3111 }
3112 }
3113 if (C.Opcode == SystemZISD::ICMP)
3114 return DAG.getNode(SystemZISD::ICMP, DL, MVT::i32, C.Op0, C.Op1,
3115 DAG.getTargetConstant(C.ICmpType, DL, MVT::i32));
3116 if (C.Opcode == SystemZISD::TM) {
3117 bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
3119 return DAG.getNode(SystemZISD::TM, DL, MVT::i32, C.Op0, C.Op1,
3120 DAG.getTargetConstant(RegisterOnly, DL, MVT::i32));
3121 }
3122 if (C.Opcode == SystemZISD::VICMPES) {
3123 SDVTList VTs = DAG.getVTList(C.Op0.getValueType(), MVT::i32);
3124 SDValue Val = DAG.getNode(C.Opcode, DL, VTs, C.Op0, C.Op1);
3125 return SDValue(Val.getNode(), 1);
3126 }
3127 if (C.Chain) {
3128 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
3129 return DAG.getNode(C.Opcode, DL, VTs, C.Chain, C.Op0, C.Op1);
3130 }
3131 return DAG.getNode(C.Opcode, DL, MVT::i32, C.Op0, C.Op1);
3132}
3133
3134// Implement a 32-bit *MUL_LOHI operation by extending both operands to
3135// 64 bits. Extend is the extension type to use. Store the high part
3136// in Hi and the low part in Lo.
3137static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend,
3138 SDValue Op0, SDValue Op1, SDValue &Hi,
3139 SDValue &Lo) {
3140 Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
3141 Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
3142 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
3143 Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
3144 DAG.getConstant(32, DL, MVT::i64));
3145 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
3146 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
3147}
3148
3149// Lower a binary operation that produces two VT results, one in each
3150// half of a GR128 pair. Op0 and Op1 are the VT operands to the operation,
3151// and Opcode performs the GR128 operation. Store the even register result
3152// in Even and the odd register result in Odd.
3153static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
3154 unsigned Opcode, SDValue Op0, SDValue Op1,
3155 SDValue &Even, SDValue &Odd) {
3156 SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped, Op0, Op1);
3157 bool Is32Bit = is32Bit(VT);
3158 Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
3159 Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
3160}
3161
3162// Return an i32 value that is 1 if the CC value produced by CCReg is
3163// in the mask CCMask and 0 otherwise. CC is known to have a value
3164// in CCValid, so other values can be ignored.
3165static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue CCReg,
3166 unsigned CCValid, unsigned CCMask) {
3167 SDValue Ops[] = {DAG.getConstant(1, DL, MVT::i32),
3168 DAG.getConstant(0, DL, MVT::i32),
3169 DAG.getTargetConstant(CCValid, DL, MVT::i32),
3170 DAG.getTargetConstant(CCMask, DL, MVT::i32), CCReg};
3171 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, MVT::i32, Ops);
3172}
3173
3174// Return the SystemISD vector comparison operation for CC, or 0 if it cannot
3175// be done directly. Mode is CmpMode::Int for integer comparisons, CmpMode::FP
3176// for regular floating-point comparisons, CmpMode::StrictFP for strict (quiet)
3177// floating-point comparisons, and CmpMode::SignalingFP for strict signaling
3178// floating-point comparisons.
3181 switch (CC) {
3182 case ISD::SETOEQ:
3183 case ISD::SETEQ:
3184 switch (Mode) {
3185 case CmpMode::Int: return SystemZISD::VICMPE;
3186 case CmpMode::FP: return SystemZISD::VFCMPE;
3187 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPE;
3188 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPES;
3189 }
3190 llvm_unreachable("Bad mode");
3191
3192 case ISD::SETOGE:
3193 case ISD::SETGE:
3194 switch (Mode) {
3195 case CmpMode::Int: return 0;
3196 case CmpMode::FP: return SystemZISD::VFCMPHE;
3197 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPHE;
3198 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHES;
3199 }
3200 llvm_unreachable("Bad mode");
3201
3202 case ISD::SETOGT:
3203 case ISD::SETGT:
3204 switch (Mode) {
3205 case CmpMode::Int: return SystemZISD::VICMPH;
3206 case CmpMode::FP: return SystemZISD::VFCMPH;
3207 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPH;
3208 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHS;
3209 }
3210 llvm_unreachable("Bad mode");
3211
3212 case ISD::SETUGT:
3213 switch (Mode) {
3214 case CmpMode::Int: return SystemZISD::VICMPHL;
3215 case CmpMode::FP: return 0;
3216 case CmpMode::StrictFP: return 0;
3217 case CmpMode::SignalingFP: return 0;
3218 }
3219 llvm_unreachable("Bad mode");
3220
3221 default:
3222 return 0;
3223 }
3224}
3225
3226// Return the SystemZISD vector comparison operation for CC or its inverse,
3227// or 0 if neither can be done directly. Indicate in Invert whether the
3228// result is for the inverse of CC. Mode is as above.
3230 bool &Invert) {
3231 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
3232 Invert = false;
3233 return Opcode;
3234 }
3235
3236 CC = ISD::getSetCCInverse(CC, Mode == CmpMode::Int ? MVT::i32 : MVT::f32);
3237 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
3238 Invert = true;
3239 return Opcode;
3240 }
3241
3242 return 0;
3243}
3244
3245// Return a v2f64 that contains the extended form of elements Start and Start+1
3246// of v4f32 value Op. If Chain is nonnull, return the strict form.
3247static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL,
3248 SDValue Op, SDValue Chain) {
3249 int Mask[] = { Start, -1, Start + 1, -1 };
3250 Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
3251 if (Chain) {
3252 SDVTList VTs = DAG.getVTList(MVT::v2f64, MVT::Other);
3253 return DAG.getNode(SystemZISD::STRICT_VEXTEND, DL, VTs, Chain, Op);
3254 }
3255 return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
3256}
3257
3258// Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
3259// producing a result of type VT. If Chain is nonnull, return the strict form.
3260SDValue SystemZTargetLowering::getVectorCmp(SelectionDAG &DAG, unsigned Opcode,
3261 const SDLoc &DL, EVT VT,
3262 SDValue CmpOp0,
3263 SDValue CmpOp1,
3264 SDValue Chain) const {
3265 // There is no hardware support for v4f32 (unless we have the vector
3266 // enhancements facility 1), so extend the vector into two v2f64s
3267 // and compare those.
3268 if (CmpOp0.getValueType() == MVT::v4f32 &&
3269 !Subtarget.hasVectorEnhancements1()) {
3270 SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0, Chain);
3271 SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0, Chain);
3272 SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1, Chain);
3273 SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1, Chain);
3274 if (Chain) {
3275 SDVTList VTs = DAG.getVTList(MVT::v2i64, MVT::Other);
3276 SDValue HRes = DAG.getNode(Opcode, DL, VTs, Chain, H0, H1);
3277 SDValue LRes = DAG.getNode(Opcode, DL, VTs, Chain, L0, L1);
3278 SDValue Res = DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
3279 SDValue Chains[6] = { H0.getValue(1), L0.getValue(1),
3280 H1.getValue(1), L1.getValue(1),
3281 HRes.getValue(1), LRes.getValue(1) };
3282 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
3283 SDValue Ops[2] = { Res, NewChain };
3284 return DAG.getMergeValues(Ops, DL);
3285 }
3286 SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
3287 SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
3288 return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
3289 }
3290 if (Chain) {
3291 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3292 return DAG.getNode(Opcode, DL, VTs, Chain, CmpOp0, CmpOp1);
3293 }
3294 return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
3295}
3296
3297// Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
3298// an integer mask of type VT. If Chain is nonnull, we have a strict
3299// floating-point comparison. If in addition IsSignaling is true, we have
3300// a strict signaling floating-point comparison.
3301SDValue SystemZTargetLowering::lowerVectorSETCC(SelectionDAG &DAG,
3302 const SDLoc &DL, EVT VT,
3304 SDValue CmpOp0,
3305 SDValue CmpOp1,
3306 SDValue Chain,
3307 bool IsSignaling) const {
3308 bool IsFP = CmpOp0.getValueType().isFloatingPoint();
3309 assert (!Chain || IsFP);
3310 assert (!IsSignaling || Chain);
3311 CmpMode Mode = IsSignaling ? CmpMode::SignalingFP :
3312 Chain ? CmpMode::StrictFP : IsFP ? CmpMode::FP : CmpMode::Int;
3313 bool Invert = false;
3314 SDValue Cmp;
3315 switch (CC) {
3316 // Handle tests for order using (or (ogt y x) (oge x y)).
3317 case ISD::SETUO:
3318 Invert = true;
3319 [[fallthrough]];
3320 case ISD::SETO: {
3321 assert(IsFP && "Unexpected integer comparison");
3322 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
3323 DL, VT, CmpOp1, CmpOp0, Chain);
3324 SDValue GE = getVectorCmp(DAG, getVectorComparison(ISD::SETOGE, Mode),
3325 DL, VT, CmpOp0, CmpOp1, Chain);
3326 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
3327 if (Chain)
3328 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
3329 LT.getValue(1), GE.getValue(1));
3330 break;
3331 }
3332
3333 // Handle <> tests using (or (ogt y x) (ogt x y)).
3334 case ISD::SETUEQ:
3335 Invert = true;
3336 [[fallthrough]];
3337 case ISD::SETONE: {
3338 assert(IsFP && "Unexpected integer comparison");
3339 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
3340 DL, VT, CmpOp1, CmpOp0, Chain);
3341 SDValue GT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
3342 DL, VT, CmpOp0, CmpOp1, Chain);
3343 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
3344 if (Chain)
3345 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
3346 LT.getValue(1), GT.getValue(1));
3347 break;
3348 }
3349
3350 // Otherwise a single comparison is enough. It doesn't really
3351 // matter whether we try the inversion or the swap first, since
3352 // there are no cases where both work.
3353 default:
3354 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
3355 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1, Chain);
3356 else {
3358 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
3359 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0, Chain);
3360 else
3361 llvm_unreachable("Unhandled comparison");
3362 }
3363 if (Chain)
3364 Chain = Cmp.getValue(1);
3365 break;
3366 }
3367 if (Invert) {
3368 SDValue Mask =
3369 DAG.getSplatBuildVector(VT, DL, DAG.getConstant(-1, DL, MVT::i64));
3370 Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
3371 }
3372 if (Chain && Chain.getNode() != Cmp.getNode()) {
3373 SDValue Ops[2] = { Cmp, Chain };
3374 Cmp = DAG.getMergeValues(Ops, DL);
3375 }
3376 return Cmp;
3377}
3378
3379SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
3380 SelectionDAG &DAG) const {
3381 SDValue CmpOp0 = Op.getOperand(0);
3382 SDValue CmpOp1 = Op.getOperand(1);
3383 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3384 SDLoc DL(Op);
3385 EVT VT = Op.getValueType();
3386 if (VT.isVector())
3387 return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
3388
3389 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
3390 SDValue CCReg = emitCmp(DAG, DL, C);
3391 return emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
3392}
3393
3394SDValue SystemZTargetLowering::lowerSTRICT_FSETCC(SDValue Op,
3395 SelectionDAG &DAG,
3396 bool IsSignaling) const {
3397 SDValue Chain = Op.getOperand(0);
3398 SDValue CmpOp0 = Op.getOperand(1);
3399 SDValue CmpOp1 = Op.getOperand(2);
3400 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
3401 SDLoc DL(Op);
3402 EVT VT = Op.getNode()->getValueType(0);
3403 if (VT.isVector()) {
3404 SDValue Res = lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1,
3405 Chain, IsSignaling);
3406 return Res.getValue(Op.getResNo());
3407 }
3408
3409 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL, Chain, IsSignaling));
3410 SDValue CCReg = emitCmp(DAG, DL, C);
3411 CCReg->setFlags(Op->getFlags());
3412 SDValue Result = emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
3413 SDValue Ops[2] = { Result, CCReg.getValue(1) };
3414 return DAG.getMergeValues(Ops, DL);
3415}
3416
3417SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3418 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3419 SDValue CmpOp0 = Op.getOperand(2);
3420 SDValue CmpOp1 = Op.getOperand(3);
3421 SDValue Dest = Op.getOperand(4);
3422 SDLoc DL(Op);
3423
3424 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
3425 SDValue CCReg = emitCmp(DAG, DL, C);
3426 return DAG.getNode(
3427 SystemZISD::BR_CCMASK, DL, Op.getValueType(), Op.getOperand(0),
3428 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
3429 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), Dest, CCReg);
3430}
3431
3432// Return true if Pos is CmpOp and Neg is the negative of CmpOp,
3433// allowing Pos and Neg to be wider than CmpOp.
3434static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
3435 return (Neg.getOpcode() == ISD::SUB &&
3436 Neg.getOperand(0).getOpcode() == ISD::Constant &&
3437 Neg.getConstantOperandVal(0) == 0 && Neg.getOperand(1) == Pos &&
3438 (Pos == CmpOp || (Pos.getOpcode() == ISD::SIGN_EXTEND &&
3439 Pos.getOperand(0) == CmpOp)));
3440}
3441
3442// Return the absolute or negative absolute of Op; IsNegative decides which.
3444 bool IsNegative) {
3445 Op = DAG.getNode(ISD::ABS, DL, Op.getValueType(), Op);
3446 if (IsNegative)
3447 Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
3448 DAG.getConstant(0, DL, Op.getValueType()), Op);
3449 return Op;
3450}
3451
3452SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
3453 SelectionDAG &DAG) const {
3454 SDValue CmpOp0 = Op.getOperand(0);
3455 SDValue CmpOp1 = Op.getOperand(1);
3456 SDValue TrueOp = Op.getOperand(2);
3457 SDValue FalseOp = Op.getOperand(3);
3458 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3459 SDLoc DL(Op);
3460
3461 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
3462
3463 // Check for absolute and negative-absolute selections, including those
3464 // where the comparison value is sign-extended (for LPGFR and LNGFR).
3465 // This check supplements the one in DAGCombiner.
3466 if (C.Opcode == SystemZISD::ICMP && C.CCMask != SystemZ::CCMASK_CMP_EQ &&
3467 C.CCMask != SystemZ::CCMASK_CMP_NE &&
3468 C.Op1.getOpcode() == ISD::Constant &&
3469 cast<ConstantSDNode>(C.Op1)->getValueSizeInBits(0) <= 64 &&
3470 C.Op1->getAsZExtVal() == 0) {
3471 if (isAbsolute(C.Op0, TrueOp, FalseOp))
3472 return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
3473 if (isAbsolute(C.Op0, FalseOp, TrueOp))
3474 return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
3475 }
3476
3477 SDValue CCReg = emitCmp(DAG, DL, C);
3478 SDValue Ops[] = {TrueOp, FalseOp,
3479 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
3480 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), CCReg};
3481
3482 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, Op.getValueType(), Ops);
3483}
3484
3485SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
3486 SelectionDAG &DAG) const {
3487 SDLoc DL(Node);
3488 const GlobalValue *GV = Node->getGlobal();
3489 int64_t Offset = Node->getOffset();
3490 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3492
3494 if (Subtarget.isPC32DBLSymbol(GV, CM)) {
3495 if (isInt<32>(Offset)) {
3496 // Assign anchors at 1<<12 byte boundaries.
3497 uint64_t Anchor = Offset & ~uint64_t(0xfff);
3498 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
3499 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3500
3501 // The offset can be folded into the address if it is aligned to a
3502 // halfword.
3503 Offset -= Anchor;
3504 if (Offset != 0 && (Offset & 1) == 0) {
3505 SDValue Full =
3506 DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
3507 Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
3508 Offset = 0;
3509 }
3510 } else {
3511 // Conservatively load a constant offset greater than 32 bits into a
3512 // register below.
3513 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT);
3514 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3515 }
3516 } else if (Subtarget.isTargetELF()) {
3517 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
3518 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3519 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3521 } else if (Subtarget.isTargetzOS()) {
3522 Result = getADAEntry(DAG, GV, DL, PtrVT);
3523 } else
3524 llvm_unreachable("Unexpected Subtarget");
3525
3526 // If there was a non-zero offset that we didn't fold, create an explicit
3527 // addition for it.
3528 if (Offset != 0)
3529 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
3530 DAG.getConstant(Offset, DL, PtrVT));
3531
3532 return Result;
3533}
3534
3535SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
3536 SelectionDAG &DAG,
3537 unsigned Opcode,
3538 SDValue GOTOffset) const {
3539 SDLoc DL(Node);
3540 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3541 SDValue Chain = DAG.getEntryNode();
3542 SDValue Glue;
3543
3546 report_fatal_error("In GHC calling convention TLS is not supported");
3547
3548 // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
3549 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
3550 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
3551 Glue = Chain.getValue(1);
3552 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
3553 Glue = Chain.getValue(1);
3554
3555 // The first call operand is the chain and the second is the TLS symbol.
3557 Ops.push_back(Chain);
3558 Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
3559 Node->getValueType(0),
3560 0, 0));
3561
3562 // Add argument registers to the end of the list so that they are
3563 // known live into the call.
3564 Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
3565 Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
3566
3567 // Add a register mask operand representing the call-preserved registers.
3568 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3569 const uint32_t *Mask =
3570 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3571 assert(Mask && "Missing call preserved mask for calling convention");
3572 Ops.push_back(DAG.getRegisterMask(Mask));
3573
3574 // Glue the call to the argument copies.
3575 Ops.push_back(Glue);
3576
3577 // Emit the call.
3578 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3579 Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
3580 Glue = Chain.getValue(1);
3581
3582 // Copy the return value from %r2.
3583 return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
3584}
3585
3586SDValue SystemZTargetLowering::lowerThreadPointer(const SDLoc &DL,
3587 SelectionDAG &DAG) const {
3588 SDValue Chain = DAG.getEntryNode();
3589 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3590
3591 // The high part of the thread pointer is in access register 0.
3592 SDValue TPHi = DAG.getCopyFromReg(Chain, DL, SystemZ::A0, MVT::i32);
3593 TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
3594
3595 // The low part of the thread pointer is in access register 1.
3596 SDValue TPLo = DAG.getCopyFromReg(Chain, DL, SystemZ::A1, MVT::i32);
3597 TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
3598
3599 // Merge them into a single 64-bit address.
3600 SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
3601 DAG.getConstant(32, DL, PtrVT));
3602 return DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
3603}
3604
3605SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
3606 SelectionDAG &DAG) const {
3607 if (DAG.getTarget().useEmulatedTLS())
3608 return LowerToTLSEmulatedModel(Node, DAG);
3609 SDLoc DL(Node);
3610 const GlobalValue *GV = Node->getGlobal();
3611 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3612 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
3613
3616 report_fatal_error("In GHC calling convention TLS is not supported");
3617
3618 SDValue TP = lowerThreadPointer(DL, DAG);
3619
3620 // Get the offset of GA from the thread pointer, based on the TLS model.
3622 switch (model) {
3624 // Load the GOT offset of the tls_index (module ID / per-symbol offset).
3627
3628 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
3629 Offset = DAG.getLoad(
3630 PtrVT, DL, DAG.getEntryNode(), Offset,
3632
3633 // Call __tls_get_offset to retrieve the offset.
3634 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
3635 break;
3636 }
3637
3639 // Load the GOT offset of the module ID.
3642
3643 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
3644 Offset = DAG.getLoad(
3645 PtrVT, DL, DAG.getEntryNode(), Offset,
3647
3648 // Call __tls_get_offset to retrieve the module base offset.
3649 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
3650
3651 // Note: The SystemZLDCleanupPass will remove redundant computations
3652 // of the module base offset. Count total number of local-dynamic
3653 // accesses to trigger execution of that pass.
3657
3658 // Add the per-symbol offset.
3660
3661 SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, Align(8));
3662 DTPOffset = DAG.getLoad(
3663 PtrVT, DL, DAG.getEntryNode(), DTPOffset,
3665
3666 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
3667 break;
3668 }
3669
3670 case TLSModel::InitialExec: {
3671 // Load the offset from the GOT.
3672 Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3675 Offset =
3676 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset,
3678 break;
3679 }
3680
3681 case TLSModel::LocalExec: {
3682 // Force the offset into the constant pool and load it from there.
3685
3686 Offset = DAG.getConstantPool(CPV, PtrVT, Align(8));
3687 Offset = DAG.getLoad(
3688 PtrVT, DL, DAG.getEntryNode(), Offset,
3690 break;
3691 }
3692 }
3693
3694 // Add the base and offset together.
3695 return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
3696}
3697
3698SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
3699 SelectionDAG &DAG) const {
3700 SDLoc DL(Node);
3701 const BlockAddress *BA = Node->getBlockAddress();
3702 int64_t Offset = Node->getOffset();
3703 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3704
3705 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
3706 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3707 return Result;
3708}
3709
3710SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
3711 SelectionDAG &DAG) const {
3712 SDLoc DL(JT);
3713 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3714 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3715
3716 // Use LARL to load the address of the table.
3717 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3718}
3719
3720SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
3721 SelectionDAG &DAG) const {
3722 SDLoc DL(CP);
3723 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3724
3726 if (CP->isMachineConstantPoolEntry())
3727 Result =
3728 DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign());
3729 else
3730 Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign(),
3731 CP->getOffset());
3732
3733 // Use LARL to load the address of the constant pool entry.
3734 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3735}
3736
3737SDValue SystemZTargetLowering::lowerFRAMEADDR(SDValue Op,
3738 SelectionDAG &DAG) const {
3739 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>();
3741 MachineFrameInfo &MFI = MF.getFrameInfo();
3742 MFI.setFrameAddressIsTaken(true);
3743
3744 SDLoc DL(Op);
3745 unsigned Depth = Op.getConstantOperandVal(0);
3746 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3747
3748 // By definition, the frame address is the address of the back chain. (In
3749 // the case of packed stack without backchain, return the address where the
3750 // backchain would have been stored. This will either be an unused space or
3751 // contain a saved register).
3752 int BackChainIdx = TFL->getOrCreateFramePointerSaveIndex(MF);
3753 SDValue BackChain = DAG.getFrameIndex(BackChainIdx, PtrVT);
3754
3755 if (Depth > 0) {
3756 // FIXME The frontend should detect this case.
3757 if (!MF.getSubtarget<SystemZSubtarget>().hasBackChain())
3758 report_fatal_error("Unsupported stack frame traversal count");
3759
3760 SDValue Offset = DAG.getConstant(TFL->getBackchainOffset(MF), DL, PtrVT);
3761 while (Depth--) {
3762 BackChain = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), BackChain,
3764 BackChain = DAG.getNode(ISD::ADD, DL, PtrVT, BackChain, Offset);
3765 }
3766 }
3767
3768 return BackChain;
3769}
3770
3771SDValue SystemZTargetLowering::lowerRETURNADDR(SDValue Op,
3772 SelectionDAG &DAG) const {
3774 MachineFrameInfo &MFI = MF.getFrameInfo();
3775 MFI.setReturnAddressIsTaken(true);
3776
3778 return SDValue();
3779
3780 SDLoc DL(Op);
3781 unsigned Depth = Op.getConstantOperandVal(0);
3782 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3783
3784 if (Depth > 0) {
3785 // FIXME The frontend should detect this case.
3786 if (!MF.getSubtarget<SystemZSubtarget>().hasBackChain())
3787 report_fatal_error("Unsupported stack frame traversal count");
3788
3789 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3790 auto *TFL = Subtarget.getFrameLowering<SystemZELFFrameLowering>();
3791 int Offset = (TFL->usePackedStack(MF) ? -2 : 14) *
3793 SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, FrameAddr,
3794 DAG.getConstant(Offset, DL, PtrVT));
3795 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr,
3797 }
3798
3799 // Return R14D, which has the return address. Mark it an implicit live-in.
3800 Register LinkReg = MF.addLiveIn(SystemZ::R14D, &SystemZ::GR64BitRegClass);
3801 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, LinkReg, PtrVT);
3802}
3803
3804SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
3805 SelectionDAG &DAG) const {
3806 SDLoc DL(Op);
3807 SDValue In = Op.getOperand(0);
3808 EVT InVT = In.getValueType();
3809 EVT ResVT = Op.getValueType();
3810
3811 // Convert loads directly. This is normally done by DAGCombiner,
3812 // but we need this case for bitcasts that are created during lowering
3813 // and which are then lowered themselves.
3814 if (auto *LoadN = dyn_cast<LoadSDNode>(In))
3815 if (ISD::isNormalLoad(LoadN)) {
3816 SDValue NewLoad = DAG.getLoad(ResVT, DL, LoadN->getChain(),
3817 LoadN->getBasePtr(), LoadN->getMemOperand());
3818 // Update the chain uses.
3819 DAG.ReplaceAllUsesOfValueWith(SDValue(LoadN, 1), NewLoad.getValue(1));
3820 return NewLoad;
3821 }
3822
3823 if (InVT == MVT::i32 && ResVT == MVT::f32) {
3824 SDValue In64;
3825 if (Subtarget.hasHighWord()) {
3826 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
3827 MVT::i64);
3828 In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
3829 MVT::i64, SDValue(U64, 0), In);
3830 } else {
3831 In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
3832 In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
3833 DAG.getConstant(32, DL, MVT::i64));
3834 }
3835 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
3836 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32,
3837 DL, MVT::f32, Out64);
3838 }
3839 if (InVT == MVT::f32 && ResVT == MVT::i32) {
3840 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
3841 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
3842 MVT::f64, SDValue(U64, 0), In);
3843 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
3844 if (Subtarget.hasHighWord())
3845 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
3846 MVT::i32, Out64);
3847 SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
3848 DAG.getConstant(32, DL, MVT::i64));
3849 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
3850 }
3851 llvm_unreachable("Unexpected bitcast combination");
3852}
3853
3854SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
3855 SelectionDAG &DAG) const {
3856
3857 if (Subtarget.isTargetXPLINK64())
3858 return lowerVASTART_XPLINK(Op, DAG);
3859 else
3860 return lowerVASTART_ELF(Op, DAG);
3861}
3862
3863SDValue SystemZTargetLowering::lowerVASTART_XPLINK(SDValue Op,
3864 SelectionDAG &DAG) const {
3866 SystemZMachineFunctionInfo *FuncInfo =
3868
3869 SDLoc DL(Op);
3870
3871 // vastart just stores the address of the VarArgsFrameIndex slot into the
3872 // memory location argument.
3873 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3874 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3875 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3876 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3877 MachinePointerInfo(SV));
3878}
3879
3880SDValue SystemZTargetLowering::lowerVASTART_ELF(SDValue Op,
3881 SelectionDAG &DAG) const {
3883 SystemZMachineFunctionInfo *FuncInfo =
3885 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3886
3887 SDValue Chain = Op.getOperand(0);
3888 SDValue Addr = Op.getOperand(1);
3889 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3890 SDLoc DL(Op);
3891
3892 // The initial values of each field.
3893 const unsigned NumFields = 4;
3894 SDValue Fields[NumFields] = {
3895 DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
3896 DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
3897 DAG.