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