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