LLVM  6.0.0svn
SystemZISelLowering.cpp
Go to the documentation of this file.
1 //===-- SystemZISelLowering.cpp - SystemZ DAG lowering implementation -----===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the SystemZTargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SystemZISelLowering.h"
15 #include "SystemZCallingConv.h"
18 #include "SystemZTargetMachine.h"
23 #include "llvm/IR/Intrinsics.h"
25 #include "llvm/Support/KnownBits.h"
26 #include <cctype>
27 
28 using namespace llvm;
29 
30 #define DEBUG_TYPE "systemz-lower"
31 
32 namespace {
33 // Represents a sequence for extracting a 0/1 value from an IPM result:
34 // (((X ^ XORValue) + AddValue) >> Bit)
35 struct IPMConversion {
36  IPMConversion(unsigned xorValue, int64_t addValue, unsigned bit)
37  : XORValue(xorValue), AddValue(addValue), Bit(bit) {}
38 
39  int64_t XORValue;
40  int64_t AddValue;
41  unsigned Bit;
42 };
43 
44 // Represents information about a comparison.
45 struct Comparison {
46  Comparison(SDValue Op0In, SDValue Op1In)
47  : Op0(Op0In), Op1(Op1In), Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
48 
49  // The operands to the comparison.
50  SDValue Op0, Op1;
51 
52  // The opcode that should be used to compare Op0 and Op1.
53  unsigned Opcode;
54 
55  // A SystemZICMP value. Only used for integer comparisons.
56  unsigned ICmpType;
57 
58  // The mask of CC values that Opcode can produce.
59  unsigned CCValid;
60 
61  // The mask of CC values for which the original condition is true.
62  unsigned CCMask;
63 };
64 } // end anonymous namespace
65 
66 // Classify VT as either 32 or 64 bit.
67 static bool is32Bit(EVT VT) {
68  switch (VT.getSimpleVT().SimpleTy) {
69  case MVT::i32:
70  return true;
71  case MVT::i64:
72  return false;
73  default:
74  llvm_unreachable("Unsupported type");
75  }
76 }
77 
78 // Return a version of MachineOperand that can be safely used before the
79 // final use.
81  if (Op.isReg())
82  Op.setIsKill(false);
83  return Op;
84 }
85 
87  const SystemZSubtarget &STI)
88  : TargetLowering(TM), Subtarget(STI) {
89  MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
90 
91  // Set up the register classes.
92  if (Subtarget.hasHighWord())
93  addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
94  else
95  addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
96  addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass);
97  if (Subtarget.hasVector()) {
98  addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass);
99  addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass);
100  } else {
101  addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass);
102  addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass);
103  }
104  if (Subtarget.hasVectorEnhancements1())
105  addRegisterClass(MVT::f128, &SystemZ::VR128BitRegClass);
106  else
107  addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
108 
109  if (Subtarget.hasVector()) {
110  addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass);
111  addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass);
112  addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass);
113  addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass);
114  addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass);
115  addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass);
116  }
117 
118  // Compute derived properties from the register classes
120 
121  // Set up special registers.
123 
124  // TODO: It may be better to default to latency-oriented scheduling, however
125  // LLVM's current latency-oriented scheduler can't handle physreg definitions
126  // such as SystemZ has with CC, so set this to the register-pressure
127  // scheduler, because it can.
129 
132 
133  // Instructions are strings of 2-byte aligned 2-byte values.
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.
144 
145  // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
147 
148  // Lower SELECT_CC and BR_CC into separate comparisons and branches.
151  }
152  }
153 
154  // Expand jump table branches as address arithmetic followed by an
155  // indirect jump.
157 
158  // Expand BRCOND into a BR_CC (see above).
160 
161  // Handle integer types.
162  for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
164  ++I) {
165  MVT VT = MVT::SimpleValueType(I);
166  if (isTypeLegal(VT)) {
167  // Expand individual DIV and REMs into DIVREMs.
174 
175  // Lower ATOMIC_LOAD and ATOMIC_STORE into normal volatile loads and
176  // stores, putting a serialization instruction after the stores.
179 
180  // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
181  // available, or if the operand is constant.
183 
184  // Use POPCNT on z196 and above.
185  if (Subtarget.hasPopulationCount())
187  else
189 
190  // No special instructions for these.
193 
194  // Use *MUL_LOHI where possible instead of MULH*.
199 
200  // Only z196 and above have native support for conversions to unsigned.
201  // On z10, promoting to i64 doesn't generate an inexact condition for
202  // values that are outside the i32 range but in the i64 range, so use
203  // the default expansion.
204  if (!Subtarget.hasFPExtension())
206  }
207  }
208 
209  // Type legalization will convert 8- and 16-bit atomic operations into
210  // forms that operate on i32s (but still keeping the original memory VT).
211  // Lower them into full i32 operations.
224 
226 
227  // Traps are legal, as we will convert them to "j .+2".
229 
230  // z10 has instructions for signed but not unsigned FP conversion.
231  // Handle unsigned 32-bit types as signed 64-bit types.
232  if (!Subtarget.hasFPExtension()) {
235  }
236 
237  // We have native support for a 64-bit CTLZ, via FLOGR.
240 
241  // Give LowerOperation the chance to replace 64-bit ORs with subregs.
243 
244  // FIXME: Can we support these natively?
248 
249  // We have native instructions for i8, i16 and i32 extensions, but not i1.
251  for (MVT VT : MVT::integer_valuetypes()) {
255  }
256 
257  // Handle the various types of symbolic address.
263 
264  // We need to handle dynamic allocations specially because of the
265  // 160-byte area at the bottom of the stack.
268 
269  // Use custom expanders so that we can force the function to use
270  // a frame pointer.
273 
274  // Handle prefetches with PFD or PFDRL.
276 
277  for (MVT VT : MVT::vector_valuetypes()) {
278  // Assume by default that all vector operations need to be expanded.
279  for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
280  if (getOperationAction(Opcode, VT) == Legal)
281  setOperationAction(Opcode, VT, Expand);
282 
283  // Likewise all truncating stores and extending loads.
284  for (MVT InnerVT : MVT::vector_valuetypes()) {
285  setTruncStoreAction(VT, InnerVT, Expand);
286  setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
287  setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
288  setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
289  }
290 
291  if (isTypeLegal(VT)) {
292  // These operations are legal for anything that can be stored in a
293  // vector register, even if there is no native support for the format
294  // as such. In particular, we can do these for v4f32 even though there
295  // are no specific instructions for that format.
301 
302  // Likewise, except that we need to replace the nodes with something
303  // more specific.
306  }
307  }
308 
309  // Handle integer vector types.
310  for (MVT VT : MVT::integer_vector_valuetypes()) {
311  if (isTypeLegal(VT)) {
312  // These operations have direct equivalents.
317  if (VT != MVT::v2i64)
322  if (Subtarget.hasVectorEnhancements1())
324  else
328 
329  // Convert a GPR scalar to a vector by inserting it into element 0.
331 
332  // Use a series of unpacks for extensions.
335 
336  // Detect shifts by a scalar amount and convert them into
337  // V*_BY_SCALAR.
341 
342  // At present ROTL isn't matched by DAGCombiner. ROTR should be
343  // converted into ROTL.
346 
347  // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
348  // and inverting the result as necessary.
350  }
351  }
352 
353  if (Subtarget.hasVector()) {
354  // There should be no need to check for float types other than v2f64
355  // since <2 x f32> isn't a legal type.
364  }
365 
366  // Handle floating-point types.
367  for (unsigned I = MVT::FIRST_FP_VALUETYPE;
369  ++I) {
370  MVT VT = MVT::SimpleValueType(I);
371  if (isTypeLegal(VT)) {
372  // We can use FI for FRINT.
374 
375  // We can use the extended form of FI for other rounding operations.
376  if (Subtarget.hasFPExtension()) {
382  }
383 
384  // No special instructions for these.
390  }
391  }
392 
393  // Handle floating-point vector types.
394  if (Subtarget.hasVector()) {
395  // Scalar-to-vector conversion is just a subreg.
398 
399  // Some insertions and extractions can be done directly but others
400  // need to go via integers.
405 
406  // These operations have direct equivalents.
421  }
422 
423  // The vector enhancements facility 1 has instructions for these.
424  if (Subtarget.hasVectorEnhancements1()) {
439 
444 
449 
454 
459 
464  }
465 
466  // We have fused multiply-addition for f32 and f64 but not f128.
469  if (Subtarget.hasVectorEnhancements1())
471  else
473 
474  // We don't have a copysign instruction on vector registers.
475  if (Subtarget.hasVectorEnhancements1())
477 
478  // Needed so that we don't try to implement f128 constant loads using
479  // a load-and-extend of a f80 constant (in cases where the constant
480  // would fit in an f80).
481  for (MVT VT : MVT::fp_valuetypes())
483 
484  // We don't have extending load instruction on vector registers.
485  if (Subtarget.hasVectorEnhancements1()) {
488  }
489 
490  // Floating-point truncation and stores need to be done separately.
494 
495  // We have 64-bit FPR<->GPR moves, but need special handling for
496  // 32-bit forms.
497  if (!Subtarget.hasVector()) {
500  }
501 
502  // VASTART and VACOPY need to deal with the SystemZ-specific varargs
503  // structure, but VAEND is a no-op.
507 
508  // Codes for which we want to perform some z-specific combinations.
518 
519  // Handle intrinsics.
522 
523  // We want to use MVC in preference to even a single load/store pair.
524  MaxStoresPerMemcpy = 0;
526 
527  // The main memset sequence is a byte store followed by an MVC.
528  // Two STC or MV..I stores win over that, but the kind of fused stores
529  // generated by target-independent code don't when the byte value is
530  // variable. E.g. "STC <reg>;MHI <reg>,257;STH <reg>" is not better
531  // than "STC;MVC". Handle the choice in target-specific code instead.
532  MaxStoresPerMemset = 0;
534 }
535 
537  LLVMContext &, EVT VT) const {
538  if (!VT.isVector())
539  return MVT::i32;
541 }
542 
544  VT = VT.getScalarType();
545 
546  if (!VT.isSimple())
547  return false;
548 
549  switch (VT.getSimpleVT().SimpleTy) {
550  case MVT::f32:
551  case MVT::f64:
552  return true;
553  case MVT::f128:
554  return Subtarget.hasVectorEnhancements1();
555  default:
556  break;
557  }
558 
559  return false;
560 }
561 
562 bool SystemZTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
563  // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
564  return Imm.isZero() || Imm.isNegZero();
565 }
566 
568  // We can use CGFI or CLGFI.
569  return isInt<32>(Imm) || isUInt<32>(Imm);
570 }
571 
573  // We can use ALGFI or SLGFI.
574  return isUInt<32>(Imm) || isUInt<32>(-Imm);
575 }
576 
578  unsigned,
579  unsigned,
580  bool *Fast) const {
581  // Unaligned accesses should never be slower than the expanded version.
582  // We check specifically for aligned accesses in the few cases where
583  // they are required.
584  if (Fast)
585  *Fast = true;
586  return true;
587 }
588 
590  const AddrMode &AM, Type *Ty,
591  unsigned AS) const {
592  // Punt on globals for now, although they can be used in limited
593  // RELATIVE LONG cases.
594  if (AM.BaseGV)
595  return false;
596 
597  // Require a 20-bit signed offset.
598  if (!isInt<20>(AM.BaseOffs))
599  return false;
600 
601  // Indexing is OK but no scale factor can be applied.
602  return AM.Scale == 0 || AM.Scale == 1;
603 }
604 
606  int64_t Offset) const {
607  // This only applies to z13.
608  if (!Subtarget.hasVector())
609  return true;
610 
611  // * Use LDE instead of LE/LEY to avoid partial register
612  // dependencies (LDE only supports small offsets).
613  // * Utilize the vector registers to hold floating point
614  // values (vector load / store instructions only support small
615  // offsets).
616 
617  assert (isa<LoadInst>(I) || isa<StoreInst>(I));
618  Type *MemAccessTy = (isa<LoadInst>(I) ? I->getType() :
619  I->getOperand(0)->getType());
620  bool IsFPAccess = MemAccessTy->isFloatingPointTy();
621  bool IsVectorAccess = MemAccessTy->isVectorTy();
622 
623  // A store of an extracted vector element will be combined into a VSTE type
624  // instruction.
625  if (!IsVectorAccess && isa<StoreInst>(I)) {
626  Value *DataOp = I->getOperand(0);
627  if (isa<ExtractElementInst>(DataOp))
628  IsVectorAccess = true;
629  }
630 
631  // A load which gets inserted into a vector element will be combined into a
632  // VLE type instruction.
633  if (!IsVectorAccess && isa<LoadInst>(I) && I->hasOneUse()) {
634  User *LoadUser = *I->user_begin();
635  if (isa<InsertElementInst>(LoadUser))
636  IsVectorAccess = true;
637  }
638 
639  if (!isUInt<12>(Offset) && (IsFPAccess || IsVectorAccess))
640  return false;
641 
642  return true;
643 }
644 
646  if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
647  return false;
648  unsigned FromBits = FromType->getPrimitiveSizeInBits();
649  unsigned ToBits = ToType->getPrimitiveSizeInBits();
650  return FromBits > ToBits;
651 }
652 
654  if (!FromVT.isInteger() || !ToVT.isInteger())
655  return false;
656  unsigned FromBits = FromVT.getSizeInBits();
657  unsigned ToBits = ToVT.getSizeInBits();
658  return FromBits > ToBits;
659 }
660 
661 //===----------------------------------------------------------------------===//
662 // Inline asm support
663 //===----------------------------------------------------------------------===//
664 
667  if (Constraint.size() == 1) {
668  switch (Constraint[0]) {
669  case 'a': // Address register
670  case 'd': // Data register (equivalent to 'r')
671  case 'f': // Floating-point register
672  case 'h': // High-part register
673  case 'r': // General-purpose register
674  return C_RegisterClass;
675 
676  case 'Q': // Memory with base and unsigned 12-bit displacement
677  case 'R': // Likewise, plus an index
678  case 'S': // Memory with base and signed 20-bit displacement
679  case 'T': // Likewise, plus an index
680  case 'm': // Equivalent to 'T'.
681  return C_Memory;
682 
683  case 'I': // Unsigned 8-bit constant
684  case 'J': // Unsigned 12-bit constant
685  case 'K': // Signed 16-bit constant
686  case 'L': // Signed 20-bit displacement (on all targets we support)
687  case 'M': // 0x7fffffff
688  return C_Other;
689 
690  default:
691  break;
692  }
693  }
694  return TargetLowering::getConstraintType(Constraint);
695 }
696 
699  const char *constraint) const {
700  ConstraintWeight weight = CW_Invalid;
701  Value *CallOperandVal = info.CallOperandVal;
702  // If we don't have a value, we can't do a match,
703  // but allow it at the lowest weight.
704  if (!CallOperandVal)
705  return CW_Default;
706  Type *type = CallOperandVal->getType();
707  // Look at the constraint type.
708  switch (*constraint) {
709  default:
710  weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
711  break;
712 
713  case 'a': // Address register
714  case 'd': // Data register (equivalent to 'r')
715  case 'h': // High-part register
716  case 'r': // General-purpose register
717  if (CallOperandVal->getType()->isIntegerTy())
718  weight = CW_Register;
719  break;
720 
721  case 'f': // Floating-point register
722  if (type->isFloatingPointTy())
723  weight = CW_Register;
724  break;
725 
726  case 'I': // Unsigned 8-bit constant
727  if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
728  if (isUInt<8>(C->getZExtValue()))
729  weight = CW_Constant;
730  break;
731 
732  case 'J': // Unsigned 12-bit constant
733  if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
734  if (isUInt<12>(C->getZExtValue()))
735  weight = CW_Constant;
736  break;
737 
738  case 'K': // Signed 16-bit constant
739  if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
740  if (isInt<16>(C->getSExtValue()))
741  weight = CW_Constant;
742  break;
743 
744  case 'L': // Signed 20-bit displacement (on all targets we support)
745  if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
746  if (isInt<20>(C->getSExtValue()))
747  weight = CW_Constant;
748  break;
749 
750  case 'M': // 0x7fffffff
751  if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
752  if (C->getZExtValue() == 0x7fffffff)
753  weight = CW_Constant;
754  break;
755  }
756  return weight;
757 }
758 
759 // Parse a "{tNNN}" register constraint for which the register type "t"
760 // has already been verified. MC is the class associated with "t" and
761 // Map maps 0-based register numbers to LLVM register numbers.
762 static std::pair<unsigned, const TargetRegisterClass *>
764  const unsigned *Map) {
765  assert(*(Constraint.end()-1) == '}' && "Missing '}'");
766  if (isdigit(Constraint[2])) {
767  unsigned Index;
768  bool Failed =
769  Constraint.slice(2, Constraint.size() - 1).getAsInteger(10, Index);
770  if (!Failed && Index < 16 && Map[Index])
771  return std::make_pair(Map[Index], RC);
772  }
773  return std::make_pair(0U, nullptr);
774 }
775 
776 std::pair<unsigned, const TargetRegisterClass *>
778  const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
779  if (Constraint.size() == 1) {
780  // GCC Constraint Letters
781  switch (Constraint[0]) {
782  default: break;
783  case 'd': // Data register (equivalent to 'r')
784  case 'r': // General-purpose register
785  if (VT == MVT::i64)
786  return std::make_pair(0U, &SystemZ::GR64BitRegClass);
787  else if (VT == MVT::i128)
788  return std::make_pair(0U, &SystemZ::GR128BitRegClass);
789  return std::make_pair(0U, &SystemZ::GR32BitRegClass);
790 
791  case 'a': // Address register
792  if (VT == MVT::i64)
793  return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
794  else if (VT == MVT::i128)
795  return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
796  return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
797 
798  case 'h': // High-part register (an LLVM extension)
799  return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
800 
801  case 'f': // Floating-point register
802  if (VT == MVT::f64)
803  return std::make_pair(0U, &SystemZ::FP64BitRegClass);
804  else if (VT == MVT::f128)
805  return std::make_pair(0U, &SystemZ::FP128BitRegClass);
806  return std::make_pair(0U, &SystemZ::FP32BitRegClass);
807  }
808  }
809  if (Constraint.size() > 0 && Constraint[0] == '{') {
810  // We need to override the default register parsing for GPRs and FPRs
811  // because the interpretation depends on VT. The internal names of
812  // the registers are also different from the external names
813  // (F0D and F0S instead of F0, etc.).
814  if (Constraint[1] == 'r') {
815  if (VT == MVT::i32)
816  return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
818  if (VT == MVT::i128)
819  return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
821  return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
823  }
824  if (Constraint[1] == 'f') {
825  if (VT == MVT::f32)
826  return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
828  if (VT == MVT::f128)
829  return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
831  return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
833  }
834  }
835  return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
836 }
837 
839 LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
840  std::vector<SDValue> &Ops,
841  SelectionDAG &DAG) const {
842  // Only support length 1 constraints for now.
843  if (Constraint.length() == 1) {
844  switch (Constraint[0]) {
845  case 'I': // Unsigned 8-bit constant
846  if (auto *C = dyn_cast<ConstantSDNode>(Op))
847  if (isUInt<8>(C->getZExtValue()))
848  Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
849  Op.getValueType()));
850  return;
851 
852  case 'J': // Unsigned 12-bit constant
853  if (auto *C = dyn_cast<ConstantSDNode>(Op))
854  if (isUInt<12>(C->getZExtValue()))
855  Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
856  Op.getValueType()));
857  return;
858 
859  case 'K': // Signed 16-bit constant
860  if (auto *C = dyn_cast<ConstantSDNode>(Op))
861  if (isInt<16>(C->getSExtValue()))
862  Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
863  Op.getValueType()));
864  return;
865 
866  case 'L': // Signed 20-bit displacement (on all targets we support)
867  if (auto *C = dyn_cast<ConstantSDNode>(Op))
868  if (isInt<20>(C->getSExtValue()))
869  Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
870  Op.getValueType()));
871  return;
872 
873  case 'M': // 0x7fffffff
874  if (auto *C = dyn_cast<ConstantSDNode>(Op))
875  if (C->getZExtValue() == 0x7fffffff)
876  Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
877  Op.getValueType()));
878  return;
879  }
880  }
881  TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
882 }
883 
884 //===----------------------------------------------------------------------===//
885 // Calling conventions
886 //===----------------------------------------------------------------------===//
887 
888 #include "SystemZGenCallingConv.inc"
889 
891  Type *ToType) const {
892  return isTruncateFree(FromType, ToType);
893 }
894 
896  return CI->isTailCall();
897 }
898 
899 // We do not yet support 128-bit single-element vector types. If the user
900 // attempts to use such types as function argument or return type, prefer
901 // to error out instead of emitting code violating the ABI.
902 static void VerifyVectorType(MVT VT, EVT ArgVT) {
903  if (ArgVT.isVector() && !VT.isVector())
904  report_fatal_error("Unsupported vector argument or return type");
905 }
906 
908  for (unsigned i = 0; i < Ins.size(); ++i)
909  VerifyVectorType(Ins[i].VT, Ins[i].ArgVT);
910 }
911 
913  for (unsigned i = 0; i < Outs.size(); ++i)
914  VerifyVectorType(Outs[i].VT, Outs[i].ArgVT);
915 }
916 
917 // Value is a value that has been passed to us in the location described by VA
918 // (and so has type VA.getLocVT()). Convert Value to VA.getValVT(), chaining
919 // any loads onto Chain.
921  CCValAssign &VA, SDValue Chain,
922  SDValue Value) {
923  // If the argument has been promoted from a smaller type, insert an
924  // assertion to capture this.
925  if (VA.getLocInfo() == CCValAssign::SExt)
926  Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value,
927  DAG.getValueType(VA.getValVT()));
928  else if (VA.getLocInfo() == CCValAssign::ZExt)
929  Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value,
930  DAG.getValueType(VA.getValVT()));
931 
932  if (VA.isExtInLoc())
933  Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
934  else if (VA.getLocInfo() == CCValAssign::BCvt) {
935  // If this is a short vector argument loaded from the stack,
936  // extend from i64 to full vector size and then bitcast.
937  assert(VA.getLocVT() == MVT::i64);
938  assert(VA.getValVT().isVector());
939  Value = DAG.getBuildVector(MVT::v2i64, DL, {Value, DAG.getUNDEF(MVT::i64)});
940  Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
941  } else
942  assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
943  return Value;
944 }
945 
946 // Value is a value of type VA.getValVT() that we need to copy into
947 // the location described by VA. Return a copy of Value converted to
948 // VA.getValVT(). The caller is responsible for handling indirect values.
950  CCValAssign &VA, SDValue Value) {
951  switch (VA.getLocInfo()) {
952  case CCValAssign::SExt:
953  return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
954  case CCValAssign::ZExt:
955  return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
956  case CCValAssign::AExt:
957  return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
958  case CCValAssign::BCvt:
959  // If this is a short vector argument to be stored to the stack,
960  // bitcast to v2i64 and then extract first element.
961  assert(VA.getLocVT() == MVT::i64);
962  assert(VA.getValVT().isVector());
963  Value = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Value);
964  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
965  DAG.getConstant(0, DL, MVT::i32));
966  case CCValAssign::Full:
967  return Value;
968  default:
969  llvm_unreachable("Unhandled getLocInfo()");
970  }
971 }
972 
974  SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
975  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
976  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
978  MachineFrameInfo &MFI = MF.getFrameInfo();
980  SystemZMachineFunctionInfo *FuncInfo =
982  auto *TFL =
983  static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering());
984  EVT PtrVT = getPointerTy(DAG.getDataLayout());
985 
986  // Detect unsupported vector argument types.
987  if (Subtarget.hasVector())
988  VerifyVectorTypes(Ins);
989 
990  // Assign locations to all of the incoming arguments.
992  SystemZCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
993  CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
994 
995  unsigned NumFixedGPRs = 0;
996  unsigned NumFixedFPRs = 0;
997  for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
998  SDValue ArgValue;
999  CCValAssign &VA = ArgLocs[I];
1000  EVT LocVT = VA.getLocVT();
1001  if (VA.isRegLoc()) {
1002  // Arguments passed in registers
1003  const TargetRegisterClass *RC;
1004  switch (LocVT.getSimpleVT().SimpleTy) {
1005  default:
1006  // Integers smaller than i64 should be promoted to i64.
1007  llvm_unreachable("Unexpected argument type");
1008  case MVT::i32:
1009  NumFixedGPRs += 1;
1010  RC = &SystemZ::GR32BitRegClass;
1011  break;
1012  case MVT::i64:
1013  NumFixedGPRs += 1;
1014  RC = &SystemZ::GR64BitRegClass;
1015  break;
1016  case MVT::f32:
1017  NumFixedFPRs += 1;
1018  RC = &SystemZ::FP32BitRegClass;
1019  break;
1020  case MVT::f64:
1021  NumFixedFPRs += 1;
1022  RC = &SystemZ::FP64BitRegClass;
1023  break;
1024  case MVT::v16i8:
1025  case MVT::v8i16:
1026  case MVT::v4i32:
1027  case MVT::v2i64:
1028  case MVT::v4f32:
1029  case MVT::v2f64:
1030  RC = &SystemZ::VR128BitRegClass;
1031  break;
1032  }
1033 
1034  unsigned VReg = MRI.createVirtualRegister(RC);
1035  MRI.addLiveIn(VA.getLocReg(), VReg);
1036  ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
1037  } else {
1038  assert(VA.isMemLoc() && "Argument not register or memory");
1039 
1040  // Create the frame index object for this incoming parameter.
1041  int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
1042  VA.getLocMemOffset(), true);
1043 
1044  // Create the SelectionDAG nodes corresponding to a load
1045  // from this parameter. Unpromoted ints and floats are
1046  // passed as right-justified 8-byte values.
1047  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1048  if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1049  FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
1050  DAG.getIntPtrConstant(4, DL));
1051  ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
1053  }
1054 
1055  // Convert the value of the argument register into the value that's
1056  // being passed.
1057  if (VA.getLocInfo() == CCValAssign::Indirect) {
1058  InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
1059  MachinePointerInfo()));
1060  // If the original argument was split (e.g. i128), we need
1061  // to load all parts of it here (using the same address).
1062  unsigned ArgIndex = Ins[I].OrigArgIndex;
1063  assert (Ins[I].PartOffset == 0);
1064  while (I + 1 != E && Ins[I + 1].OrigArgIndex == ArgIndex) {
1065  CCValAssign &PartVA = ArgLocs[I + 1];
1066  unsigned PartOffset = Ins[I + 1].PartOffset;
1067  SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
1068  DAG.getIntPtrConstant(PartOffset, DL));
1069  InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
1070  MachinePointerInfo()));
1071  ++I;
1072  }
1073  } else
1074  InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
1075  }
1076 
1077  if (IsVarArg) {
1078  // Save the number of non-varargs registers for later use by va_start, etc.
1079  FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
1080  FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
1081 
1082  // Likewise the address (in the form of a frame index) of where the
1083  // first stack vararg would be. The 1-byte size here is arbitrary.
1084  int64_t StackSize = CCInfo.getNextStackOffset();
1085  FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
1086 
1087  // ...and a similar frame index for the caller-allocated save area
1088  // that will be used to store the incoming registers.
1089  int64_t RegSaveOffset = TFL->getOffsetOfLocalArea();
1090  unsigned RegSaveIndex = MFI.CreateFixedObject(1, RegSaveOffset, true);
1091  FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
1092 
1093  // Store the FPR varargs in the reserved frame slots. (We store the
1094  // GPRs as part of the prologue.)
1095  if (NumFixedFPRs < SystemZ::NumArgFPRs) {
1096  SDValue MemOps[SystemZ::NumArgFPRs];
1097  for (unsigned I = NumFixedFPRs; I < SystemZ::NumArgFPRs; ++I) {
1098  unsigned Offset = TFL->getRegSpillOffset(SystemZ::ArgFPRs[I]);
1099  int FI = MFI.CreateFixedObject(8, RegSaveOffset + Offset, true);
1100  SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1101  unsigned VReg = MF.addLiveIn(SystemZ::ArgFPRs[I],
1102  &SystemZ::FP64BitRegClass);
1103  SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
1104  MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
1106  }
1107  // Join the stores, which are independent of one another.
1108  Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
1109  makeArrayRef(&MemOps[NumFixedFPRs],
1110  SystemZ::NumArgFPRs-NumFixedFPRs));
1111  }
1112  }
1113 
1114  return Chain;
1115 }
1116 
1117 static bool canUseSiblingCall(const CCState &ArgCCInfo,
1120  // Punt if there are any indirect or stack arguments, or if the call
1121  // needs the callee-saved argument register R6, or if the call uses
1122  // the callee-saved register arguments SwiftSelf and SwiftError.
1123  for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1124  CCValAssign &VA = ArgLocs[I];
1125  if (VA.getLocInfo() == CCValAssign::Indirect)
1126  return false;
1127  if (!VA.isRegLoc())
1128  return false;
1129  unsigned Reg = VA.getLocReg();
1130  if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
1131  return false;
1132  if (Outs[I].Flags.isSwiftSelf() || Outs[I].Flags.isSwiftError())
1133  return false;
1134  }
1135  return true;
1136 }
1137 
1138 SDValue
1140  SmallVectorImpl<SDValue> &InVals) const {
1141  SelectionDAG &DAG = CLI.DAG;
1142  SDLoc &DL = CLI.DL;
1144  SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1146  SDValue Chain = CLI.Chain;
1147  SDValue Callee = CLI.Callee;
1148  bool &IsTailCall = CLI.IsTailCall;
1149  CallingConv::ID CallConv = CLI.CallConv;
1150  bool IsVarArg = CLI.IsVarArg;
1151  MachineFunction &MF = DAG.getMachineFunction();
1152  EVT PtrVT = getPointerTy(MF.getDataLayout());
1153 
1154  // Detect unsupported vector argument and return types.
1155  if (Subtarget.hasVector()) {
1156  VerifyVectorTypes(Outs);
1157  VerifyVectorTypes(Ins);
1158  }
1159 
1160  // Analyze the operands of the call, assigning locations to each operand.
1162  SystemZCCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1163  ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
1164 
1165  // We don't support GuaranteedTailCallOpt, only automatically-detected
1166  // sibling calls.
1167  if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs, Outs))
1168  IsTailCall = false;
1169 
1170  // Get a count of how many bytes are to be pushed on the stack.
1171  unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1172 
1173  // Mark the start of the call.
1174  if (!IsTailCall)
1175  Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
1176 
1177  // Copy argument values to their designated locations.
1179  SmallVector<SDValue, 8> MemOpChains;
1180  SDValue StackPtr;
1181  for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1182  CCValAssign &VA = ArgLocs[I];
1183  SDValue ArgValue = OutVals[I];
1184 
1185  if (VA.getLocInfo() == CCValAssign::Indirect) {
1186  // Store the argument in a stack slot and pass its address.
1187  SDValue SpillSlot = DAG.CreateStackTemporary(Outs[I].ArgVT);
1188  int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1189  MemOpChains.push_back(
1190  DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1192  // If the original argument was split (e.g. i128), we need
1193  // to store all parts of it here (and pass just one address).
1194  unsigned ArgIndex = Outs[I].OrigArgIndex;
1195  assert (Outs[I].PartOffset == 0);
1196  while (I + 1 != E && Outs[I + 1].OrigArgIndex == ArgIndex) {
1197  SDValue PartValue = OutVals[I + 1];
1198  unsigned PartOffset = Outs[I + 1].PartOffset;
1199  SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
1200  DAG.getIntPtrConstant(PartOffset, DL));
1201  MemOpChains.push_back(
1202  DAG.getStore(Chain, DL, PartValue, Address,
1204  ++I;
1205  }
1206  ArgValue = SpillSlot;
1207  } else
1208  ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
1209 
1210  if (VA.isRegLoc())
1211  // Queue up the argument copies and emit them at the end.
1212  RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1213  else {
1214  assert(VA.isMemLoc() && "Argument not register or memory");
1215 
1216  // Work out the address of the stack slot. Unpromoted ints and
1217  // floats are passed as right-justified 8-byte values.
1218  if (!StackPtr.getNode())
1219  StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT);
1221  if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1222  Offset += 4;
1223  SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1224  DAG.getIntPtrConstant(Offset, DL));
1225 
1226  // Emit the store.
1227  MemOpChains.push_back(
1228  DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
1229  }
1230  }
1231 
1232  // Join the stores, which are independent of one another.
1233  if (!MemOpChains.empty())
1234  Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1235 
1236  // Accept direct calls by converting symbolic call addresses to the
1237  // associated Target* opcodes. Force %r1 to be used for indirect
1238  // tail calls.
1239  SDValue Glue;
1240  if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1241  Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
1242  Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1243  } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1244  Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
1245  Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1246  } else if (IsTailCall) {
1247  Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
1248  Glue = Chain.getValue(1);
1249  Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
1250  }
1251 
1252  // Build a sequence of copy-to-reg nodes, chained and glued together.
1253  for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
1254  Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
1255  RegsToPass[I].second, Glue);
1256  Glue = Chain.getValue(1);
1257  }
1258 
1259  // The first call operand is the chain and the second is the target address.
1261  Ops.push_back(Chain);
1262  Ops.push_back(Callee);
1263 
1264  // Add argument registers to the end of the list so that they are
1265  // known live into the call.
1266  for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
1267  Ops.push_back(DAG.getRegister(RegsToPass[I].first,
1268  RegsToPass[I].second.getValueType()));
1269 
1270  // Add a register mask operand representing the call-preserved registers.
1271  const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1272  const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1273  assert(Mask && "Missing call preserved mask for calling convention");
1274  Ops.push_back(DAG.getRegisterMask(Mask));
1275 
1276  // Glue the call to the argument copies, if any.
1277  if (Glue.getNode())
1278  Ops.push_back(Glue);
1279 
1280  // Emit the call.
1281  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1282  if (IsTailCall)
1283  return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
1284  Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
1285  Glue = Chain.getValue(1);
1286 
1287  // Mark the end of the call, which is glued to the call itself.
1288  Chain = DAG.getCALLSEQ_END(Chain,
1289  DAG.getConstant(NumBytes, DL, PtrVT, true),
1290  DAG.getConstant(0, DL, PtrVT, true),
1291  Glue, DL);
1292  Glue = Chain.getValue(1);
1293 
1294  // Assign locations to each value returned by this call.
1296  CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1297  RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
1298 
1299  // Copy all of the result registers out of their specified physreg.
1300  for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1301  CCValAssign &VA = RetLocs[I];
1302 
1303  // Copy the value out, gluing the copy to the end of the call sequence.
1304  SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
1305  VA.getLocVT(), Glue);
1306  Chain = RetValue.getValue(1);
1307  Glue = RetValue.getValue(2);
1308 
1309  // Convert the value of the return register into the value that's
1310  // being returned.
1311  InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
1312  }
1313 
1314  return Chain;
1315 }
1316 
1319  MachineFunction &MF, bool isVarArg,
1320  const SmallVectorImpl<ISD::OutputArg> &Outs,
1321  LLVMContext &Context) const {
1322  // Detect unsupported vector return types.
1323  if (Subtarget.hasVector())
1324  VerifyVectorTypes(Outs);
1325 
1326  // Special case that we cannot easily detect in RetCC_SystemZ since
1327  // i128 is not a legal type.
1328  for (auto &Out : Outs)
1329  if (Out.ArgVT == MVT::i128)
1330  return false;
1331 
1333  CCState RetCCInfo(CallConv, isVarArg, MF, RetLocs, Context);
1334  return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ);
1335 }
1336 
1337 SDValue
1339  bool IsVarArg,
1340  const SmallVectorImpl<ISD::OutputArg> &Outs,
1341  const SmallVectorImpl<SDValue> &OutVals,
1342  const SDLoc &DL, SelectionDAG &DAG) const {
1343  MachineFunction &MF = DAG.getMachineFunction();
1344 
1345  // Detect unsupported vector return types.
1346  if (Subtarget.hasVector())
1347  VerifyVectorTypes(Outs);
1348 
1349  // Assign locations to each returned value.
1351  CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1352  RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
1353 
1354  // Quick exit for void returns
1355  if (RetLocs.empty())
1356  return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
1357 
1358  // Copy the result values into the output registers.
1359  SDValue Glue;
1360  SmallVector<SDValue, 4> RetOps;
1361  RetOps.push_back(Chain);
1362  for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1363  CCValAssign &VA = RetLocs[I];
1364  SDValue RetValue = OutVals[I];
1365 
1366  // Make the return register live on exit.
1367  assert(VA.isRegLoc() && "Can only return in registers!");
1368 
1369  // Promote the value as required.
1370  RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
1371 
1372  // Chain and glue the copies together.
1373  unsigned Reg = VA.getLocReg();
1374  Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
1375  Glue = Chain.getValue(1);
1376  RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
1377  }
1378 
1379  // Update chain and glue.
1380  RetOps[0] = Chain;
1381  if (Glue.getNode())
1382  RetOps.push_back(Glue);
1383 
1384  return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, RetOps);
1385 }
1386 
1387 // Return true if Op is an intrinsic node with chain that returns the CC value
1388 // as its only (other) argument. Provide the associated SystemZISD opcode and
1389 // the mask of valid CC values if so.
1390 static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
1391  unsigned &CCValid) {
1392  unsigned Id = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1393  switch (Id) {
1394  case Intrinsic::s390_tbegin:
1395  Opcode = SystemZISD::TBEGIN;
1396  CCValid = SystemZ::CCMASK_TBEGIN;
1397  return true;
1398 
1399  case Intrinsic::s390_tbegin_nofloat:
1400  Opcode = SystemZISD::TBEGIN_NOFLOAT;
1401  CCValid = SystemZ::CCMASK_TBEGIN;
1402  return true;
1403 
1404  case Intrinsic::s390_tend:
1405  Opcode = SystemZISD::TEND;
1406  CCValid = SystemZ::CCMASK_TEND;
1407  return true;
1408 
1409  default:
1410  return false;
1411  }
1412 }
1413 
1414 // Return true if Op is an intrinsic node without chain that returns the
1415 // CC value as its final argument. Provide the associated SystemZISD
1416 // opcode and the mask of valid CC values if so.
1417 static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) {
1418  unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1419  switch (Id) {
1420  case Intrinsic::s390_vpkshs:
1421  case Intrinsic::s390_vpksfs:
1422  case Intrinsic::s390_vpksgs:
1423  Opcode = SystemZISD::PACKS_CC;
1424  CCValid = SystemZ::CCMASK_VCMP;
1425  return true;
1426 
1427  case Intrinsic::s390_vpklshs:
1428  case Intrinsic::s390_vpklsfs:
1429  case Intrinsic::s390_vpklsgs:
1430  Opcode = SystemZISD::PACKLS_CC;
1431  CCValid = SystemZ::CCMASK_VCMP;
1432  return true;
1433 
1434  case Intrinsic::s390_vceqbs:
1435  case Intrinsic::s390_vceqhs:
1436  case Intrinsic::s390_vceqfs:
1437  case Intrinsic::s390_vceqgs:
1438  Opcode = SystemZISD::VICMPES;
1439  CCValid = SystemZ::CCMASK_VCMP;
1440  return true;
1441 
1442  case Intrinsic::s390_vchbs:
1443  case Intrinsic::s390_vchhs:
1444  case Intrinsic::s390_vchfs:
1445  case Intrinsic::s390_vchgs:
1446  Opcode = SystemZISD::VICMPHS;
1447  CCValid = SystemZ::CCMASK_VCMP;
1448  return true;
1449 
1450  case Intrinsic::s390_vchlbs:
1451  case Intrinsic::s390_vchlhs:
1452  case Intrinsic::s390_vchlfs:
1453  case Intrinsic::s390_vchlgs:
1454  Opcode = SystemZISD::VICMPHLS;
1455  CCValid = SystemZ::CCMASK_VCMP;
1456  return true;
1457 
1458  case Intrinsic::s390_vtm:
1459  Opcode = SystemZISD::VTM;
1460  CCValid = SystemZ::CCMASK_VCMP;
1461  return true;
1462 
1463  case Intrinsic::s390_vfaebs:
1464  case Intrinsic::s390_vfaehs:
1465  case Intrinsic::s390_vfaefs:
1466  Opcode = SystemZISD::VFAE_CC;
1467  CCValid = SystemZ::CCMASK_ANY;
1468  return true;
1469 
1470  case Intrinsic::s390_vfaezbs:
1471  case Intrinsic::s390_vfaezhs:
1472  case Intrinsic::s390_vfaezfs:
1473  Opcode = SystemZISD::VFAEZ_CC;
1474  CCValid = SystemZ::CCMASK_ANY;
1475  return true;
1476 
1477  case Intrinsic::s390_vfeebs:
1478  case Intrinsic::s390_vfeehs:
1479  case Intrinsic::s390_vfeefs:
1480  Opcode = SystemZISD::VFEE_CC;
1481  CCValid = SystemZ::CCMASK_ANY;
1482  return true;
1483 
1484  case Intrinsic::s390_vfeezbs:
1485  case Intrinsic::s390_vfeezhs:
1486  case Intrinsic::s390_vfeezfs:
1487  Opcode = SystemZISD::VFEEZ_CC;
1488  CCValid = SystemZ::CCMASK_ANY;
1489  return true;
1490 
1491  case Intrinsic::s390_vfenebs:
1492  case Intrinsic::s390_vfenehs:
1493  case Intrinsic::s390_vfenefs:
1494  Opcode = SystemZISD::VFENE_CC;
1495  CCValid = SystemZ::CCMASK_ANY;
1496  return true;
1497 
1498  case Intrinsic::s390_vfenezbs:
1499  case Intrinsic::s390_vfenezhs:
1500  case Intrinsic::s390_vfenezfs:
1501  Opcode = SystemZISD::VFENEZ_CC;
1502  CCValid = SystemZ::CCMASK_ANY;
1503  return true;
1504 
1505  case Intrinsic::s390_vistrbs:
1506  case Intrinsic::s390_vistrhs:
1507  case Intrinsic::s390_vistrfs:
1508  Opcode = SystemZISD::VISTR_CC;
1510  return true;
1511 
1512  case Intrinsic::s390_vstrcbs:
1513  case Intrinsic::s390_vstrchs:
1514  case Intrinsic::s390_vstrcfs:
1515  Opcode = SystemZISD::VSTRC_CC;
1516  CCValid = SystemZ::CCMASK_ANY;
1517  return true;
1518 
1519  case Intrinsic::s390_vstrczbs:
1520  case Intrinsic::s390_vstrczhs:
1521  case Intrinsic::s390_vstrczfs:
1522  Opcode = SystemZISD::VSTRCZ_CC;
1523  CCValid = SystemZ::CCMASK_ANY;
1524  return true;
1525 
1526  case Intrinsic::s390_vfcedbs:
1527  case Intrinsic::s390_vfcesbs:
1528  Opcode = SystemZISD::VFCMPES;
1529  CCValid = SystemZ::CCMASK_VCMP;
1530  return true;
1531 
1532  case Intrinsic::s390_vfchdbs:
1533  case Intrinsic::s390_vfchsbs:
1534  Opcode = SystemZISD::VFCMPHS;
1535  CCValid = SystemZ::CCMASK_VCMP;
1536  return true;
1537 
1538  case Intrinsic::s390_vfchedbs:
1539  case Intrinsic::s390_vfchesbs:
1540  Opcode = SystemZISD::VFCMPHES;
1541  CCValid = SystemZ::CCMASK_VCMP;
1542  return true;
1543 
1544  case Intrinsic::s390_vftcidb:
1545  case Intrinsic::s390_vftcisb:
1546  Opcode = SystemZISD::VFTCI;
1547  CCValid = SystemZ::CCMASK_VCMP;
1548  return true;
1549 
1550  case Intrinsic::s390_tdc:
1551  Opcode = SystemZISD::TDC;
1552  CCValid = SystemZ::CCMASK_TDC;
1553  return true;
1554 
1555  default:
1556  return false;
1557  }
1558 }
1559 
1560 // Emit an intrinsic with chain with a glued value instead of its CC result.
1562  unsigned Opcode) {
1563  // Copy all operands except the intrinsic ID.
1564  unsigned NumOps = Op.getNumOperands();
1566  Ops.reserve(NumOps - 1);
1567  Ops.push_back(Op.getOperand(0));
1568  for (unsigned I = 2; I < NumOps; ++I)
1569  Ops.push_back(Op.getOperand(I));
1570 
1571  assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
1572  SDVTList RawVTs = DAG.getVTList(MVT::Other, MVT::Glue);
1573  SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
1574  SDValue OldChain = SDValue(Op.getNode(), 1);
1575  SDValue NewChain = SDValue(Intr.getNode(), 0);
1576  DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
1577  return Intr;
1578 }
1579 
1580 // Emit an intrinsic with a glued value instead of its CC result.
1582  unsigned Opcode) {
1583  // Copy all operands except the intrinsic ID.
1584  unsigned NumOps = Op.getNumOperands();
1586  Ops.reserve(NumOps - 1);
1587  for (unsigned I = 1; I < NumOps; ++I)
1588  Ops.push_back(Op.getOperand(I));
1589 
1590  if (Op->getNumValues() == 1)
1591  return DAG.getNode(Opcode, SDLoc(Op), MVT::Glue, Ops);
1592  assert(Op->getNumValues() == 2 && "Expected exactly one non-CC result");
1593  SDVTList RawVTs = DAG.getVTList(Op->getValueType(0), MVT::Glue);
1594  return DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
1595 }
1596 
1597 // CC is a comparison that will be implemented using an integer or
1598 // floating-point comparison. Return the condition code mask for
1599 // a branch on true. In the integer case, CCMASK_CMP_UO is set for
1600 // unsigned comparisons and clear for signed ones. In the floating-point
1601 // case, CCMASK_CMP_UO has its normal mask meaning (unordered).
1602 static unsigned CCMaskForCondCode(ISD::CondCode CC) {
1603 #define CONV(X) \
1604  case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
1605  case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
1606  case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
1607 
1608  switch (CC) {
1609  default:
1610  llvm_unreachable("Invalid integer condition!");
1611 
1612  CONV(EQ);
1613  CONV(NE);
1614  CONV(GT);
1615  CONV(GE);
1616  CONV(LT);
1617  CONV(LE);
1618 
1619  case ISD::SETO: return SystemZ::CCMASK_CMP_O;
1620  case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
1621  }
1622 #undef CONV
1623 }
1624 
1625 // Return a sequence for getting a 1 from an IPM result when CC has a
1626 // value in CCMask and a 0 when CC has a value in CCValid & ~CCMask.
1627 // The handling of CC values outside CCValid doesn't matter.
1628 static IPMConversion getIPMConversion(unsigned CCValid, unsigned CCMask) {
1629  // Deal with cases where the result can be taken directly from a bit
1630  // of the IPM result.
1631  if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_3)))
1632  return IPMConversion(0, 0, SystemZ::IPM_CC);
1633  if (CCMask == (CCValid & (SystemZ::CCMASK_2 | SystemZ::CCMASK_3)))
1634  return IPMConversion(0, 0, SystemZ::IPM_CC + 1);
1635 
1636  // Deal with cases where we can add a value to force the sign bit
1637  // to contain the right value. Putting the bit in 31 means we can
1638  // use SRL rather than RISBG(L), and also makes it easier to get a
1639  // 0/-1 value, so it has priority over the other tests below.
1640  //
1641  // These sequences rely on the fact that the upper two bits of the
1642  // IPM result are zero.
1643  uint64_t TopBit = uint64_t(1) << 31;
1644  if (CCMask == (CCValid & SystemZ::CCMASK_0))
1645  return IPMConversion(0, -(1 << SystemZ::IPM_CC), 31);
1646  if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_1)))
1647  return IPMConversion(0, -(2 << SystemZ::IPM_CC), 31);
1648  if (CCMask == (CCValid & (SystemZ::CCMASK_0
1650  | SystemZ::CCMASK_2)))
1651  return IPMConversion(0, -(3 << SystemZ::IPM_CC), 31);
1652  if (CCMask == (CCValid & SystemZ::CCMASK_3))
1653  return IPMConversion(0, TopBit - (3 << SystemZ::IPM_CC), 31);
1654  if (CCMask == (CCValid & (SystemZ::CCMASK_1
1656  | SystemZ::CCMASK_3)))
1657  return IPMConversion(0, TopBit - (1 << SystemZ::IPM_CC), 31);
1658 
1659  // Next try inverting the value and testing a bit. 0/1 could be
1660  // handled this way too, but we dealt with that case above.
1661  if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_2)))
1662  return IPMConversion(-1, 0, SystemZ::IPM_CC);
1663 
1664  // Handle cases where adding a value forces a non-sign bit to contain
1665  // the right value.
1666  if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_2)))
1667  return IPMConversion(0, 1 << SystemZ::IPM_CC, SystemZ::IPM_CC + 1);
1668  if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_3)))
1669  return IPMConversion(0, -(1 << SystemZ::IPM_CC), SystemZ::IPM_CC + 1);
1670 
1671  // The remaining cases are 1, 2, 0/1/3 and 0/2/3. All these are
1672  // can be done by inverting the low CC bit and applying one of the
1673  // sign-based extractions above.
1674  if (CCMask == (CCValid & SystemZ::CCMASK_1))
1675  return IPMConversion(1 << SystemZ::IPM_CC, -(1 << SystemZ::IPM_CC), 31);
1676  if (CCMask == (CCValid & SystemZ::CCMASK_2))
1677  return IPMConversion(1 << SystemZ::IPM_CC,
1678  TopBit - (3 << SystemZ::IPM_CC), 31);
1679  if (CCMask == (CCValid & (SystemZ::CCMASK_0
1680  | SystemZ::CCMASK_1
1681  | SystemZ::CCMASK_3)))
1682  return IPMConversion(1 << SystemZ::IPM_CC, -(3 << SystemZ::IPM_CC), 31);
1683  if (CCMask == (CCValid & (SystemZ::CCMASK_0
1684  | SystemZ::CCMASK_2
1685  | SystemZ::CCMASK_3)))
1686  return IPMConversion(1 << SystemZ::IPM_CC,
1687  TopBit - (1 << SystemZ::IPM_CC), 31);
1688 
1689  llvm_unreachable("Unexpected CC combination");
1690 }
1691 
1692 // If C can be converted to a comparison against zero, adjust the operands
1693 // as necessary.
1694 static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
1695  if (C.ICmpType == SystemZICMP::UnsignedOnly)
1696  return;
1697 
1698  auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
1699  if (!ConstOp1)
1700  return;
1701 
1702  int64_t Value = ConstOp1->getSExtValue();
1703  if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
1704  (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
1705  (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
1706  (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
1707  C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
1708  C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
1709  }
1710 }
1711 
1712 // If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
1713 // adjust the operands as necessary.
1714 static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL,
1715  Comparison &C) {
1716  // For us to make any changes, it must a comparison between a single-use
1717  // load and a constant.
1718  if (!C.Op0.hasOneUse() ||
1719  C.Op0.getOpcode() != ISD::LOAD ||
1720  C.Op1.getOpcode() != ISD::Constant)
1721  return;
1722 
1723  // We must have an 8- or 16-bit load.
1724  auto *Load = cast<LoadSDNode>(C.Op0);
1725  unsigned NumBits = Load->getMemoryVT().getStoreSizeInBits();
1726  if (NumBits != 8 && NumBits != 16)
1727  return;
1728 
1729  // The load must be an extending one and the constant must be within the
1730  // range of the unextended value.
1731  auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
1732  uint64_t Value = ConstOp1->getZExtValue();
1733  uint64_t Mask = (1 << NumBits) - 1;
1734  if (Load->getExtensionType() == ISD::SEXTLOAD) {
1735  // Make sure that ConstOp1 is in range of C.Op0.
1736  int64_t SignedValue = ConstOp1->getSExtValue();
1737  if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
1738  return;
1739  if (C.ICmpType != SystemZICMP::SignedOnly) {
1740  // Unsigned comparison between two sign-extended values is equivalent
1741  // to unsigned comparison between two zero-extended values.
1742  Value &= Mask;
1743  } else if (NumBits == 8) {
1744  // Try to treat the comparison as unsigned, so that we can use CLI.
1745  // Adjust CCMask and Value as necessary.
1746  if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
1747  // Test whether the high bit of the byte is set.
1748  Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
1749  else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
1750  // Test whether the high bit of the byte is clear.
1751  Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
1752  else
1753  // No instruction exists for this combination.
1754  return;
1755  C.ICmpType = SystemZICMP::UnsignedOnly;
1756  }
1757  } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
1758  if (Value > Mask)
1759  return;
1760  // If the constant is in range, we can use any comparison.
1761  C.ICmpType = SystemZICMP::Any;
1762  } else
1763  return;
1764 
1765  // Make sure that the first operand is an i32 of the right extension type.
1766  ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
1767  ISD::SEXTLOAD :
1768  ISD::ZEXTLOAD);
1769  if (C.Op0.getValueType() != MVT::i32 ||
1770  Load->getExtensionType() != ExtType)
1771  C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32, Load->getChain(),
1772  Load->getBasePtr(), Load->getPointerInfo(),
1773  Load->getMemoryVT(), Load->getAlignment(),
1774  Load->getMemOperand()->getFlags());
1775 
1776  // Make sure that the second operand is an i32 with the right value.
1777  if (C.Op1.getValueType() != MVT::i32 ||
1778  Value != ConstOp1->getZExtValue())
1779  C.Op1 = DAG.getConstant(Value, DL, MVT::i32);
1780 }
1781 
1782 // Return true if Op is either an unextended load, or a load suitable
1783 // for integer register-memory comparisons of type ICmpType.
1784 static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
1785  auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
1786  if (Load) {
1787  // There are no instructions to compare a register with a memory byte.
1788  if (Load->getMemoryVT() == MVT::i8)
1789  return false;
1790  // Otherwise decide on extension type.
1791  switch (Load->getExtensionType()) {
1792  case ISD::NON_EXTLOAD:
1793  return true;
1794  case ISD::SEXTLOAD:
1795  return ICmpType != SystemZICMP::UnsignedOnly;
1796  case ISD::ZEXTLOAD:
1797  return ICmpType != SystemZICMP::SignedOnly;
1798  default:
1799  break;
1800  }
1801  }
1802  return false;
1803 }
1804 
1805 // Return true if it is better to swap the operands of C.
1806 static bool shouldSwapCmpOperands(const Comparison &C) {
1807  // Leave f128 comparisons alone, since they have no memory forms.
1808  if (C.Op0.getValueType() == MVT::f128)
1809  return false;
1810 
1811  // Always keep a floating-point constant second, since comparisons with
1812  // zero can use LOAD TEST and comparisons with other constants make a
1813  // natural memory operand.
1814  if (isa<ConstantFPSDNode>(C.Op1))
1815  return false;
1816 
1817  // Never swap comparisons with zero since there are many ways to optimize
1818  // those later.
1819  auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
1820  if (ConstOp1 && ConstOp1->getZExtValue() == 0)
1821  return false;
1822 
1823  // Also keep natural memory operands second if the loaded value is
1824  // only used here. Several comparisons have memory forms.
1825  if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
1826  return false;
1827 
1828  // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
1829  // In that case we generally prefer the memory to be second.
1830  if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
1831  // The only exceptions are when the second operand is a constant and
1832  // we can use things like CHHSI.
1833  if (!ConstOp1)
1834  return true;
1835  // The unsigned memory-immediate instructions can handle 16-bit
1836  // unsigned integers.
1837  if (C.ICmpType != SystemZICMP::SignedOnly &&
1838  isUInt<16>(ConstOp1->getZExtValue()))
1839  return false;
1840  // The signed memory-immediate instructions can handle 16-bit
1841  // signed integers.
1842  if (C.ICmpType != SystemZICMP::UnsignedOnly &&
1843  isInt<16>(ConstOp1->getSExtValue()))
1844  return false;
1845  return true;
1846  }
1847 
1848  // Try to promote the use of CGFR and CLGFR.
1849  unsigned Opcode0 = C.Op0.getOpcode();
1850  if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
1851  return true;
1852  if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
1853  return true;
1854  if (C.ICmpType != SystemZICMP::SignedOnly &&
1855  Opcode0 == ISD::AND &&
1856  C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
1857  cast<ConstantSDNode>(C.Op0.getOperand(1))->getZExtValue() == 0xffffffff)
1858  return true;
1859 
1860  return false;
1861 }
1862 
1863 // Return a version of comparison CC mask CCMask in which the LT and GT
1864 // actions are swapped.
1865 static unsigned reverseCCMask(unsigned CCMask) {
1866  return ((CCMask & SystemZ::CCMASK_CMP_EQ) |
1868  (CCMask & SystemZ::CCMASK_CMP_LT ? SystemZ::CCMASK_CMP_GT : 0) |
1869  (CCMask & SystemZ::CCMASK_CMP_UO));
1870 }
1871 
1872 // Check whether C tests for equality between X and Y and whether X - Y
1873 // or Y - X is also computed. In that case it's better to compare the
1874 // result of the subtraction against zero.
1875 static void adjustForSubtraction(SelectionDAG &DAG, const SDLoc &DL,
1876  Comparison &C) {
1877  if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
1878  C.CCMask == SystemZ::CCMASK_CMP_NE) {
1879  for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1880  SDNode *N = *I;
1881  if (N->getOpcode() == ISD::SUB &&
1882  ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
1883  (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
1884  C.Op0 = SDValue(N, 0);
1885  C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
1886  return;
1887  }
1888  }
1889  }
1890 }
1891 
1892 // Check whether C compares a floating-point value with zero and if that
1893 // floating-point value is also negated. In this case we can use the
1894 // negation to set CC, so avoiding separate LOAD AND TEST and
1895 // LOAD (NEGATIVE/COMPLEMENT) instructions.
1896 static void adjustForFNeg(Comparison &C) {
1897  auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
1898  if (C1 && C1->isZero()) {
1899  for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
1900  SDNode *N = *I;
1901  if (N->getOpcode() == ISD::FNEG) {
1902  C.Op0 = SDValue(N, 0);
1903  C.CCMask = reverseCCMask(C.CCMask);
1904  return;
1905  }
1906  }
1907  }
1908 }
1909 
1910 // Check whether C compares (shl X, 32) with 0 and whether X is
1911 // also sign-extended. In that case it is better to test the result
1912 // of the sign extension using LTGFR.
1913 //
1914 // This case is important because InstCombine transforms a comparison
1915 // with (sext (trunc X)) into a comparison with (shl X, 32).
1916 static void adjustForLTGFR(Comparison &C) {
1917  // Check for a comparison between (shl X, 32) and 0.
1918  if (C.Op0.getOpcode() == ISD::SHL &&
1919  C.Op0.getValueType() == MVT::i64 &&
1920  C.Op1.getOpcode() == ISD::Constant &&
1921  cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1922  auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
1923  if (C1 && C1->getZExtValue() == 32) {
1924  SDValue ShlOp0 = C.Op0.getOperand(0);
1925  // See whether X has any SIGN_EXTEND_INREG uses.
1926  for (auto I = ShlOp0->use_begin(), E = ShlOp0->use_end(); I != E; ++I) {
1927  SDNode *N = *I;
1928  if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
1929  cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
1930  C.Op0 = SDValue(N, 0);
1931  return;
1932  }
1933  }
1934  }
1935  }
1936 }
1937 
1938 // If C compares the truncation of an extending load, try to compare
1939 // the untruncated value instead. This exposes more opportunities to
1940 // reuse CC.
1941 static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL,
1942  Comparison &C) {
1943  if (C.Op0.getOpcode() == ISD::TRUNCATE &&
1944  C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
1945  C.Op1.getOpcode() == ISD::Constant &&
1946  cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
1947  auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
1948  if (L->getMemoryVT().getStoreSizeInBits() <= C.Op0.getValueSizeInBits()) {
1949  unsigned Type = L->getExtensionType();
1950  if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
1951  (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
1952  C.Op0 = C.Op0.getOperand(0);
1953  C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
1954  }
1955  }
1956  }
1957 }
1958 
1959 // Return true if shift operation N has an in-range constant shift value.
1960 // Store it in ShiftVal if so.
1961 static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
1962  auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
1963  if (!Shift)
1964  return false;
1965 
1966  uint64_t Amount = Shift->getZExtValue();
1967  if (Amount >= N.getValueSizeInBits())
1968  return false;
1969 
1970  ShiftVal = Amount;
1971  return true;
1972 }
1973 
1974 // Check whether an AND with Mask is suitable for a TEST UNDER MASK
1975 // instruction and whether the CC value is descriptive enough to handle
1976 // a comparison of type Opcode between the AND result and CmpVal.
1977 // CCMask says which comparison result is being tested and BitSize is
1978 // the number of bits in the operands. If TEST UNDER MASK can be used,
1979 // return the corresponding CC mask, otherwise return 0.
1980 static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
1981  uint64_t Mask, uint64_t CmpVal,
1982  unsigned ICmpType) {
1983  assert(Mask != 0 && "ANDs with zero should have been removed by now");
1984 
1985  // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
1986  if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
1987  !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
1988  return 0;
1989 
1990  // Work out the masks for the lowest and highest bits.
1991  unsigned HighShift = 63 - countLeadingZeros(Mask);
1992  uint64_t High = uint64_t(1) << HighShift;
1993  uint64_t Low = uint64_t(1) << countTrailingZeros(Mask);
1994 
1995  // Signed ordered comparisons are effectively unsigned if the sign
1996  // bit is dropped.
1997  bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
1998 
1999  // Check for equality comparisons with 0, or the equivalent.
2000  if (CmpVal == 0) {
2001  if (CCMask == SystemZ::CCMASK_CMP_EQ)
2002  return SystemZ::CCMASK_TM_ALL_0;
2003  if (CCMask == SystemZ::CCMASK_CMP_NE)
2005  }
2006  if (EffectivelyUnsigned && CmpVal > 0 && CmpVal <= Low) {
2007  if (CCMask == SystemZ::CCMASK_CMP_LT)
2008  return SystemZ::CCMASK_TM_ALL_0;
2009  if (CCMask == SystemZ::CCMASK_CMP_GE)
2011  }
2012  if (EffectivelyUnsigned && CmpVal < Low) {
2013  if (CCMask == SystemZ::CCMASK_CMP_LE)
2014  return SystemZ::CCMASK_TM_ALL_0;
2015  if (CCMask == SystemZ::CCMASK_CMP_GT)
2017  }
2018 
2019  // Check for equality comparisons with the mask, or the equivalent.
2020  if (CmpVal == Mask) {
2021  if (CCMask == SystemZ::CCMASK_CMP_EQ)
2022  return SystemZ::CCMASK_TM_ALL_1;
2023  if (CCMask == SystemZ::CCMASK_CMP_NE)
2025  }
2026  if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
2027  if (CCMask == SystemZ::CCMASK_CMP_GT)
2028  return SystemZ::CCMASK_TM_ALL_1;
2029  if (CCMask == SystemZ::CCMASK_CMP_LE)
2031  }
2032  if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
2033  if (CCMask == SystemZ::CCMASK_CMP_GE)
2034  return SystemZ::CCMASK_TM_ALL_1;
2035  if (CCMask == SystemZ::CCMASK_CMP_LT)
2037  }
2038 
2039  // Check for ordered comparisons with the top bit.
2040  if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
2041  if (CCMask == SystemZ::CCMASK_CMP_LE)
2042  return SystemZ::CCMASK_TM_MSB_0;
2043  if (CCMask == SystemZ::CCMASK_CMP_GT)
2044  return SystemZ::CCMASK_TM_MSB_1;
2045  }
2046  if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
2047  if (CCMask == SystemZ::CCMASK_CMP_LT)
2048  return SystemZ::CCMASK_TM_MSB_0;
2049  if (CCMask == SystemZ::CCMASK_CMP_GE)
2050  return SystemZ::CCMASK_TM_MSB_1;
2051  }
2052 
2053  // If there are just two bits, we can do equality checks for Low and High
2054  // as well.
2055  if (Mask == Low + High) {
2056  if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
2058  if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
2060  if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
2062  if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
2064  }
2065 
2066  // Looks like we've exhausted our options.
2067  return 0;
2068 }
2069 
2070 // See whether C can be implemented as a TEST UNDER MASK instruction.
2071 // Update the arguments with the TM version if so.
2072 static void adjustForTestUnderMask(SelectionDAG &DAG, const SDLoc &DL,
2073  Comparison &C) {
2074  // Check that we have a comparison with a constant.
2075  auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
2076  if (!ConstOp1)
2077  return;
2078  uint64_t CmpVal = ConstOp1->getZExtValue();
2079 
2080  // Check whether the nonconstant input is an AND with a constant mask.
2081  Comparison NewC(C);
2082  uint64_t MaskVal;
2083  ConstantSDNode *Mask = nullptr;
2084  if (C.Op0.getOpcode() == ISD::AND) {
2085  NewC.Op0 = C.Op0.getOperand(0);
2086  NewC.Op1 = C.Op0.getOperand(1);
2087  Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
2088  if (!Mask)
2089  return;
2090  MaskVal = Mask->getZExtValue();
2091  } else {
2092  // There is no instruction to compare with a 64-bit immediate
2093  // so use TMHH instead if possible. We need an unsigned ordered
2094  // comparison with an i64 immediate.
2095  if (NewC.Op0.getValueType() != MVT::i64 ||
2096  NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
2097  NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
2098  NewC.ICmpType == SystemZICMP::SignedOnly)
2099  return;
2100  // Convert LE and GT comparisons into LT and GE.
2101  if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
2102  NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
2103  if (CmpVal == uint64_t(-1))
2104  return;
2105  CmpVal += 1;
2106  NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
2107  }
2108  // If the low N bits of Op1 are zero than the low N bits of Op0 can
2109  // be masked off without changing the result.
2110  MaskVal = -(CmpVal & -CmpVal);
2111  NewC.ICmpType = SystemZICMP::UnsignedOnly;
2112  }
2113  if (!MaskVal)
2114  return;
2115 
2116  // Check whether the combination of mask, comparison value and comparison
2117  // type are suitable.
2118  unsigned BitSize = NewC.Op0.getValueSizeInBits();
2119  unsigned NewCCMask, ShiftVal;
2120  if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2121  NewC.Op0.getOpcode() == ISD::SHL &&
2122  isSimpleShift(NewC.Op0, ShiftVal) &&
2123  (MaskVal >> ShiftVal != 0) &&
2124  (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2125  MaskVal >> ShiftVal,
2126  CmpVal >> ShiftVal,
2127  SystemZICMP::Any))) {
2128  NewC.Op0 = NewC.Op0.getOperand(0);
2129  MaskVal >>= ShiftVal;
2130  } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2131  NewC.Op0.getOpcode() == ISD::SRL &&
2132  isSimpleShift(NewC.Op0, ShiftVal) &&
2133  (MaskVal << ShiftVal != 0) &&
2134  (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2135  MaskVal << ShiftVal,
2136  CmpVal << ShiftVal,
2138  NewC.Op0 = NewC.Op0.getOperand(0);
2139  MaskVal <<= ShiftVal;
2140  } else {
2141  NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
2142  NewC.ICmpType);
2143  if (!NewCCMask)
2144  return;
2145  }
2146 
2147  // Go ahead and make the change.
2148  C.Opcode = SystemZISD::TM;
2149  C.Op0 = NewC.Op0;
2150  if (Mask && Mask->getZExtValue() == MaskVal)
2151  C.Op1 = SDValue(Mask, 0);
2152  else
2153  C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
2154  C.CCValid = SystemZ::CCMASK_TM;
2155  C.CCMask = NewCCMask;
2156 }
2157 
2158 // Return a Comparison that tests the condition-code result of intrinsic
2159 // node Call against constant integer CC using comparison code Cond.
2160 // Opcode is the opcode of the SystemZISD operation for the intrinsic
2161 // and CCValid is the set of possible condition-code results.
2162 static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
2163  SDValue Call, unsigned CCValid, uint64_t CC,
2164  ISD::CondCode Cond) {
2165  Comparison C(Call, SDValue());
2166  C.Opcode = Opcode;
2167  C.CCValid = CCValid;
2168  if (Cond == ISD::SETEQ)
2169  // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
2170  C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
2171  else if (Cond == ISD::SETNE)
2172  // ...and the inverse of that.
2173  C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
2174  else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
2175  // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
2176  // always true for CC>3.
2177  C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1;
2178  else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
2179  // ...and the inverse of that.
2180  C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0;
2181  else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
2182  // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
2183  // always true for CC>3.
2184  C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1;
2185  else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
2186  // ...and the inverse of that.
2187  C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0;
2188  else
2189  llvm_unreachable("Unexpected integer comparison type");
2190  C.CCMask &= CCValid;
2191  return C;
2192 }
2193 
2194 // Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
2195 static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
2196  ISD::CondCode Cond, const SDLoc &DL) {
2197  if (CmpOp1.getOpcode() == ISD::Constant) {
2198  uint64_t Constant = cast<ConstantSDNode>(CmpOp1)->getZExtValue();
2199  unsigned Opcode, CCValid;
2200  if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
2201  CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
2202  isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
2203  return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2204  if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
2205  CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 &&
2206  isIntrinsicWithCC(CmpOp0, Opcode, CCValid))
2207  return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2208  }
2209  Comparison C(CmpOp0, CmpOp1);
2210  C.CCMask = CCMaskForCondCode(Cond);
2211  if (C.Op0.getValueType().isFloatingPoint()) {
2212  C.CCValid = SystemZ::CCMASK_FCMP;
2213  C.Opcode = SystemZISD::FCMP;
2214  adjustForFNeg(C);
2215  } else {
2216  C.CCValid = SystemZ::CCMASK_ICMP;
2217  C.Opcode = SystemZISD::ICMP;
2218  // Choose the type of comparison. Equality and inequality tests can
2219  // use either signed or unsigned comparisons. The choice also doesn't
2220  // matter if both sign bits are known to be clear. In those cases we
2221  // want to give the main isel code the freedom to choose whichever
2222  // form fits best.
2223  if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
2224  C.CCMask == SystemZ::CCMASK_CMP_NE ||
2225  (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
2226  C.ICmpType = SystemZICMP::Any;
2227  else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
2228  C.ICmpType = SystemZICMP::UnsignedOnly;
2229  else
2230  C.ICmpType = SystemZICMP::SignedOnly;
2231  C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
2232  adjustZeroCmp(DAG, DL, C);
2233  adjustSubwordCmp(DAG, DL, C);
2234  adjustForSubtraction(DAG, DL, C);
2235  adjustForLTGFR(C);
2236  adjustICmpTruncate(DAG, DL, C);
2237  }
2238 
2239  if (shouldSwapCmpOperands(C)) {
2240  std::swap(C.Op0, C.Op1);
2241  C.CCMask = reverseCCMask(C.CCMask);
2242  }
2243 
2244  adjustForTestUnderMask(DAG, DL, C);
2245  return C;
2246 }
2247 
2248 // Emit the comparison instruction described by C.
2249 static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
2250  if (!C.Op1.getNode()) {
2251  SDValue Op;
2252  switch (C.Op0.getOpcode()) {
2254  Op = emitIntrinsicWithChainAndGlue(DAG, C.Op0, C.Opcode);
2255  break;
2257  Op = emitIntrinsicWithGlue(DAG, C.Op0, C.Opcode);
2258  break;
2259  default:
2260  llvm_unreachable("Invalid comparison operands");
2261  }
2262  return SDValue(Op.getNode(), Op->getNumValues() - 1);
2263  }
2264  if (C.Opcode == SystemZISD::ICMP)
2265  return DAG.getNode(SystemZISD::ICMP, DL, MVT::Glue, C.Op0, C.Op1,
2266  DAG.getConstant(C.ICmpType, DL, MVT::i32));
2267  if (C.Opcode == SystemZISD::TM) {
2268  bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
2269  bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_1));
2270  return DAG.getNode(SystemZISD::TM, DL, MVT::Glue, C.Op0, C.Op1,
2271  DAG.getConstant(RegisterOnly, DL, MVT::i32));
2272  }
2273  return DAG.getNode(C.Opcode, DL, MVT::Glue, C.Op0, C.Op1);
2274 }
2275 
2276 // Implement a 32-bit *MUL_LOHI operation by extending both operands to
2277 // 64 bits. Extend is the extension type to use. Store the high part
2278 // in Hi and the low part in Lo.
2279 static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend,
2280  SDValue Op0, SDValue Op1, SDValue &Hi,
2281  SDValue &Lo) {
2282  Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
2283  Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
2284  SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
2285  Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2286  DAG.getConstant(32, DL, MVT::i64));
2287  Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
2288  Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
2289 }
2290 
2291 // Lower a binary operation that produces two VT results, one in each
2292 // half of a GR128 pair. Op0 and Op1 are the VT operands to the operation,
2293 // and Opcode performs the GR128 operation. Store the even register result
2294 // in Even and the odd register result in Odd.
2295 static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
2296  unsigned Opcode, SDValue Op0, SDValue Op1,
2297  SDValue &Even, SDValue &Odd) {
2298  SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped, Op0, Op1);
2299  bool Is32Bit = is32Bit(VT);
2300  Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
2301  Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
2302 }
2303 
2304 // Return an i32 value that is 1 if the CC value produced by Glue is
2305 // in the mask CCMask and 0 otherwise. CC is known to have a value
2306 // in CCValid, so other values can be ignored.
2307 static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue Glue,
2308  unsigned CCValid, unsigned CCMask) {
2309  IPMConversion Conversion = getIPMConversion(CCValid, CCMask);
2310  SDValue Result = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
2311 
2312  if (Conversion.XORValue)
2313  Result = DAG.getNode(ISD::XOR, DL, MVT::i32, Result,
2314  DAG.getConstant(Conversion.XORValue, DL, MVT::i32));
2315 
2316  if (Conversion.AddValue)
2317  Result = DAG.getNode(ISD::ADD, DL, MVT::i32, Result,
2318  DAG.getConstant(Conversion.AddValue, DL, MVT::i32));
2319 
2320  // The SHR/AND sequence should get optimized to an RISBG.
2321  Result = DAG.getNode(ISD::SRL, DL, MVT::i32, Result,
2322  DAG.getConstant(Conversion.Bit, DL, MVT::i32));
2323  if (Conversion.Bit != 31)
2324  Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
2325  DAG.getConstant(1, DL, MVT::i32));
2326  return Result;
2327 }
2328 
2329 // Return the SystemISD vector comparison operation for CC, or 0 if it cannot
2330 // be done directly. IsFP is true if CC is for a floating-point rather than
2331 // integer comparison.
2332 static unsigned getVectorComparison(ISD::CondCode CC, bool IsFP) {
2333  switch (CC) {
2334  case ISD::SETOEQ:
2335  case ISD::SETEQ:
2336  return IsFP ? SystemZISD::VFCMPE : SystemZISD::VICMPE;
2337 
2338  case ISD::SETOGE:
2339  case ISD::SETGE:
2340  return IsFP ? SystemZISD::VFCMPHE : static_cast<SystemZISD::NodeType>(0);
2341 
2342  case ISD::SETOGT:
2343  case ISD::SETGT:
2344  return IsFP ? SystemZISD::VFCMPH : SystemZISD::VICMPH;
2345 
2346  case ISD::SETUGT:
2347  return IsFP ? static_cast<SystemZISD::NodeType>(0) : SystemZISD::VICMPHL;
2348 
2349  default:
2350  return 0;
2351  }
2352 }
2353 
2354 // Return the SystemZISD vector comparison operation for CC or its inverse,
2355 // or 0 if neither can be done directly. Indicate in Invert whether the
2356 // result is for the inverse of CC. IsFP is true if CC is for a
2357 // floating-point rather than integer comparison.
2358 static unsigned getVectorComparisonOrInvert(ISD::CondCode CC, bool IsFP,
2359  bool &Invert) {
2360  if (unsigned Opcode = getVectorComparison(CC, IsFP)) {
2361  Invert = false;
2362  return Opcode;
2363  }
2364 
2365  CC = ISD::getSetCCInverse(CC, !IsFP);
2366  if (unsigned Opcode = getVectorComparison(CC, IsFP)) {
2367  Invert = true;
2368  return Opcode;
2369  }
2370 
2371  return 0;
2372 }
2373 
2374 // Return a v2f64 that contains the extended form of elements Start and Start+1
2375 // of v4f32 value Op.
2376 static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL,
2377  SDValue Op) {
2378  int Mask[] = { Start, -1, Start + 1, -1 };
2379  Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
2380  return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
2381 }
2382 
2383 // Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
2384 // producing a result of type VT.
2385 SDValue SystemZTargetLowering::getVectorCmp(SelectionDAG &DAG, unsigned Opcode,
2386  const SDLoc &DL, EVT VT,
2387  SDValue CmpOp0,
2388  SDValue CmpOp1) const {
2389  // There is no hardware support for v4f32 (unless we have the vector
2390  // enhancements facility 1), so extend the vector into two v2f64s
2391  // and compare those.
2392  if (CmpOp0.getValueType() == MVT::v4f32 &&
2393  !Subtarget.hasVectorEnhancements1()) {
2394  SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0);
2395  SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0);
2396  SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1);
2397  SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1);
2398  SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
2399  SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
2400  return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
2401  }
2402  return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
2403 }
2404 
2405 // Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
2406 // an integer mask of type VT.
2407 SDValue SystemZTargetLowering::lowerVectorSETCC(SelectionDAG &DAG,
2408  const SDLoc &DL, EVT VT,
2409  ISD::CondCode CC,
2410  SDValue CmpOp0,
2411  SDValue CmpOp1) const {
2412  bool IsFP = CmpOp0.getValueType().isFloatingPoint();
2413  bool Invert = false;
2414  SDValue Cmp;
2415  switch (CC) {
2416  // Handle tests for order using (or (ogt y x) (oge x y)).
2417  case ISD::SETUO:
2418  Invert = true;
2420  case ISD::SETO: {
2421  assert(IsFP && "Unexpected integer comparison");
2422  SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0);
2423  SDValue GE = getVectorCmp(DAG, SystemZISD::VFCMPHE, DL, VT, CmpOp0, CmpOp1);
2424  Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
2425  break;
2426  }
2427 
2428  // Handle <> tests using (or (ogt y x) (ogt x y)).
2429  case ISD::SETUEQ:
2430  Invert = true;
2432  case ISD::SETONE: {
2433  assert(IsFP && "Unexpected integer comparison");
2434  SDValue LT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp1, CmpOp0);
2435  SDValue GT = getVectorCmp(DAG, SystemZISD::VFCMPH, DL, VT, CmpOp0, CmpOp1);
2436  Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
2437  break;
2438  }
2439 
2440  // Otherwise a single comparison is enough. It doesn't really
2441  // matter whether we try the inversion or the swap first, since
2442  // there are no cases where both work.
2443  default:
2444  if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert))
2445  Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1);
2446  else {
2448  if (unsigned Opcode = getVectorComparisonOrInvert(CC, IsFP, Invert))
2449  Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0);
2450  else
2451  llvm_unreachable("Unhandled comparison");
2452  }
2453  break;
2454  }
2455  if (Invert) {
2457  DAG.getConstant(65535, DL, MVT::i32));
2458  Mask = DAG.getNode(ISD::BITCAST, DL, VT, Mask);
2459  Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
2460  }
2461  return Cmp;
2462 }
2463 
2464 SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
2465  SelectionDAG &DAG) const {
2466  SDValue CmpOp0 = Op.getOperand(0);
2467  SDValue CmpOp1 = Op.getOperand(1);
2468  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2469  SDLoc DL(Op);
2470  EVT VT = Op.getValueType();
2471  if (VT.isVector())
2472  return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
2473 
2474  Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2475  SDValue Glue = emitCmp(DAG, DL, C);
2476  return emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
2477 }
2478 
2479 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2480  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2481  SDValue CmpOp0 = Op.getOperand(2);
2482  SDValue CmpOp1 = Op.getOperand(3);
2483  SDValue Dest = Op.getOperand(4);
2484  SDLoc DL(Op);
2485 
2486  Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2487  SDValue Glue = emitCmp(DAG, DL, C);
2488  return DAG.getNode(SystemZISD::BR_CCMASK, DL, Op.getValueType(),
2489  Op.getOperand(0), DAG.getConstant(C.CCValid, DL, MVT::i32),
2490  DAG.getConstant(C.CCMask, DL, MVT::i32), Dest, Glue);
2491 }
2492 
2493 // Return true if Pos is CmpOp and Neg is the negative of CmpOp,
2494 // allowing Pos and Neg to be wider than CmpOp.
2495 static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
2496  return (Neg.getOpcode() == ISD::SUB &&
2497  Neg.getOperand(0).getOpcode() == ISD::Constant &&
2498  cast<ConstantSDNode>(Neg.getOperand(0))->getZExtValue() == 0 &&
2499  Neg.getOperand(1) == Pos &&
2500  (Pos == CmpOp ||
2501  (Pos.getOpcode() == ISD::SIGN_EXTEND &&
2502  Pos.getOperand(0) == CmpOp)));
2503 }
2504 
2505 // Return the absolute or negative absolute of Op; IsNegative decides which.
2506 static SDValue getAbsolute(SelectionDAG &DAG, const SDLoc &DL, SDValue Op,
2507  bool IsNegative) {
2508  Op = DAG.getNode(SystemZISD::IABS, DL, Op.getValueType(), Op);
2509  if (IsNegative)
2510  Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
2511  DAG.getConstant(0, DL, Op.getValueType()), Op);
2512  return Op;
2513 }
2514 
2515 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
2516  SelectionDAG &DAG) const {
2517  SDValue CmpOp0 = Op.getOperand(0);
2518  SDValue CmpOp1 = Op.getOperand(1);
2519  SDValue TrueOp = Op.getOperand(2);
2520  SDValue FalseOp = Op.getOperand(3);
2521  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2522  SDLoc DL(Op);
2523 
2524  Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2525 
2526  // Check for absolute and negative-absolute selections, including those
2527  // where the comparison value is sign-extended (for LPGFR and LNGFR).
2528  // This check supplements the one in DAGCombiner.
2529  if (C.Opcode == SystemZISD::ICMP &&
2530  C.CCMask != SystemZ::CCMASK_CMP_EQ &&
2531  C.CCMask != SystemZ::CCMASK_CMP_NE &&
2532  C.Op1.getOpcode() == ISD::Constant &&
2533  cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2534  if (isAbsolute(C.Op0, TrueOp, FalseOp))
2535  return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
2536  if (isAbsolute(C.Op0, FalseOp, TrueOp))
2537  return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
2538  }
2539 
2540  SDValue Glue = emitCmp(DAG, DL, C);
2541 
2542  // Special case for handling -1/0 results. The shifts we use here
2543  // should get optimized with the IPM conversion sequence.
2544  auto *TrueC = dyn_cast<ConstantSDNode>(TrueOp);
2545  auto *FalseC = dyn_cast<ConstantSDNode>(FalseOp);
2546  if (TrueC && FalseC) {
2547  int64_t TrueVal = TrueC->getSExtValue();
2548  int64_t FalseVal = FalseC->getSExtValue();
2549  if ((TrueVal == -1 && FalseVal == 0) || (TrueVal == 0 && FalseVal == -1)) {
2550  // Invert the condition if we want -1 on false.
2551  if (TrueVal == 0)
2552  C.CCMask ^= C.CCValid;
2553  SDValue Result = emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
2554  EVT VT = Op.getValueType();
2555  // Extend the result to VT. Upper bits are ignored.
2556  if (!is32Bit(VT))
2557  Result = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Result);
2558  // Sign-extend from the low bit.
2559  SDValue ShAmt = DAG.getConstant(VT.getSizeInBits() - 1, DL, MVT::i32);
2560  SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Result, ShAmt);
2561  return DAG.getNode(ISD::SRA, DL, VT, Shl, ShAmt);
2562  }
2563  }
2564 
2565  SDValue Ops[] = {TrueOp, FalseOp, DAG.getConstant(C.CCValid, DL, MVT::i32),
2566  DAG.getConstant(C.CCMask, DL, MVT::i32), Glue};
2567 
2568  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
2569  return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VTs, Ops);
2570 }
2571 
2572 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
2573  SelectionDAG &DAG) const {
2574  SDLoc DL(Node);
2575  const GlobalValue *GV = Node->getGlobal();
2576  int64_t Offset = Node->getOffset();
2577  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2579 
2580  SDValue Result;
2581  if (Subtarget.isPC32DBLSymbol(GV, CM)) {
2582  // Assign anchors at 1<<12 byte boundaries.
2583  uint64_t Anchor = Offset & ~uint64_t(0xfff);
2584  Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
2585  Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2586 
2587  // The offset can be folded into the address if it is aligned to a halfword.
2588  Offset -= Anchor;
2589  if (Offset != 0 && (Offset & 1) == 0) {
2590  SDValue Full = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
2591  Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
2592  Offset = 0;
2593  }
2594  } else {
2595  Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
2596  Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2597  Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2599  }
2600 
2601  // If there was a non-zero offset that we didn't fold, create an explicit
2602  // addition for it.
2603  if (Offset != 0)
2604  Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
2605  DAG.getConstant(Offset, DL, PtrVT));
2606 
2607  return Result;
2608 }
2609 
2610 SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
2611  SelectionDAG &DAG,
2612  unsigned Opcode,
2613  SDValue GOTOffset) const {
2614  SDLoc DL(Node);
2615  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2616  SDValue Chain = DAG.getEntryNode();
2617  SDValue Glue;
2618 
2619  // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
2620  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2621  Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
2622  Glue = Chain.getValue(1);
2623  Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
2624  Glue = Chain.getValue(1);
2625 
2626  // The first call operand is the chain and the second is the TLS symbol.
2628  Ops.push_back(Chain);
2629  Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
2630  Node->getValueType(0),
2631  0, 0));
2632 
2633  // Add argument registers to the end of the list so that they are
2634  // known live into the call.
2635  Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
2636  Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
2637 
2638  // Add a register mask operand representing the call-preserved registers.
2639  const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2640  const uint32_t *Mask =
2642  assert(Mask && "Missing call preserved mask for calling convention");
2643  Ops.push_back(DAG.getRegisterMask(Mask));
2644 
2645  // Glue the call to the argument copies.
2646  Ops.push_back(Glue);
2647 
2648  // Emit the call.
2649  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2650  Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
2651  Glue = Chain.getValue(1);
2652 
2653  // Copy the return value from %r2.
2654  return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
2655 }
2656 
2657 SDValue SystemZTargetLowering::lowerThreadPointer(const SDLoc &DL,
2658  SelectionDAG &DAG) const {
2659  SDValue Chain = DAG.getEntryNode();
2660  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2661 
2662  // The high part of the thread pointer is in access register 0.
2663  SDValue TPHi = DAG.getCopyFromReg(Chain, DL, SystemZ::A0, MVT::i32);
2664  TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
2665 
2666  // The low part of the thread pointer is in access register 1.
2667  SDValue TPLo = DAG.getCopyFromReg(Chain, DL, SystemZ::A1, MVT::i32);
2668  TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
2669 
2670  // Merge them into a single 64-bit address.
2671  SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
2672  DAG.getConstant(32, DL, PtrVT));
2673  return DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
2674 }
2675 
2676 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
2677  SelectionDAG &DAG) const {
2678  if (DAG.getTarget().Options.EmulatedTLS)
2679  return LowerToTLSEmulatedModel(Node, DAG);
2680  SDLoc DL(Node);
2681  const GlobalValue *GV = Node->getGlobal();
2682  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2683  TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
2684 
2685  SDValue TP = lowerThreadPointer(DL, DAG);
2686 
2687  // Get the offset of GA from the thread pointer, based on the TLS model.
2688  SDValue Offset;
2689  switch (model) {
2690  case TLSModel::GeneralDynamic: {
2691  // Load the GOT offset of the tls_index (module ID / per-symbol offset).
2694 
2695  Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2696  Offset = DAG.getLoad(
2697  PtrVT, DL, DAG.getEntryNode(), Offset,
2699 
2700  // Call __tls_get_offset to retrieve the offset.
2701  Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
2702  break;
2703  }
2704 
2705  case TLSModel::LocalDynamic: {
2706  // Load the GOT offset of the module ID.
2709 
2710  Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2711  Offset = DAG.getLoad(
2712  PtrVT, DL, DAG.getEntryNode(), Offset,
2714 
2715  // Call __tls_get_offset to retrieve the module base offset.
2716  Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
2717 
2718  // Note: The SystemZLDCleanupPass will remove redundant computations
2719  // of the module base offset. Count total number of local-dynamic
2720  // accesses to trigger execution of that pass.
2724 
2725  // Add the per-symbol offset.
2727 
2728  SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, 8);
2729  DTPOffset = DAG.getLoad(
2730  PtrVT, DL, DAG.getEntryNode(), DTPOffset,
2732 
2733  Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
2734  break;
2735  }
2736 
2737  case TLSModel::InitialExec: {
2738  // Load the offset from the GOT.
2739  Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2741  Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
2742  Offset =
2743  DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset,
2745  break;
2746  }
2747 
2748  case TLSModel::LocalExec: {
2749  // Force the offset into the constant pool and load it from there.
2752 
2753  Offset = DAG.getConstantPool(CPV, PtrVT, 8);
2754  Offset = DAG.getLoad(
2755  PtrVT, DL, DAG.getEntryNode(), Offset,
2757  break;
2758  }
2759  }
2760 
2761  // Add the base and offset together.
2762  return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
2763 }
2764 
2765 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
2766  SelectionDAG &DAG) const {
2767  SDLoc DL(Node);
2768  const BlockAddress *BA = Node->getBlockAddress();
2769  int64_t Offset = Node->getOffset();
2770  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2771 
2772  SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
2773  Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2774  return Result;
2775 }
2776 
2777 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
2778  SelectionDAG &DAG) const {
2779  SDLoc DL(JT);
2780  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2781  SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2782 
2783  // Use LARL to load the address of the table.
2784  return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2785 }
2786 
2787 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
2788  SelectionDAG &DAG) const {
2789  SDLoc DL(CP);
2790  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2791 
2792  SDValue Result;
2793  if (CP->isMachineConstantPoolEntry())
2794  Result = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2795  CP->getAlignment());
2796  else
2797  Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2798  CP->getAlignment(), CP->getOffset());
2799 
2800  // Use LARL to load the address of the constant pool entry.
2801  return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
2802 }
2803 
2804 SDValue SystemZTargetLowering::lowerFRAMEADDR(SDValue Op,
2805  SelectionDAG &DAG) const {
2806  MachineFunction &MF = DAG.getMachineFunction();
2807  MachineFrameInfo &MFI = MF.getFrameInfo();
2808  MFI.setFrameAddressIsTaken(true);
2809 
2810  SDLoc DL(Op);
2811  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2812  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2813 
2814  // If the back chain frame index has not been allocated yet, do so.
2816  int BackChainIdx = FI->getFramePointerSaveIndex();
2817  if (!BackChainIdx) {
2818  // By definition, the frame address is the address of the back chain.
2819  BackChainIdx = MFI.CreateFixedObject(8, -SystemZMC::CallFrameSize, false);
2820  FI->setFramePointerSaveIndex(BackChainIdx);
2821  }
2822  SDValue BackChain = DAG.getFrameIndex(BackChainIdx, PtrVT);
2823 
2824  // FIXME The frontend should detect this case.
2825  if (Depth > 0) {
2826  report_fatal_error("Unsupported stack frame traversal count");
2827  }
2828 
2829  return BackChain;
2830 }
2831 
2832 SDValue SystemZTargetLowering::lowerRETURNADDR(SDValue Op,
2833  SelectionDAG &DAG) const {
2834  MachineFunction &MF = DAG.getMachineFunction();
2835  MachineFrameInfo &MFI = MF.getFrameInfo();
2836  MFI.setReturnAddressIsTaken(true);
2837 
2839  return SDValue();
2840 
2841  SDLoc DL(Op);
2842  unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2843  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2844 
2845  // FIXME The frontend should detect this case.
2846  if (Depth > 0) {
2847  report_fatal_error("Unsupported stack frame traversal count");
2848  }
2849 
2850  // Return R14D, which has the return address. Mark it an implicit live-in.
2851  unsigned LinkReg = MF.addLiveIn(SystemZ::R14D, &SystemZ::GR64BitRegClass);
2852  return DAG.getCopyFromReg(DAG.getEntryNode(), DL, LinkReg, PtrVT);
2853 }
2854 
2855 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
2856  SelectionDAG &DAG) const {
2857  SDLoc DL(Op);
2858  SDValue In = Op.getOperand(0);
2859  EVT InVT = In.getValueType();
2860  EVT ResVT = Op.getValueType();
2861 
2862  // Convert loads directly. This is normally done by DAGCombiner,
2863  // but we need this case for bitcasts that are created during lowering
2864  // and which are then lowered themselves.
2865  if (auto *LoadN = dyn_cast<LoadSDNode>(In))
2866  if (ISD::isNormalLoad(LoadN))
2867  return DAG.getLoad(ResVT, DL, LoadN->getChain(), LoadN->getBasePtr(),
2868  LoadN->getMemOperand());
2869 
2870  if (InVT == MVT::i32 && ResVT == MVT::f32) {
2871  SDValue In64;
2872  if (Subtarget.hasHighWord()) {
2873  SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
2874  MVT::i64);
2875  In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
2876  MVT::i64, SDValue(U64, 0), In);
2877  } else {
2878  In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
2879  In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
2880  DAG.getConstant(32, DL, MVT::i64));
2881  }
2882  SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
2883  return DAG.getTargetExtractSubreg(SystemZ::subreg_r32,
2884  DL, MVT::f32, Out64);
2885  }
2886  if (InVT == MVT::f32 && ResVT == MVT::i32) {
2887  SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
2888  SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_r32, DL,
2889  MVT::f64, SDValue(U64, 0), In);
2890  SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
2891  if (Subtarget.hasHighWord())
2892  return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
2893  MVT::i32, Out64);
2894  SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
2895  DAG.getConstant(32, DL, MVT::i64));
2896  return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
2897  }
2898  llvm_unreachable("Unexpected bitcast combination");
2899 }
2900 
2901 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
2902  SelectionDAG &DAG) const {
2903  MachineFunction &MF = DAG.getMachineFunction();
2904  SystemZMachineFunctionInfo *FuncInfo =
2906  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2907 
2908  SDValue Chain = Op.getOperand(0);
2909  SDValue Addr = Op.getOperand(1);
2910  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2911  SDLoc DL(Op);
2912 
2913  // The initial values of each field.
2914  const unsigned NumFields = 4;
2915  SDValue Fields[NumFields] = {
2916  DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
2917  DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
2918  DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
2919  DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
2920  };
2921 
2922  // Store each field into its respective slot.
2923  SDValue MemOps[NumFields];
2924  unsigned Offset = 0;
2925  for (unsigned I = 0; I < NumFields; ++I) {
2926  SDValue FieldAddr = Addr;
2927  if (Offset != 0)
2928  FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
2929  DAG.getIntPtrConstant(Offset, DL));
2930  MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
2931  MachinePointerInfo(SV, Offset));
2932  Offset += 8;
2933  }
2934  return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2935 }
2936 
2937 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
2938  SelectionDAG &DAG) const {
2939  SDValue Chain = Op.getOperand(0);
2940  SDValue DstPtr = Op.getOperand(1);
2941  SDValue SrcPtr = Op.getOperand(2);
2942  const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2943  const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
2944  SDLoc DL(Op);
2945 
2946  return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32, DL),
2947  /*Align*/8, /*isVolatile*/false, /*AlwaysInline*/false,
2948  /*isTailCall*/false,
2949  MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
2950 }
2951 
2952 SDValue SystemZTargetLowering::
2953 lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
2954  const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
2955  MachineFunction &MF = DAG.getMachineFunction();
2956  bool RealignOpt = !MF.getFunction()-> hasFnAttribute("no-realign-stack");
2957  bool StoreBackchain = MF.getFunction()->hasFnAttribute("backchain");
2958 
2959  SDValue Chain = Op.getOperand(0);
2960  SDValue Size = Op.getOperand(1);
2961  SDValue Align = Op.getOperand(2);
2962  SDLoc DL(Op);
2963 
2964  // If user has set the no alignment function attribute, ignore
2965  // alloca alignments.
2966  uint64_t AlignVal = (RealignOpt ?
2967  dyn_cast<ConstantSDNode>(Align)->getZExtValue() : 0);
2968 
2969  uint64_t StackAlign = TFI->getStackAlignment();
2970  uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
2971  uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
2972 
2973  unsigned SPReg = getStackPointerRegisterToSaveRestore();
2974  SDValue NeededSpace = Size;
2975 
2976  // Get a reference to the stack pointer.
2977  SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
2978 
2979  // If we need a backchain, save it now.
2980  SDValue Backchain;
2981  if (StoreBackchain)
2982  Backchain = DAG.getLoad(MVT::i64, DL, Chain, OldSP, MachinePointerInfo());
2983 
2984  // Add extra space for alignment if needed.
2985  if (ExtraAlignSpace)
2986  NeededSpace = DAG.getNode(ISD::ADD, DL, MVT::i64, NeededSpace,
2987  DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
2988 
2989  // Get the new stack pointer value.
2990  SDValue NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, NeededSpace);
2991 
2992  // Copy the new stack pointer back.
2993  Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
2994 
2995  // The allocated data lives above the 160 bytes allocated for the standard
2996  // frame, plus any outgoing stack arguments. We don't know how much that
2997  // amounts to yet, so emit a special ADJDYNALLOC placeholder.
2998  SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
2999  SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
3000 
3001  // Dynamically realign if needed.
3002  if (RequiredAlign > StackAlign) {
3003  Result =
3004  DAG.getNode(ISD::ADD, DL, MVT::i64, Result,
3005  DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
3006  Result =
3007  DAG.getNode(ISD::AND, DL, MVT::i64, Result,
3008  DAG.getConstant(~(RequiredAlign - 1), DL, MVT::i64));
3009  }
3010 
3011  if (StoreBackchain)
3012  Chain = DAG.getStore(Chain, DL, Backchain, NewSP, MachinePointerInfo());
3013 
3014  SDValue Ops[2] = { Result, Chain };
3015  return DAG.getMergeValues(Ops, DL);
3016 }
3017 
3018 SDValue SystemZTargetLowering::lowerGET_DYNAMIC_AREA_OFFSET(
3019  SDValue Op, SelectionDAG &DAG) const {
3020  SDLoc DL(Op);
3021 
3022  return DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
3023 }
3024 
3025 SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
3026  SelectionDAG &DAG) const {
3027  EVT VT = Op.getValueType();
3028  SDLoc DL(Op);
3029  SDValue Ops[2];
3030  if (is32Bit(VT))
3031  // Just do a normal 64-bit multiplication and extract the results.
3032  // We define this so that it can be used for constant division.
3034  Op.getOperand(1), Ops[1], Ops[0]);
3035  else if (Subtarget.hasMiscellaneousExtensions2())
3036  // SystemZISD::SMUL_LOHI returns the low result in the odd register and
3037  // the high result in the even register. ISD::SMUL_LOHI is defined to
3038  // return the low half first, so the results are in reverse order.
3040  Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3041  else {
3042  // Do a full 128-bit multiplication based on SystemZISD::UMUL_LOHI:
3043  //
3044  // (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
3045  //
3046  // but using the fact that the upper halves are either all zeros
3047  // or all ones:
3048  //
3049  // (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
3050  //
3051  // and grouping the right terms together since they are quicker than the
3052  // multiplication:
3053  //
3054  // (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
3055  SDValue C63 = DAG.getConstant(63, DL, MVT::i64);
3056  SDValue LL = Op.getOperand(0);
3057  SDValue RL = Op.getOperand(1);
3058  SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
3059  SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
3060  // SystemZISD::UMUL_LOHI returns the low result in the odd register and
3061  // the high result in the even register. ISD::SMUL_LOHI is defined to
3062  // return the low half first, so the results are in reverse order.
3064  LL, RL, Ops[1], Ops[0]);
3065  SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
3066  SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
3067  SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
3068  Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
3069  }
3070  return DAG.getMergeValues(Ops, DL);
3071 }
3072 
3073 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
3074  SelectionDAG &DAG) const {
3075  EVT VT = Op.getValueType();
3076  SDLoc DL(Op);
3077  SDValue Ops[2];
3078  if (is32Bit(VT))
3079  // Just do a normal 64-bit multiplication and extract the results.
3080  // We define this so that it can be used for constant division.
3082  Op.getOperand(1), Ops[1], Ops[0]);
3083  else
3084  // SystemZISD::UMUL_LOHI returns the low result in the odd register and
3085  // the high result in the even register. ISD::UMUL_LOHI is defined to
3086  // return the low half first, so the results are in reverse order.
3088  Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3089  return DAG.getMergeValues(Ops, DL);
3090 }
3091 
3092 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
3093  SelectionDAG &DAG) const {
3094  SDValue Op0 = Op.getOperand(0);
3095  SDValue Op1 = Op.getOperand(1);
3096  EVT VT = Op.getValueType();
3097  SDLoc DL(Op);
3098 
3099  // We use DSGF for 32-bit division. This means the first operand must
3100  // always be 64-bit, and the second operand should be 32-bit whenever
3101  // that is possible, to improve performance.
3102  if (is32Bit(VT))
3103  Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
3104  else if (DAG.ComputeNumSignBits(Op1) > 32)
3105  Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
3106 
3107  // DSG(F) returns the remainder in the even register and the
3108  // quotient in the odd register.
3109  SDValue Ops[2];
3110  lowerGR128Binary(DAG, DL, VT, SystemZISD::SDIVREM, Op0, Op1, Ops[1], Ops[0]);
3111  return DAG.getMergeValues(Ops, DL);
3112 }
3113 
3114 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
3115  SelectionDAG &DAG) const {
3116  EVT VT = Op.getValueType();
3117  SDLoc DL(Op);
3118 
3119  // DL(G) returns the remainder in the even register and the
3120  // quotient in the odd register.
3121  SDValue Ops[2];
3123  Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3124  return DAG.getMergeValues(Ops, DL);
3125 }
3126 
3127 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
3128  assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
3129 
3130  // Get the known-zero masks for each operand.
3131  SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
3132  KnownBits Known[2];
3133  DAG.computeKnownBits(Ops[0], Known[0]);
3134  DAG.computeKnownBits(Ops[1], Known[1]);
3135 
3136  // See if the upper 32 bits of one operand and the lower 32 bits of the
3137  // other are known zero. They are the low and high operands respectively.
3138  uint64_t Masks[] = { Known[0].Zero.getZExtValue(),
3139  Known[1].Zero.getZExtValue() };
3140  unsigned High, Low;
3141  if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
3142  High = 1, Low = 0;
3143  else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
3144  High = 0, Low = 1;
3145  else
3146  return Op;
3147 
3148  SDValue LowOp = Ops[Low];
3149  SDValue HighOp = Ops[High];
3150 
3151  // If the high part is a constant, we're better off using IILH.
3152  if (HighOp.getOpcode() == ISD::Constant)
3153  return Op;
3154 
3155  // If the low part is a constant that is outside the range of LHI,
3156  // then we're better off using IILF.
3157  if (LowOp.getOpcode() == ISD::Constant) {
3158  int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
3159  if (!isInt<16>(Value))
3160  return Op;
3161  }
3162 
3163  // Check whether the high part is an AND that doesn't change the
3164  // high 32 bits and just masks out low bits. We can skip it if so.
3165  if (HighOp.getOpcode() == ISD::AND &&
3166  HighOp.getOperand(1).getOpcode() == ISD::Constant) {
3167  SDValue HighOp0 = HighOp.getOperand(0);
3168  uint64_t Mask = cast<ConstantSDNode>(HighOp.getOperand(1))->getZExtValue();
3169  if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
3170  HighOp = HighOp0;
3171  }
3172 
3173  // Take advantage of the fact that all GR32 operations only change the
3174  // low 32 bits by truncating Low to an i32 and inserting it directly
3175  // using a subreg. The interesting cases are those where the truncation
3176  // can be folded.
3177  SDLoc DL(Op);
3178  SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
3179  return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
3180  MVT::i64, HighOp, Low32);
3181 }
3182 
3183 SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op,
3184  SelectionDAG &DAG) const {
3185  EVT VT = Op.getValueType();
3186  SDLoc DL(Op);
3187  Op = Op.getOperand(0);
3188 
3189  // Handle vector types via VPOPCT.
3190  if (VT.isVector()) {
3191  Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op);
3192  Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op);
3193  switch (VT.getScalarSizeInBits()) {
3194  case 8:
3195  break;
3196  case 16: {
3197  Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
3198  SDValue Shift = DAG.getConstant(8, DL, MVT::i32);
3199  SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift);
3200  Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
3201  Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift);
3202  break;
3203  }
3204  case 32: {
3206  DAG.getConstant(0, DL, MVT::i32));
3207  Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
3208  break;
3209  }
3210  case 64: {
3212  DAG.getConstant(0, DL, MVT::i32));
3213  Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp);
3214  Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
3215  break;
3216  }
3217  default:
3218  llvm_unreachable("Unexpected type");
3219  }
3220  return Op;
3221  }
3222 
3223  // Get the known-zero mask for the operand.
3224  KnownBits Known;
3225  DAG.computeKnownBits(Op, Known);
3226  unsigned NumSignificantBits = (~Known.Zero).getActiveBits();
3227  if (NumSignificantBits == 0)
3228  return DAG.getConstant(0, DL, VT);
3229 
3230  // Skip known-zero high parts of the operand.
3231  int64_t OrigBitSize = VT.getSizeInBits();
3232  int64_t BitSize = (int64_t)1 << Log2_32_Ceil(NumSignificantBits);
3233  BitSize = std::min(BitSize, OrigBitSize);
3234 
3235  // The POPCNT instruction counts the number of bits in each byte.
3236  Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op);
3237  Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op);
3238  Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
3239 
3240  // Add up per-byte counts in a binary tree. All bits of Op at
3241  // position larger than BitSize remain zero throughout.
3242  for (int64_t I = BitSize / 2; I >= 8; I = I / 2) {
3243  SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT));
3244  if (BitSize != OrigBitSize)
3245  Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp,
3246  DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT));
3247  Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
3248  }
3249 
3250  // Extract overall result from high byte.
3251  if (BitSize > 8)
3252  Op = DAG.getNode(ISD::SRL, DL, VT, Op,
3253  DAG.getConstant(BitSize - 8, DL, VT));
3254 
3255  return Op;
3256 }
3257 
3258 SDValue SystemZTargetLowering::lowerATOMIC_FENCE(SDValue Op,
3259  SelectionDAG &DAG) const {
3260  SDLoc DL(Op);
3261  AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
3262  cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
3263  SyncScope::ID FenceSSID = static_cast<SyncScope::ID>(
3264  cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
3265 
3266  // The only fence that needs an instruction is a sequentially-consistent
3267  // cross-thread fence.
3268  if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
3269  FenceSSID == SyncScope::System) {
3270  return SDValue(DAG.getMachineNode(SystemZ::Serialize, DL, MVT::Other,
3271  Op.getOperand(0)),
3272  0);
3273  }
3274 
3275  // MEMBARRIER is a compiler barrier; it codegens to a no-op.
3276  return DAG.getNode(SystemZISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
3277 }
3278 
3279 // Op is an atomic load. Lower it into a serialization followed
3280 // by a normal volatile load.
3281 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
3282  SelectionDAG &DAG) const {
3283  auto *Node = cast<AtomicSDNode>(Op.getNode());
3284  SDValue Chain = SDValue(DAG.getMachineNode(SystemZ::Serialize, SDLoc(Op),
3285  MVT::Other, Node->getChain()), 0);
3286  return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), Op.getValueType(),
3287  Chain, Node->getBasePtr(),
3288  Node->getMemoryVT(), Node->getMemOperand());
3289 }
3290 
3291 // Op is an atomic store. Lower it into a normal volatile store followed
3292 // by a serialization.
3293 SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
3294  SelectionDAG &DAG) const {
3295  auto *Node = cast<AtomicSDNode>(Op.getNode());
3296  SDValue Chain = DAG.getTruncStore(Node->getChain(), SDLoc(Op), Node->getVal(),
3297  Node->getBasePtr(), Node->getMemoryVT(),
3298  Node->getMemOperand());
3299  return SDValue(DAG.getMachineNode(SystemZ::Serialize, SDLoc(Op), MVT::Other,
3300  Chain), 0);
3301 }
3302 
3303 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation. Lower the first
3304 // two into the fullword ATOMIC_LOADW_* operation given by Opcode.
3305 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op,
3306  SelectionDAG &DAG,
3307  unsigned Opcode) const {
3308  auto *Node = cast<AtomicSDNode>(Op.getNode());
3309 
3310  // 32-bit operations need no code outside the main loop.
3311  EVT NarrowVT = Node->getMemoryVT();
3312  EVT WideVT = MVT::i32;
3313  if (NarrowVT == WideVT)
3314  return Op;
3315 
3316  int64_t BitSize = NarrowVT.getSizeInBits();
3317  SDValue ChainIn = Node->getChain();
3318  SDValue Addr = Node->getBasePtr();
3319  SDValue Src2 = Node->getVal();
3320  MachineMemOperand *MMO = Node->getMemOperand();
3321  SDLoc DL(Node);
3322  EVT PtrVT = Addr.getValueType();
3323 
3324  // Convert atomic subtracts of constants into additions.
3325  if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
3326  if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
3328  Src2 = DAG.getConstant(-Const->getSExtValue(), DL, Src2.getValueType());
3329  }
3330 
3331  // Get the address of the containing word.
3332  SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
3333  DAG.getConstant(-4, DL, PtrVT));
3334 
3335  // Get the number of bits that the word must be rotated left in order
3336  // to bring the field to the top bits of a GR32.
3337  SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
3338  DAG.getConstant(3, DL, PtrVT));
3339  BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
3340 
3341  // Get the complementing shift amount, for rotating a field in the top
3342  // bits back to its proper position.
3343  SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
3344  DAG.getConstant(0, DL, WideVT), BitShift);
3345 
3346  // Extend the source operand to 32 bits and prepare it for the inner loop.
3347  // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
3348  // operations require the source to be shifted in advance. (This shift
3349  // can be folded if the source is constant.) For AND and NAND, the lower
3350  // bits must be set, while for other opcodes they should be left clear.
3351  if (Opcode != SystemZISD::ATOMIC_SWAPW)
3352  Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
3353  DAG.getConstant(32 - BitSize, DL, WideVT));
3354  if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
3356  Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
3357  DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT));
3358 
3359  // Construct the ATOMIC_LOADW_* node.
3360  SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
3361  SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
3362  DAG.getConstant(BitSize, DL, WideVT) };
3363  SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
3364  NarrowVT, MMO);
3365 
3366  // Rotate the result of the final CS so that the field is in the lower
3367  // bits of a GR32, then truncate it.
3368  SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
3369  DAG.getConstant(BitSize, DL, WideVT));
3370  SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
3371 
3372  SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
3373  return DAG.getMergeValues(RetOps, DL);
3374 }
3375 
3376 // Op is an ATOMIC_LOAD_SUB operation. Lower 8- and 16-bit operations
3377 // into ATOMIC_LOADW_SUBs and decide whether to convert 32- and 64-bit
3378 // operations into additions.
3379 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
3380  SelectionDAG &DAG) const {
3381  auto *Node = cast<AtomicSDNode>(Op.getNode());
3382  EVT MemVT = Node->getMemoryVT();
3383  if (MemVT == MVT::i32 || MemVT == MVT::i64) {
3384  // A full-width operation.
3385  assert(Op.getValueType() == MemVT && "Mismatched VTs");
3386  SDValue Src2 = Node->getVal();
3387  SDValue NegSrc2;
3388  SDLoc DL(Src2);
3389 
3390  if (auto *Op2 = dyn_cast<ConstantSDNode>(Src2)) {
3391  // Use an addition if the operand is constant and either LAA(G) is
3392  // available or the negative value is in the range of A(G)FHI.
3393  int64_t Value = (-Op2->getAPIntValue()).getSExtValue();
3394  if (isInt<32>(Value) || Subtarget.hasInterlockedAccess1())
3395  NegSrc2 = DAG.getConstant(Value, DL, MemVT);
3396  } else if (Subtarget.hasInterlockedAccess1())
3397  // Use LAA(G) if available.
3398  NegSrc2 = DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT),
3399  Src2);
3400 
3401  if (NegSrc2.getNode())
3402  return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT,
3403  Node->getChain(), Node->getBasePtr(), NegSrc2,
3404  Node->getMemOperand());
3405 
3406  // Use the node as-is.
3407  return Op;
3408  }
3409 
3410  return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
3411 }
3412 
3413 // Node is an 8- or 16-bit ATOMIC_CMP_SWAP operation. Lower the first two
3414 // into a fullword ATOMIC_CMP_SWAPW operation.
3415 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
3416  SelectionDAG &DAG) const {
3417  auto *Node = cast<AtomicSDNode>(Op.getNode());
3418 
3419  // We have native support for 32-bit compare and swap.
3420  EVT NarrowVT = Node->getMemoryVT();
3421  EVT WideVT = MVT::i32;
3422  if (NarrowVT == WideVT)
3423  return Op;
3424 
3425  int64_t BitSize = NarrowVT.getSizeInBits();
3426  SDValue ChainIn = Node->getOperand(0);
3427  SDValue Addr = Node->getOperand(1);
3428  SDValue CmpVal = Node->getOperand(2);
3429  SDValue SwapVal = Node->getOperand(3);
3430  MachineMemOperand *MMO = Node->getMemOperand();
3431  SDLoc DL(Node);
3432  EVT PtrVT = Addr.getValueType();
3433 
3434  // Get the address of the containing word.
3435  SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
3436  DAG.getConstant(-4, DL, PtrVT));
3437 
3438  // Get the number of bits that the word must be rotated left in order
3439  // to bring the field to the top bits of a GR32.
3440  SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
3441  DAG.getConstant(3, DL, PtrVT));
3442  BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
3443 
3444  // Get the complementing shift amount, for rotating a field in the top
3445  // bits back to its proper position.
3446  SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
3447  DAG.getConstant(0, DL, WideVT), BitShift);
3448 
3449  // Construct the ATOMIC_CMP_SWAPW node.
3450  SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
3451  SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
3452  NegBitShift, DAG.getConstant(BitSize, DL, WideVT) };
3454  VTList, Ops, NarrowVT, MMO);
3455  return AtomicOp;
3456 }
3457 
3458 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
3459  SelectionDAG &DAG) const {
3460  MachineFunction &MF = DAG.getMachineFunction();
3461  MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
3462  return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
3463  SystemZ::R15D, Op.getValueType());
3464 }
3465 
3466 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
3467  SelectionDAG &DAG) const {
3468  MachineFunction &MF = DAG.getMachineFunction();
3469  MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
3470  bool StoreBackchain = MF.getFunction()->hasFnAttribute("backchain");
3471 
3472  SDValue Chain = Op.getOperand(0);
3473  SDValue NewSP = Op.getOperand(1);
3474  SDValue Backchain;
3475  SDLoc DL(Op);
3476 
3477  if (StoreBackchain) {
3478  SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, MVT::i64);
3479  Backchain = DAG.getLoad(MVT::i64, DL, Chain, OldSP, MachinePointerInfo());
3480  }
3481 
3482  Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R15D, NewSP);
3483 
3484  if (StoreBackchain)
3485  Chain = DAG.getStore(Chain, DL, Backchain, NewSP, MachinePointerInfo());
3486 
3487  return Chain;
3488 }
3489 
3490 SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
3491  SelectionDAG &DAG) const {
3492  bool IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3493  if (!IsData)
3494  // Just preserve the chain.
3495  return Op.getOperand(0);
3496 
3497  SDLoc DL(Op);
3498  bool IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
3499  unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
3500  auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
3501  SDValue Ops[] = {
3502  Op.getOperand(0),
3503  DAG.getConstant(Code, DL, MVT::i32),
3504  Op.getOperand(1)
3505  };
3507  Node->getVTList(), Ops,
3508  Node->getMemoryVT(), Node->getMemOperand());
3509 }
3510 
3511 // Return an i32 that contains the value of CC immediately after After,
3512 // whose final operand must be MVT::Glue.
3513 static SDValue getCCResult(SelectionDAG &DAG, SDNode *After) {
3514  SDLoc DL(After);
3515  SDValue Glue = SDValue(After, After->getNumValues() - 1);
3516  SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
3517  return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM,
3519 }
3520 
3521 SDValue
3522 SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
3523  SelectionDAG &DAG) const {
3524  unsigned Opcode, CCValid;
3525  if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) {
3526  assert(Op->getNumValues() == 2 && "Expected only CC result and chain");
3527  SDValue Glued = emitIntrinsicWithChainAndGlue(DAG, Op, Opcode);
3528  SDValue CC = getCCResult(DAG, Glued.getNode());
3529  DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC);
3530  return SDValue();
3531  }
3532 
3533  return SDValue();
3534 }
3535 
3536 SDValue
3537 SystemZTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
3538  SelectionDAG &DAG) const {
3539  unsigned Opcode, CCValid;
3540  if (isIntrinsicWithCC(Op, Opcode, CCValid)) {
3541  SDValue Glued = emitIntrinsicWithGlue(DAG, Op, Opcode);
3542  SDValue CC = getCCResult(DAG, Glued.getNode());
3543  if (Op->getNumValues() == 1)
3544  return CC;
3545  assert(Op->getNumValues() == 2 && "Expected a CC and non-CC result");
3546  return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), Op->getVTList(), Glued,
3547  CC);
3548  }
3549 
3550  unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3551  switch (Id) {
3552  case Intrinsic::thread_pointer:
3553  return lowerThreadPointer(SDLoc(Op), DAG);
3554 
3555  case Intrinsic::s390_vpdi:
3556  return DAG.getNode(SystemZISD::PERMUTE_DWORDS, SDLoc(Op), Op.getValueType(),
3557  Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3558 
3559  case Intrinsic::s390_vperm:
3560  return DAG.getNode(SystemZISD::PERMUTE, SDLoc(Op), Op.getValueType(),
3561  Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3562 
3563  case Intrinsic::s390_vuphb:
3564  case Intrinsic::s390_vuphh:
3565  case Intrinsic::s390_vuphf:
3566  return DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(Op), Op.getValueType(),
3567  Op.getOperand(1));
3568 
3569  case Intrinsic::s390_vuplhb:
3570  case Intrinsic::s390_vuplhh:
3571  case Intrinsic::s390_vuplhf:
3572  return DAG.getNode(SystemZISD::UNPACKL_HIGH, SDLoc(Op), Op.getValueType(),
3573  Op.getOperand(1));
3574 
3575  case Intrinsic::s390_vuplb:
3576  case Intrinsic::s390_vuplhw:
3577  case Intrinsic::s390_vuplf:
3578  return DAG.getNode(SystemZISD::UNPACK_LOW, SDLoc(Op), Op.getValueType(),
3579  Op.getOperand(1));
3580 
3581  case Intrinsic::s390_vupllb:
3582  case Intrinsic::s390_vupllh:
3583  case Intrinsic::s390_vupllf:
3584  return DAG.getNode(SystemZISD::UNPACKL_LOW, SDLoc(Op), Op.getValueType(),
3585  Op.getOperand(1));
3586 
3587  case Intrinsic::s390_vsumb:
3588  case Intrinsic::s390_vsumh:
3589  case Intrinsic::s390_vsumgh:
3590  case Intrinsic::s390_vsumgf:
3591  case Intrinsic::s390_vsumqf:
3592  case Intrinsic::s390_vsumqg:
3593  return DAG.getNode(SystemZISD::VSUM, SDLoc(Op), Op.getValueType(),
3594  Op.getOperand(1), Op.getOperand(2));
3595  }
3596 
3597  return SDValue();
3598 }
3599 
3600 namespace {
3601 // Says that SystemZISD operation Opcode can be used to perform the equivalent
3602 // of a VPERM with permute vector Bytes. If Opcode takes three operands,
3603 // Operand is the constant third operand, otherwise it is the number of
3604 // bytes in each element of the result.
3605 struct Permute {
3606  unsigned Opcode;
3607  unsigned Operand;
3608  unsigned char Bytes[SystemZ::VectorBytes];
3609 };
3610 }
3611 
3612 static const Permute PermuteForms[] = {
3613  // VMRHG
3615  { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } },
3616  // VMRHF
3618  { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } },
3619  // VMRHH
3621  { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } },
3622  // VMRHB
3624  { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } },
3625  // VMRLG
3626  { SystemZISD::MERGE_LOW, 8,
3627  { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } },
3628  // VMRLF
3629  { SystemZISD::MERGE_LOW, 4,
3630  { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
3631  // VMRLH
3632  { SystemZISD::MERGE_LOW, 2,
3633  { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
3634  // VMRLB
3635  { SystemZISD::MERGE_LOW, 1,
3636  { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
3637  // VPKG
3638  { SystemZISD::PACK, 4,
3639  { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } },
3640  // VPKF
3641  { SystemZISD::PACK, 2,
3642  { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
3643  // VPKH
3644  { SystemZISD::PACK, 1,
3645  { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
3646  // VPDI V1, V2, 4 (low half of V1, high half of V2)
3648  { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } },
3649  // VPDI V1, V2, 1 (high half of V1, low half of V2)
3651  { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } }
3652 };
3653 
3654 // Called after matching a vector shuffle against a particular pattern.
3655 // Both the original shuffle and the pattern have two vector operands.
3656 // OpNos[0] is the operand of the original shuffle that should be used for
3657 // operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything.
3658 // OpNos[1] is the same for operand 1 of the pattern. Resolve these -1s and
3659 // set OpNo0 and OpNo1 to the shuffle operands that should actually be used
3660 // for operands 0 and 1 of the pattern.
3661 static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) {
3662  if (OpNos[0] < 0) {
3663  if (OpNos[1] < 0)
3664  return false;
3665  OpNo0 = OpNo1 = OpNos[1];
3666  } else if (OpNos[1] < 0) {
3667  OpNo0 = OpNo1 = OpNos[0];
3668  } else {
3669  OpNo0 = OpNos[0];
3670  OpNo1 = OpNos[1];
3671  }
3672  return true;
3673 }
3674 
3675 // Bytes is a VPERM-like permute vector, except that -1 is used for
3676 // undefined bytes. Return true if the VPERM can be implemented using P.
3677 // When returning true set OpNo0 to the VPERM operand that should be
3678 // used for operand 0 of P and likewise OpNo1 for operand 1 of P.
3679 //
3680 // For example, if swapping the VPERM operands allows P to match, OpNo0
3681 // will be 1 and OpNo1 will be 0. If instead Bytes only refers to one
3682 // operand, but rewriting it to use two duplicated operands allows it to
3683 // match P, then OpNo0 and OpNo1 will be the same.
3684 static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P,
3685  unsigned &OpNo0, unsigned &OpNo1) {
3686  int OpNos[] = { -1, -1 };
3687  for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
3688  int Elt = Bytes[I];
3689  if (Elt >= 0) {
3690  // Make sure that the two permute vectors use the same suboperand
3691  // byte number. Only the operand numbers (the high bits) are
3692  // allowed to differ.
3693  if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1))
3694  return false;
3695  int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes;
3696  int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes;
3697  // Make sure that the operand mappings are consistent with previous
3698  // elements.
3699  if (OpNos[ModelOpNo] == 1 - RealOpNo)
3700  return false;
3701  OpNos[ModelOpNo] = RealOpNo;
3702  }
3703  }
3704  return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
3705 }
3706 
3707 // As above, but search for a matching permute.
3708 static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes,
3709  unsigned &OpNo0, unsigned &OpNo1) {
3710  for (auto &P : PermuteForms)
3711  if (matchPermute(Bytes, P, OpNo0, OpNo1))
3712  return &P;
3713  return nullptr;
3714 }
3715 
3716 // Bytes is a VPERM-like permute vector, except that -1 is used for
3717 // undefined bytes. This permute is an operand of an outer permute.
3718 // See whether redistributing the -1 bytes gives a shuffle that can be
3719 // implemented using P. If so, set Transform to a VPERM-like permute vector
3720 // that, when applied to the result of P, gives the original permute in Bytes.
3721 static bool matchDoublePermute(const SmallVectorImpl<int> &Bytes,
3722  const Permute &P,
3723  SmallVectorImpl<int> &Transform) {
3724  unsigned To = 0;
3725  for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) {
3726  int Elt = Bytes[From];
3727  if (Elt < 0)
3728  // Byte number From of the result is undefined.
3729  Transform[From] = -1;
3730  else {
3731  while (P.Bytes[To] != Elt) {
3732  To += 1;
3733  if (To == SystemZ::VectorBytes)
3734  return false;
3735  }
3736  Transform[From] = To;
3737  }
3738  }
3739  return true;
3740 }
3741 
3742 // As above, but search for a matching permute.
3743 static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes,
3744  SmallVectorImpl<int> &Transform) {
3745  for (auto &P : PermuteForms)
3746  if (matchDoublePermute(Bytes, P, Transform))
3747  return &P;
3748  return nullptr;
3749 }
3750 
3751 // Convert the mask of the given VECTOR_SHUFFLE into a byte-level mask,
3752 // as if it had type vNi8.
3754  SmallVectorImpl<int> &Bytes) {
3755  EVT VT = VSN->getValueType(0);
3756  unsigned NumElements = VT.getVectorNumElements();
3757  unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3758  Bytes.resize(NumElements * BytesPerElement, -1);
3759  for (unsigned I = 0; I < NumElements; ++I) {
3760  int Index = VSN->getMaskElt(I);
3761  if (Index >= 0)
3762  for (unsigned J = 0; J < BytesPerElement; ++J)
3763  Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
3764  }
3765 }
3766 
3767 // Bytes is a VPERM-like permute vector, except that -1 is used for
3768 // undefined bytes. See whether bytes [Start, Start + BytesPerElement) of
3769 // the result come from a contiguous sequence of bytes from one input.
3770 // Set Base to the selector for the first byte if so.
3771 static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start,
3772  unsigned BytesPerElement, int &Base) {
3773  Base = -1;
3774  for (unsigned I = 0; I < BytesPerElement; ++I) {
3775  if (Bytes[Start + I] >= 0) {
3776  unsigned Elem = Bytes[Start + I];
3777  if (Base < 0) {
3778  Base = Elem - I;
3779  // Make sure the bytes would come from one input operand.
3780  if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size())
3781  return false;
3782  } else if (unsigned(Base) != Elem - I)
3783  return false;
3784  }
3785  }
3786  return true;
3787 }
3788 
3789 // Bytes is a VPERM-like permute vector, except that -1 is used for
3790 // undefined bytes. Return true if it can be performed using VSLDI.
3791 // When returning true, set StartIndex to the shift amount and OpNo0
3792 // and OpNo1 to the VPERM operands that should be used as the first
3793 // and second shift operand respectively.
3794 static bool isShlDoublePermute(const SmallVectorImpl<int> &Bytes,
3795  unsigned &StartIndex, unsigned &OpNo0,
3796  unsigned &OpNo1) {
3797  int OpNos[] = { -1, -1 };
3798  int Shift = -1;
3799  for (unsigned I = 0; I < 16; ++I) {
3800  int Index = Bytes[I];
3801  if (Index >= 0) {
3802  int ExpectedShift = (Index - I) % SystemZ::VectorBytes;
3803  int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes;
3804  int RealOpNo = unsigned(Index) / SystemZ::VectorBytes;
3805  if (Shift < 0)
3806  Shift = ExpectedShift;
3807  else if (Shift != ExpectedShift)
3808  return false;
3809  // Make sure that the operand mappings are consistent with previous
3810  // elements.
3811  if (OpNos[ModelOpNo] == 1 - RealOpNo)
3812  return false;
3813  OpNos[ModelOpNo] = RealOpNo;
3814  }
3815  }
3816  StartIndex = Shift;
3817  return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
3818 }
3819 
3820 // Create a node that performs P on operands Op0 and Op1, casting the
3821 // operands to the appropriate type. The type of the result is determined by P.
3822 static SDValue getPermuteNode(SelectionDAG &DAG, const SDLoc &DL,
3823  const Permute &P, SDValue Op0, SDValue Op1) {
3824  // VPDI (PERMUTE_DWORDS) always operates on v2i64s. The input
3825  // elements of a PACK are twice as wide as the outputs.
3826  unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 :
3827  P.Opcode == SystemZISD::PACK ? P.Operand * 2 :
3828  P.Operand);
3829  // Cast both operands to the appropriate type.
3830  MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8),
3831  SystemZ::VectorBytes / InBytes);
3832  Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0);
3833  Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1);
3834  SDValue Op;
3835  if (P.Opcode == SystemZISD::PERMUTE_DWORDS) {
3836  SDValue Op2 = DAG.getConstant(P.Operand, DL, MVT::i32);
3837  Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2);
3838  } else if (P.Opcode == SystemZISD::PACK) {
3839  MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8),
3840  SystemZ::VectorBytes / P.Operand);
3841  Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1);
3842  } else {
3843  Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1);
3844  }
3845  return Op;
3846 }
3847 
3848 // Bytes is a VPERM-like permute vector, except that -1 is used for
3849 // undefined bytes. Implement it on operands Ops[0] and Ops[1] using
3850 // VSLDI or VPERM.
3852  SDValue *Ops,
3853  const SmallVectorImpl<int> &Bytes) {
3854  for (unsigned I = 0; I < 2; ++I)
3855  Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]);
3856 
3857  // First see whether VSLDI can be used.
3858  unsigned StartIndex, OpNo0, OpNo1;
3859  if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1))
3860  return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0],
3861  Ops[OpNo1], DAG.getConstant(StartIndex, DL, MVT::i32));
3862 
3863  // Fall back on VPERM. Construct an SDNode for the permute vector.
3864  SDValue IndexNodes[SystemZ::VectorBytes];
3865  for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
3866  if (Bytes[I] >= 0)
3867  IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32);
3868  else
3869  IndexNodes[I] = DAG.getUNDEF(MVT::i32);
3870  SDValue Op2 = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
3871  return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0], Ops[1], Op2);
3872 }
3873 
3874 namespace {
3875 // Describes a general N-operand vector shuffle.
3876 struct GeneralShuffle {
3877  GeneralShuffle(EVT vt) : VT(vt) {}
3878  void addUndef();
3879  bool add(SDValue, unsigned);
3880  SDValue getNode(SelectionDAG &, const SDLoc &);
3881 
3882  // The operands of the shuffle.
3884 
3885  // Index I is -1 if byte I of the result is undefined. Otherwise the
3886  // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand
3887  // Bytes[I] / SystemZ::VectorBytes.
3889 
3890  // The type of the shuffle result.
3891  EVT VT;
3892 };
3893 }
3894 
3895 // Add an extra undefined element to the shuffle.
3896 void GeneralShuffle::addUndef() {
3897  unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3898  for (unsigned I = 0; I < BytesPerElement; ++I)
3899  Bytes.push_back(-1);
3900 }
3901 
3902 // Add an extra element to the shuffle, taking it from element Elem of Op.
3903 // A null Op indicates a vector input whose value will be calculated later;
3904 // there is at most one such input per shuffle and it always has the same
3905 // type as the result. Aborts and returns false if the source vector elements
3906 // of an EXTRACT_VECTOR_ELT are smaller than the destination elements. Per
3907 // LLVM they become implicitly extended, but this is rare and not optimized.
3908 bool GeneralShuffle::add(SDValue Op, unsigned Elem) {
3909  unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
3910 
3911  // The source vector can have wider elements than the result,
3912  // either through an explicit TRUNCATE or because of type legalization.
3913  // We want the least significant part.
3914  EVT FromVT = Op.getNode() ? Op.getValueType() : VT;
3915  unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize();
3916 
3917  // Return false if the source elements are smaller than their destination
3918  // elements.
3919  if (FromBytesPerElement < BytesPerElement)
3920  return false;
3921 
3922  unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes +
3923  (FromBytesPerElement - BytesPerElement));
3924 
3925  // Look through things like shuffles and bitcasts.
3926  while (Op.getNode()) {
3927  if (Op.getOpcode() == ISD::BITCAST)
3928  Op = Op.getOperand(0);
3929  else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) {
3930  // See whether the bytes we need come from a contiguous part of one
3931  // operand.
3933  getVPermMask(cast<ShuffleVectorSDNode>(Op), OpBytes);
3934  int NewByte;
3935  if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte))
3936  break;
3937  if (NewByte < 0) {
3938  addUndef();
3939  return true;
3940  }
3941  Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes);
3942  Byte = unsigned(NewByte) % SystemZ::VectorBytes;
3943  } else if (Op.isUndef()) {
3944  addUndef();
3945  return true;
3946  } else
3947  break;
3948  }
3949 
3950  // Make sure that the source of the extraction is in Ops.
3951  unsigned OpNo = 0;
3952  for (; OpNo < Ops.size(); ++OpNo)
3953  if (Ops[OpNo] == Op)
3954  break;
3955  if (OpNo == Ops.size())
3956  Ops.push_back(Op);
3957 
3958  // Add the element to Bytes.
3959  unsigned Base = OpNo * SystemZ::VectorBytes + Byte;
3960  for (unsigned I = 0; I < BytesPerElement; ++I)
3961  Bytes.push_back(Base + I);
3962 
3963  return true;
3964 }
3965 
3966 // Return SDNodes for the completed shuffle.
3967 SDValue GeneralShuffle::getNode(SelectionDAG &DAG, const SDLoc &DL) {
3968  assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector");
3969 
3970  if (Ops.size() == 0)
3971  return DAG.getUNDEF(VT);
3972 
3973  // Make sure that there are at least two shuffle operands.
3974  if (Ops.size() == 1)
3975  Ops.push_back(DAG.getUNDEF(MVT::v16i8));
3976 
3977  // Create a tree of shuffles, deferring root node until after the loop.
3978  // Try to redistribute the undefined elements of non-root nodes so that
3979  // the non-root shuffles match something like a pack or merge, then adjust
3980  // the parent node's permute vector to compensate for the new order.
3981  // Among other things, this copes with vectors like <2 x i16> that were
3982  // padded with undefined elements during type legalization.
3983  //
3984  // In the best case this redistribution will lead to the whole tree
3985  // using packs and merges. It should rarely be a loss in other cases.
3986  unsigned Stride = 1;
3987  for (; Stride * 2 < Ops.size(); Stride *= 2) {
3988  for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) {
3989  SDValue SubOps[] = { Ops[I], Ops[I + Stride] };
3990 
3991  // Create a mask for just these two operands.
3993  for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
3994  unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes;
3995  unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes;
3996  if (OpNo == I)
3997  NewBytes[J] = Byte;
3998  else if (OpNo == I + Stride)
3999  NewBytes[J] = SystemZ::VectorBytes + Byte;
4000  else
4001  NewBytes[J] = -1;
4002  }
4003  // See if it would be better to reorganize NewMask to avoid using VPERM.
4004  SmallVector<int, SystemZ::VectorBytes> NewBytesMap(SystemZ::VectorBytes);
4005  if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) {
4006  Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]);
4007  // Applying NewBytesMap to Ops[I] gets back to NewBytes.
4008  for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
4009  if (NewBytes[J] >= 0) {
4010  assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
4011  "Invalid double permute");
4012  Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J];
4013  } else
4014  assert(NewBytesMap[J] < 0 && "Invalid double permute");
4015  }
4016  } else {
4017  // Just use NewBytes on the operands.
4018  Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes);
4019  for (unsigned J = 0; J < SystemZ::VectorBytes; ++J)
4020  if (NewBytes[J] >= 0)
4021  Bytes[J] = I * SystemZ::VectorBytes + J;
4022  }
4023  }
4024  }
4025 
4026  // Now we just have 2 inputs. Put the second operand in Ops[1].
4027  if (Stride > 1) {
4028  Ops[1] = Ops[Stride];
4029  for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
4030  if (Bytes[I] >= int(SystemZ::VectorBytes))
4031  Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes;
4032  }
4033 
4034  // Look for an instruction that can do the permute without resorting
4035  // to VPERM.
4036  unsigned OpNo0, OpNo1;
4037  SDValue Op;
4038  if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1))
4039  Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]);
4040  else
4041  Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes);
4042  return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4043 }
4044 
4045 // Return true if the given BUILD_VECTOR is a scalar-to-vector conversion.
4046 static bool isScalarToVector(SDValue Op) {
4047  for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I)
4048  if (!Op.getOperand(I).isUndef())
4049  return false;
4050  return true;
4051 }
4052 
4053 // Return a vector of type VT that contains Value in the first element.
4054 // The other elements don't matter.
4055 static SDValue buildScalarToVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
4056  SDValue Value) {
4057  // If we have a constant, replicate it to all elements and let the
4058  // BUILD_VECTOR lowering take care of it.
4059  if (Value.getOpcode() == ISD::Constant ||
4060  Value.getOpcode() == ISD::ConstantFP) {
4062  return DAG.getBuildVector(VT, DL, Ops);
4063  }
4064  if (Value.isUndef())
4065  return DAG.getUNDEF(VT);
4066  return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
4067 }
4068 
4069 // Return a vector of type VT in which Op0 is in element 0 and Op1 is in
4070 // element 1. Used for cases in which replication is cheap.
4071 static SDValue buildMergeScalars(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
4072  SDValue Op0, SDValue Op1) {
4073  if (Op0.isUndef()) {
4074  if (Op1.isUndef())
4075  return DAG.getUNDEF(VT);
4076  return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1);
4077  }
4078  if (Op1.isUndef())
4079  return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0);
4080  return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT,
4081  buildScalarToVector(DAG, DL, VT, Op0),
4082  buildScalarToVector(DAG, DL, VT, Op1));
4083 }
4084 
4085 // Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64
4086 // vector for them.
4087 static SDValue joinDwords(SelectionDAG &DAG, const SDLoc &DL, SDValue Op0,
4088  SDValue Op1) {
4089  if (Op0.isUndef() && Op1.isUndef())
4090  return DAG.getUNDEF(MVT::v2i64);
4091  // If one of the two inputs is undefined then replicate the other one,
4092  // in order to avoid using another register unnecessarily.
4093  if (Op0.isUndef())
4094  Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
4095  else if (Op1.isUndef())
4096  Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
4097  else {
4098  Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
4099  Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
4100  }
4101  return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1);
4102 }
4103 
4104 // Try to represent constant BUILD_VECTOR node BVN using a
4105 // SystemZISD::BYTE_MASK-style mask. Store the mask value in Mask
4106 // on success.
4107 static bool tryBuildVectorByteMask(BuildVectorSDNode *BVN, uint64_t &Mask) {
4108  EVT ElemVT = BVN->getValueType(0).getVectorElementType();
4109  unsigned BytesPerElement = ElemVT.getStoreSize();
4110  for (unsigned I = 0, E = BVN->getNumOperands(); I != E; ++I) {
4111  SDValue Op = BVN->getOperand(I);
4112  if (!Op.isUndef()) {
4113  uint64_t Value;
4114  if (Op.getOpcode() == ISD::Constant)
4115  Value = dyn_cast<ConstantSDNode>(Op)->getZExtValue();
4116  else if (Op.getOpcode() == ISD::ConstantFP)
4117  Value = (dyn_cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt()
4118  .getZExtValue());
4119  else
4120  return false;
4121  for (unsigned J = 0; J < BytesPerElement; ++J) {
4122  uint64_t Byte = (Value >> (J * 8)) & 0xff;
4123  if (Byte == 0xff)
4124  Mask |= 1ULL << ((E - I - 1) * BytesPerElement + J);
4125  else if (Byte != 0)
4126  return false;
4127  }
4128  }
4129  }
4130  return true;
4131 }
4132 
4133 // Try to load a vector constant in which BitsPerElement-bit value Value
4134 // is replicated to fill the vector. VT is the type of the resulting
4135 // constant, which may have elements of a different size from BitsPerElement.
4136 // Return the SDValue of the constant on success, otherwise return
4137 // an empty value.
4139  const SystemZInstrInfo *TII,
4140  const SDLoc &DL, EVT VT, uint64_t Value,
4141  unsigned BitsPerElement) {
4142  // Signed 16-bit values can be replicated using VREPI.
4143  int64_t SignedValue = SignExtend64(Value, BitsPerElement);
4144  if (isInt<16>(SignedValue)) {
4145  MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement),
4146  SystemZ::VectorBits / BitsPerElement);
4147  SDValue Op = DAG.getNode(SystemZISD::REPLICATE, DL, VecVT,
4148  DAG.getConstant(SignedValue, DL, MVT::i32));
4149  return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4150  }
4151  // See whether rotating the constant left some N places gives a value that
4152  // is one less than a power of 2 (i.e. all zeros followed by all ones).
4153  // If so we can use VGM.
4154  unsigned Start, End;
4155  if (TII->isRxSBGMask(Value, BitsPerElement, Start, End)) {
4156  // isRxSBGMask returns the bit numbers for a full 64-bit value,
4157  // with 0 denoting 1 << 63 and 63 denoting 1. Convert them to
4158  // bit numbers for an BitsPerElement value, so that 0 denotes
4159  // 1 << (BitsPerElement-1).
4160  Start -= 64 - BitsPerElement;
4161  End -= 64 - BitsPerElement;
4162  MVT VecVT = MVT::getVectorVT(MVT::getIntegerVT(BitsPerElement),
4163  SystemZ::VectorBits / BitsPerElement);
4164  SDValue Op = DAG.getNode(SystemZISD::ROTATE_MASK, DL, VecVT,
4165  DAG.getConstant(Start, DL, MVT::i32),
4166  DAG.getConstant(End, DL, MVT::i32));
4167  return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4168  }
4169  return SDValue();
4170 }
4171 
4172 // If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually
4173 // better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for
4174 // the non-EXTRACT_VECTOR_ELT elements. See if the given BUILD_VECTOR
4175 // would benefit from this representation and return it if so.
4177  BuildVectorSDNode *BVN) {
4178  EVT VT = BVN->getValueType(0);
4179  unsigned NumElements = VT.getVectorNumElements();
4180 
4181  // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation
4182  // on byte vectors. If there are non-EXTRACT_VECTOR_ELT elements that still
4183  // need a BUILD_VECTOR, add an additional placeholder operand for that
4184  // BUILD_VECTOR and store its operands in ResidueOps.
4185  GeneralShuffle GS(VT);
4187  bool FoundOne = false;
4188  for (unsigned I = 0; I < NumElements; ++I) {
4189  SDValue Op = BVN->getOperand(I);
4190  if (Op.getOpcode() == ISD::TRUNCATE)
4191  Op = Op.getOperand(0);
4192  if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4193  Op.getOperand(1).getOpcode() == ISD::Constant) {
4194  unsigned Elem = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4195  if (!GS.add(Op.getOperand(0), Elem))
4196  return SDValue();
4197  FoundOne = true;
4198  } else if (Op.isUndef()) {
4199  GS.addUndef();
4200  } else {
4201  if (!GS.add(SDValue(), ResidueOps.size()))
4202  return SDValue();
4203  ResidueOps.push_back(BVN->getOperand(I));
4204  }
4205  }
4206 
4207  // Nothing to do if there are no EXTRACT_VECTOR_ELTs.
4208  if (!FoundOne)
4209  return SDValue();
4210 
4211  // Create the BUILD_VECTOR for the remaining elements, if any.
4212  if (!ResidueOps.empty()) {
4213  while (ResidueOps.size() < NumElements)
4214  ResidueOps.push_back(DAG.getUNDEF(ResidueOps[0].getValueType()));
4215  for (auto &Op : GS.Ops) {
4216  if (!Op.getNode()) {
4217  Op = DAG.getBuildVector(VT, SDLoc(BVN), ResidueOps);
4218  break;
4219  }
4220  }
4221  }
4222  return GS.getNode(DAG, SDLoc(BVN));
4223 }
4224 
4225 // Combine GPR scalar values Elems into a vector of type VT.
4226 static SDValue buildVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
4227  SmallVectorImpl<SDValue> &Elems) {
4228  // See whether there is a single replicated value.
4229  SDValue Single;
4230  unsigned int NumElements = Elems.size();
4231  unsigned int Count = 0;
4232  for (auto Elem : Elems) {
4233  if (!Elem.isUndef()) {
4234  if (!Single.getNode())
4235  Single = Elem;
4236  else if (Elem != Single) {
4237  Single = SDValue();
4238  break;
4239  }
4240  Count += 1;
4241  }
4242  }
4243  // There are three cases here:
4244  //
4245  // - if the only defined element is a loaded one, the best sequence
4246  // is a replicating load.
4247  //
4248  // - otherwise, if the only defined element is an i64 value, we will
4249  // end up with the same VLVGP sequence regardless of whether we short-cut
4250  // for replication or fall through to the later code.
4251  //
4252  // - otherwise, if the only defined element is an i32 or smaller value,
4253  // we would need 2 instructions to replicate it: VLVGP followed by VREPx.
4254  // This is only a win if the single defined element is used more than once.
4255  // In other cases we're better off using a single VLVGx.
4256  if (Single.getNode() && (Count > 1 || Single.getOpcode() == ISD::LOAD))
4257  return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single);
4258 
4259  // If all elements are loads, use VLREP/VLEs (below).
4260  bool AllLoads = true;
4261  for (auto Elem : Elems)
4262  if (Elem.getOpcode() != ISD::LOAD || cast<LoadSDNode>(Elem)->isIndexed()) {
4263  AllLoads = false;
4264  break;
4265  }
4266 
4267  // The best way of building a v2i64 from two i64s is to use VLVGP.
4268  if (VT == MVT::v2i64 && !AllLoads)
4269  return joinDwords(DAG, DL, Elems[0], Elems[1]);
4270 
4271  // Use a 64-bit merge high to combine two doubles.
4272  if (VT == MVT::v2f64 && !AllLoads)
4273  return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
4274 
4275  // Build v4f32 values directly from the FPRs:
4276  //
4277  // <Axxx> <Bxxx> <Cxxxx> <Dxxx>
4278  // V V VMRHF
4279  // <ABxx> <CDxx>
4280  // V VMRHG
4281  // <ABCD>
4282  if (VT == MVT::v4f32 && !AllLoads) {
4283  SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
4284  SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[2], Elems[3]);
4285  // Avoid unnecessary undefs by reusing the other operand.
4286  if (Op01.isUndef())
4287  Op01 = Op23;
4288  else if (Op23.isUndef())
4289  Op23 = Op01;
4290  // Merging identical replications is a no-op.
4291  if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23)
4292  return Op01;
4293  Op01 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op01);
4294  Op23 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op23);
4296  DL, MVT::v2i64, Op01, Op23);
4297  return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4298  }
4299 
4300  // Collect the constant terms.
4302  SmallVector<bool, SystemZ::VectorBytes> Done(NumElements, false);
4303 
4304  unsigned NumConstants = 0;
4305  for (unsigned I = 0; I < NumElements; ++I) {
4306  SDValue Elem = Elems[I];
4307  if (Elem.getOpcode() == ISD::Constant ||
4308  Elem.getOpcode() == ISD::ConstantFP) {
4309  NumConstants += 1;
4310  Constants[I] = Elem;
4311  Done[I] = true;
4312  }
4313  }
4314  // If there was at least one constant, fill in the other elements of
4315  // Constants with undefs to get a full vector constant and use that
4316  // as the starting point.
4317  SDValue Result;
4318  if (NumConstants > 0) {
4319  for (unsigned I = 0; I < NumElements; ++I)
4320  if (!Constants[I].getNode())
4321  Constants[I] = DAG.getUNDEF(Elems[I].getValueType());
4322  Result = DAG.getBuildVector(VT, DL, Constants);
4323  } else {
4324  // Otherwise try to use VLREP or VLVGP to start the sequence in order to
4325  // avoid a false dependency on any previous contents of the vector
4326  // register.
4327 
4328  // Use a VLREP if at least one element is a load.
4329  unsigned LoadElIdx = UINT_MAX;
4330  for (unsigned I = 0; I < NumElements; ++I)
4331  if (Elems[I].getOpcode() == ISD::LOAD &&
4332  cast<LoadSDNode>(Elems[I])->isUnindexed()) {
4333  LoadElIdx = I;
4334  break;
4335  }
4336  if (LoadElIdx != UINT_MAX) {
4337  Result = DAG.getNode(SystemZISD::REPLICATE, DL, VT, Elems[LoadElIdx]);
4338  Done[LoadElIdx] = true;
4339  } else {
4340  // Try to use VLVGP.
4341  unsigned I1 = NumElements / 2 - 1;
4342  unsigned I2 = NumElements - 1;
4343  bool Def1 = !Elems[I1].isUndef();
4344  bool Def2 = !Elems[I2].isUndef();
4345  if (Def1 || Def2) {
4346  SDValue Elem1 = Elems[Def1 ? I1 : I2];
4347  SDValue Elem2 = Elems[Def2 ? I2 : I1];
4348  Result = DAG.getNode(ISD::BITCAST, DL, VT,
4349  joinDwords(DAG, DL, Elem1, Elem2));
4350  Done[I1] = true;
4351  Done[I2] = true;
4352  } else
4353  Result = DAG.getUNDEF(VT);
4354  }
4355  }
4356 
4357  // Use VLVGx to insert the other elements.
4358  for (unsigned I = 0; I < NumElements; ++I)
4359  if (!Done[I] && !Elems[I].isUndef())
4360  Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I],
4361  DAG.getConstant(I, DL, MVT::i32));
4362  return Result;
4363 }
4364 
4365 SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op,
4366  SelectionDAG &DAG) const {
4367  const SystemZInstrInfo *TII =
4368  static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
4369  auto *BVN = cast<BuildVectorSDNode>(Op.getNode());
4370  SDLoc DL(Op);
4371  EVT VT = Op.getValueType();
4372 
4373  if (BVN->isConstant()) {
4374  // Try using VECTOR GENERATE BYTE MASK. This is the architecturally-
4375  // preferred way of creating all-zero and all-one vectors so give it
4376  // priority over other methods below.
4377  uint64_t Mask = 0;
4378  if (tryBuildVectorByteMask(BVN, Mask)) {
4380  DAG.getConstant(Mask, DL, MVT::i32));
4381  return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4382  }
4383 
4384  // Try using some form of replication.
4385  APInt SplatBits, SplatUndef;
4386  unsigned SplatBitSize;
4387  bool HasAnyUndefs;
4388  if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
4389  8, true) &&
4390  SplatBitSize <= 64) {
4391  // First try assuming that any undefined bits above the highest set bit
4392  // and below the lowest set bit are 1s. This increases the likelihood of
4393  // being able to use a sign-extended element value in VECTOR REPLICATE
4394  // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
4395  uint64_t SplatBitsZ = SplatBits.getZExtValue();
4396  uint64_t SplatUndefZ = SplatUndef.getZExtValue();
4397  uint64_t Lower = (SplatUndefZ
4398  & ((uint64_t(1) << findFirstSet(SplatBitsZ)) - 1));
4399  uint64_t Upper = (SplatUndefZ
4400  & ~((uint64_t(1) << findLastSet(SplatBitsZ)) - 1));
4401  uint64_t Value = SplatBitsZ | Upper | Lower;
4402  SDValue Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value,
4403  SplatBitSize);
4404  if (Op.getNode())
4405  return Op;
4406 
4407  // Now try assuming that any undefined bits between the first and
4408  // last defined set bits are set. This increases the chances of
4409  // using a non-wraparound mask.
4410  uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
4411  Value = SplatBitsZ | Middle;
4412  Op = tryBuildVectorReplicate(DAG, TII, DL, VT, Value, SplatBitSize);
4413  if (Op.getNode())
4414  return Op;
4415  }
4416 
4417  // Fall back to loading it from memory.
4418  return SDValue();
4419  }
4420 
4421  // See if we should use shuffles to construct the vector from other vectors.
4422  if (SDValue Res = tryBuildVectorShuffle(DAG, BVN))
4423  return Res;
4424 
4425  // Detect SCALAR_TO_VECTOR conversions.
4427  return buildScalarToVector(DAG, DL, VT, Op.getOperand(0));
4428 
4429  // Otherwise use buildVector to build the vector up from GPRs.
4430  unsigned NumElements = Op.getNumOperands();
4432  for (unsigned I = 0; I < NumElements; ++I)
4433  Ops[I] = Op.getOperand(I);
4434  return buildVector(DAG, DL, VT, Ops);
4435 }
4436 
4437 SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
4438  SelectionDAG &DAG) const {
4439  auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode());
4440  SDLoc DL(Op);
4441  EVT VT = Op.getValueType();
4442  unsigned NumElements = VT.getVectorNumElements();
4443 
4444  if (VSN->isSplat()) {
4445  SDValue Op0 = Op.getOperand(0);
4446  unsigned Index = VSN->getSplatIndex();
4447  assert(Index < VT.getVectorNumElements() &&
4448  "Splat index should be defined and in first operand");
4449  // See whether the value we're splatting is directly available as a scalar.
4450  if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
4451  Op0.getOpcode() == ISD::BUILD_VECTOR)
4452  return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index));
4453  // Otherwise keep it as a vector-to-vector operation.
4454  return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0),
4455  DAG.getConstant(Index, DL, MVT::i32));
4456  }
4457 
4458  GeneralShuffle GS(VT);
4459  for (unsigned I = 0; I < NumElements; ++I) {
4460  int Elt = VSN->getMaskElt(I);
4461  if (Elt < 0)
4462  GS.addUndef();
4463  else if (!GS.add(Op.getOperand(unsigned(Elt) / NumElements),
4464  unsigned(Elt) % NumElements))
4465  return SDValue();
4466  }
4467  return GS.getNode(DAG, SDLoc(VSN));
4468 }
4469 
4470 SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
4471  SelectionDAG &DAG) const {
4472  SDLoc DL(Op);
4473  // Just insert the scalar into element 0 of an undefined vector.
4474  return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL,
4475  Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
4476  Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32));
4477 }
4478 
4479 SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4480  SelectionDAG &DAG) const {
4481  // Handle insertions of floating-point values.
4482  SDLoc DL(Op);
4483  SDValue Op0 = Op.getOperand(0);
4484  SDValue Op1 = Op.getOperand(1);
4485  SDValue Op2 = Op.getOperand(2);
4486  EVT VT = Op.getValueType();
4487 
4488  // Insertions into constant indices of a v2f64 can be done using VPDI.
4489  // However, if the inserted value is a bitcast or a constant then it's
4490  // better to use GPRs, as below.
4491  if (VT == MVT::v2f64 &&
4492  Op1.getOpcode() != ISD::BITCAST &&
4493  Op1.getOpcode() != ISD::ConstantFP &&
4494  Op2.getOpcode() == ISD::Constant) {
4495  uint64_t Index = dyn_cast<ConstantSDNode>(Op2)->getZExtValue();
4496  unsigned Mask = VT.getVectorNumElements() - 1;
4497  if (Index <= Mask)
4498  return Op;
4499  }
4500 
4501  // Otherwise bitcast to the equivalent integer form and insert via a GPR.
4503  MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements());
4504  SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT,
4505  DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0),
4506  DAG.getNode(ISD::BITCAST, DL, IntVT, Op1), Op2);
4507  return DAG.getNode(ISD::BITCAST, DL, VT, Res);
4508 }
4509 
4510 SDValue
4511 SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4512  SelectionDAG &DAG) const {
4513  // Handle extractions of floating-point values.
4514  SDLoc DL(Op);
4515  SDValue Op0 = Op.getOperand(0);
4516  SDValue Op1 = Op.getOperand(1);
4517  EVT VT = Op.getValueType();
4518  EVT VecVT = Op0.getValueType();
4519 
4520  // Extractions of constant indices can be done directly.
4521  if (auto *CIndexN = dyn_cast<ConstantSDNode>(Op1)) {
4522  uint64_t Index = CIndexN->getZExtValue();
4523  unsigned Mask = VecVT.getVectorNumElements() - 1;
4524  if (Index <= Mask)
4525  return Op;
4526  }
4527 
4528  // Otherwise bitcast to the equivalent integer form and extract via a GPR.
4529  MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
4530  MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements());
4531  SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntVT,
4532  DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1);
4533  return DAG.getNode(ISD::BITCAST, DL, VT, Res);
4534 }
4535 
4536 SDValue
4537 SystemZTargetLowering::lowerExtendVectorInreg(SDValue Op, SelectionDAG &DAG,
4538  unsigned UnpackHigh) const {
4539  SDValue PackedOp = Op.getOperand(0);
4540  EVT OutVT = Op.getValueType();
4541  EVT InVT = PackedOp.getValueType();
4542  unsigned ToBits = OutVT.getScalarSizeInBits();
4543  unsigned FromBits = InVT.getScalarSizeInBits();
4544  do {
4545  FromBits *= 2;
4546  EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(FromBits),
4547  SystemZ::VectorBits / FromBits);
4548  PackedOp = DAG.getNode(UnpackHigh, SDLoc(PackedOp), OutVT, PackedOp);
4549  } while (FromBits != ToBits);
4550  return PackedOp;
4551 }
4552 
4553 SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG,
4554  unsigned ByScalar) const {
4555  // Look for cases where a vector shift can use the *_BY_SCALAR form.
4556  SDValue Op0 = Op.getOperand(0);
4557  SDValue Op1 = Op.getOperand(1);
4558  SDLoc DL(Op);
4559  EVT VT = Op.getValueType();
4560  unsigned ElemBitSize = VT.getScalarSizeInBits();
4561 
4562  // See whether the shift vector is a splat represented as BUILD_VECTOR.
4563  if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) {
4564  APInt SplatBits, SplatUndef;
4565  unsigned SplatBitSize;
4566  bool HasAnyUndefs;
4567  // Check for constant splats. Use ElemBitSize as the minimum element
4568  // width and reject splats that need wider elements.
4569  if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
4570  ElemBitSize, true) &&
4571  SplatBitSize == ElemBitSize) {
4572  SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff,
4573  DL, MVT::i32);
4574  return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4575  }
4576  // Check for variable splats.
4577  BitVector UndefElements;
4578  SDValue Splat = BVN->getSplatValue(&UndefElements);
4579  if (Splat) {
4580  // Since i32 is the smallest legal type, we either need a no-op
4581  // or a truncation.
4582  SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat);
4583  return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4584  }
4585  }
4586 
4587  // See whether the shift vector is a splat represented as SHUFFLE_VECTOR,
4588  // and the shift amount is directly available in a GPR.
4589  if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) {
4590  if (VSN->isSplat()) {
4591  SDValue VSNOp0 = VSN->getOperand(0);
4592  unsigned Index = VSN->getSplatIndex();
4593  assert(Index < VT.getVectorNumElements() &&
4594  "Splat index should be defined and in first operand");
4595  if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
4596  VSNOp0.getOpcode() == ISD::BUILD_VECTOR) {
4597  // Since i32 is the smallest legal type, we either need a no-op
4598  // or a truncation.
4599  SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
4600  VSNOp0.getOperand(Index));
4601  return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
4602  }
4603  }
4604  }
4605 
4606  // Otherwise just treat the current form as legal.
4607  return Op;
4608 }
4609 
4611  SelectionDAG &DAG) const {
4612  switch (Op.getOpcode()) {
4613  case ISD::FRAMEADDR:
4614  return lowerFRAMEADDR(Op, DAG);
4615  case ISD::RETURNADDR:
4616  return lowerRETURNADDR(Op, DAG);
4617  case ISD::BR_CC:
4618  return lowerBR_CC(Op, DAG);
4619  case ISD::SELECT_CC:
4620  return lowerSELECT_CC(Op, DAG);
4621  case ISD::SETCC:
4622  return lowerSETCC(Op, DAG);
4623  case ISD::GlobalAddress:
4624  return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
4625  case ISD::GlobalTLSAddress:
4626  return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
4627  case ISD::BlockAddress:
4628  return lowerBlockAddr