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