LLVM API Documentation

SystemZISelLowering.cpp
Go to the documentation of this file.
00001 //===-- SystemZISelLowering.cpp - SystemZ DAG lowering implementation -----===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the SystemZTargetLowering class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "SystemZISelLowering.h"
00015 #include "SystemZCallingConv.h"
00016 #include "SystemZConstantPoolValue.h"
00017 #include "SystemZMachineFunctionInfo.h"
00018 #include "SystemZTargetMachine.h"
00019 #include "llvm/CodeGen/CallingConvLower.h"
00020 #include "llvm/CodeGen/MachineInstrBuilder.h"
00021 #include "llvm/CodeGen/MachineRegisterInfo.h"
00022 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
00023 #include <cctype>
00024 
00025 using namespace llvm;
00026 
00027 #define DEBUG_TYPE "systemz-lower"
00028 
00029 namespace {
00030 // Represents a sequence for extracting a 0/1 value from an IPM result:
00031 // (((X ^ XORValue) + AddValue) >> Bit)
00032 struct IPMConversion {
00033   IPMConversion(unsigned xorValue, int64_t addValue, unsigned bit)
00034     : XORValue(xorValue), AddValue(addValue), Bit(bit) {}
00035 
00036   int64_t XORValue;
00037   int64_t AddValue;
00038   unsigned Bit;
00039 };
00040 
00041 // Represents information about a comparison.
00042 struct Comparison {
00043   Comparison(SDValue Op0In, SDValue Op1In)
00044     : Op0(Op0In), Op1(Op1In), Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
00045 
00046   // The operands to the comparison.
00047   SDValue Op0, Op1;
00048 
00049   // The opcode that should be used to compare Op0 and Op1.
00050   unsigned Opcode;
00051 
00052   // A SystemZICMP value.  Only used for integer comparisons.
00053   unsigned ICmpType;
00054 
00055   // The mask of CC values that Opcode can produce.
00056   unsigned CCValid;
00057 
00058   // The mask of CC values for which the original condition is true.
00059   unsigned CCMask;
00060 };
00061 } // end anonymous namespace
00062 
00063 // Classify VT as either 32 or 64 bit.
00064 static bool is32Bit(EVT VT) {
00065   switch (VT.getSimpleVT().SimpleTy) {
00066   case MVT::i32:
00067     return true;
00068   case MVT::i64:
00069     return false;
00070   default:
00071     llvm_unreachable("Unsupported type");
00072   }
00073 }
00074 
00075 // Return a version of MachineOperand that can be safely used before the
00076 // final use.
00077 static MachineOperand earlyUseOperand(MachineOperand Op) {
00078   if (Op.isReg())
00079     Op.setIsKill(false);
00080   return Op;
00081 }
00082 
00083 SystemZTargetLowering::SystemZTargetLowering(SystemZTargetMachine &tm)
00084   : TargetLowering(tm, new TargetLoweringObjectFileELF()),
00085     Subtarget(*tm.getSubtargetImpl()), TM(tm) {
00086   MVT PtrVT = getPointerTy();
00087 
00088   // Set up the register classes.
00089   if (Subtarget.hasHighWord())
00090     addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
00091   else
00092     addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
00093   addRegisterClass(MVT::i64,  &SystemZ::GR64BitRegClass);
00094   addRegisterClass(MVT::f32,  &SystemZ::FP32BitRegClass);
00095   addRegisterClass(MVT::f64,  &SystemZ::FP64BitRegClass);
00096   addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
00097 
00098   // Compute derived properties from the register classes
00099   computeRegisterProperties();
00100 
00101   // Set up special registers.
00102   setExceptionPointerRegister(SystemZ::R6D);
00103   setExceptionSelectorRegister(SystemZ::R7D);
00104   setStackPointerRegisterToSaveRestore(SystemZ::R15D);
00105 
00106   // TODO: It may be better to default to latency-oriented scheduling, however
00107   // LLVM's current latency-oriented scheduler can't handle physreg definitions
00108   // such as SystemZ has with CC, so set this to the register-pressure
00109   // scheduler, because it can.
00110   setSchedulingPreference(Sched::RegPressure);
00111 
00112   setBooleanContents(ZeroOrOneBooleanContent);
00113   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
00114 
00115   // Instructions are strings of 2-byte aligned 2-byte values.
00116   setMinFunctionAlignment(2);
00117 
00118   // Handle operations that are handled in a similar way for all types.
00119   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
00120        I <= MVT::LAST_FP_VALUETYPE;
00121        ++I) {
00122     MVT VT = MVT::SimpleValueType(I);
00123     if (isTypeLegal(VT)) {
00124       // Lower SET_CC into an IPM-based sequence.
00125       setOperationAction(ISD::SETCC, VT, Custom);
00126 
00127       // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
00128       setOperationAction(ISD::SELECT, VT, Expand);
00129 
00130       // Lower SELECT_CC and BR_CC into separate comparisons and branches.
00131       setOperationAction(ISD::SELECT_CC, VT, Custom);
00132       setOperationAction(ISD::BR_CC,     VT, Custom);
00133     }
00134   }
00135 
00136   // Expand jump table branches as address arithmetic followed by an
00137   // indirect jump.
00138   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
00139 
00140   // Expand BRCOND into a BR_CC (see above).
00141   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
00142 
00143   // Handle integer types.
00144   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
00145        I <= MVT::LAST_INTEGER_VALUETYPE;
00146        ++I) {
00147     MVT VT = MVT::SimpleValueType(I);
00148     if (isTypeLegal(VT)) {
00149       // Expand individual DIV and REMs into DIVREMs.
00150       setOperationAction(ISD::SDIV, VT, Expand);
00151       setOperationAction(ISD::UDIV, VT, Expand);
00152       setOperationAction(ISD::SREM, VT, Expand);
00153       setOperationAction(ISD::UREM, VT, Expand);
00154       setOperationAction(ISD::SDIVREM, VT, Custom);
00155       setOperationAction(ISD::UDIVREM, VT, Custom);
00156 
00157       // Lower ATOMIC_LOAD and ATOMIC_STORE into normal volatile loads and
00158       // stores, putting a serialization instruction after the stores.
00159       setOperationAction(ISD::ATOMIC_LOAD,  VT, Custom);
00160       setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
00161 
00162       // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
00163       // available, or if the operand is constant.
00164       setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
00165 
00166       // No special instructions for these.
00167       setOperationAction(ISD::CTPOP,           VT, Expand);
00168       setOperationAction(ISD::CTTZ,            VT, Expand);
00169       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
00170       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
00171       setOperationAction(ISD::ROTR,            VT, Expand);
00172 
00173       // Use *MUL_LOHI where possible instead of MULH*.
00174       setOperationAction(ISD::MULHS, VT, Expand);
00175       setOperationAction(ISD::MULHU, VT, Expand);
00176       setOperationAction(ISD::SMUL_LOHI, VT, Custom);
00177       setOperationAction(ISD::UMUL_LOHI, VT, Custom);
00178 
00179       // Only z196 and above have native support for conversions to unsigned.
00180       if (!Subtarget.hasFPExtension())
00181         setOperationAction(ISD::FP_TO_UINT, VT, Expand);
00182     }
00183   }
00184 
00185   // Type legalization will convert 8- and 16-bit atomic operations into
00186   // forms that operate on i32s (but still keeping the original memory VT).
00187   // Lower them into full i32 operations.
00188   setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Custom);
00189   setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Custom);
00190   setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Custom);
00191   setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Custom);
00192   setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Custom);
00193   setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Custom);
00194   setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Custom);
00195   setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i32, Custom);
00196   setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i32, Custom);
00197   setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Custom);
00198   setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Custom);
00199   setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Custom);
00200 
00201   // z10 has instructions for signed but not unsigned FP conversion.
00202   // Handle unsigned 32-bit types as signed 64-bit types.
00203   if (!Subtarget.hasFPExtension()) {
00204     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote);
00205     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
00206   }
00207 
00208   // We have native support for a 64-bit CTLZ, via FLOGR.
00209   setOperationAction(ISD::CTLZ, MVT::i32, Promote);
00210   setOperationAction(ISD::CTLZ, MVT::i64, Legal);
00211 
00212   // Give LowerOperation the chance to replace 64-bit ORs with subregs.
00213   setOperationAction(ISD::OR, MVT::i64, Custom);
00214 
00215   // FIXME: Can we support these natively?
00216   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
00217   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
00218   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
00219 
00220   // We have native instructions for i8, i16 and i32 extensions, but not i1.
00221   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
00222   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
00223   setLoadExtAction(ISD::EXTLOAD,  MVT::i1, Promote);
00224   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
00225 
00226   // Handle the various types of symbolic address.
00227   setOperationAction(ISD::ConstantPool,     PtrVT, Custom);
00228   setOperationAction(ISD::GlobalAddress,    PtrVT, Custom);
00229   setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom);
00230   setOperationAction(ISD::BlockAddress,     PtrVT, Custom);
00231   setOperationAction(ISD::JumpTable,        PtrVT, Custom);
00232 
00233   // We need to handle dynamic allocations specially because of the
00234   // 160-byte area at the bottom of the stack.
00235   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
00236 
00237   // Use custom expanders so that we can force the function to use
00238   // a frame pointer.
00239   setOperationAction(ISD::STACKSAVE,    MVT::Other, Custom);
00240   setOperationAction(ISD::STACKRESTORE, MVT::Other, Custom);
00241 
00242   // Handle prefetches with PFD or PFDRL.
00243   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
00244 
00245   // Handle floating-point types.
00246   for (unsigned I = MVT::FIRST_FP_VALUETYPE;
00247        I <= MVT::LAST_FP_VALUETYPE;
00248        ++I) {
00249     MVT VT = MVT::SimpleValueType(I);
00250     if (isTypeLegal(VT)) {
00251       // We can use FI for FRINT.
00252       setOperationAction(ISD::FRINT, VT, Legal);
00253 
00254       // We can use the extended form of FI for other rounding operations.
00255       if (Subtarget.hasFPExtension()) {
00256         setOperationAction(ISD::FNEARBYINT, VT, Legal);
00257         setOperationAction(ISD::FFLOOR, VT, Legal);
00258         setOperationAction(ISD::FCEIL, VT, Legal);
00259         setOperationAction(ISD::FTRUNC, VT, Legal);
00260         setOperationAction(ISD::FROUND, VT, Legal);
00261       }
00262 
00263       // No special instructions for these.
00264       setOperationAction(ISD::FSIN, VT, Expand);
00265       setOperationAction(ISD::FCOS, VT, Expand);
00266       setOperationAction(ISD::FREM, VT, Expand);
00267     }
00268   }
00269 
00270   // We have fused multiply-addition for f32 and f64 but not f128.
00271   setOperationAction(ISD::FMA, MVT::f32,  Legal);
00272   setOperationAction(ISD::FMA, MVT::f64,  Legal);
00273   setOperationAction(ISD::FMA, MVT::f128, Expand);
00274 
00275   // Needed so that we don't try to implement f128 constant loads using
00276   // a load-and-extend of a f80 constant (in cases where the constant
00277   // would fit in an f80).
00278   setLoadExtAction(ISD::EXTLOAD, MVT::f80, Expand);
00279 
00280   // Floating-point truncation and stores need to be done separately.
00281   setTruncStoreAction(MVT::f64,  MVT::f32, Expand);
00282   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
00283   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
00284 
00285   // We have 64-bit FPR<->GPR moves, but need special handling for
00286   // 32-bit forms.
00287   setOperationAction(ISD::BITCAST, MVT::i32, Custom);
00288   setOperationAction(ISD::BITCAST, MVT::f32, Custom);
00289 
00290   // VASTART and VACOPY need to deal with the SystemZ-specific varargs
00291   // structure, but VAEND is a no-op.
00292   setOperationAction(ISD::VASTART, MVT::Other, Custom);
00293   setOperationAction(ISD::VACOPY,  MVT::Other, Custom);
00294   setOperationAction(ISD::VAEND,   MVT::Other, Expand);
00295 
00296   // Codes for which we want to perform some z-specific combinations.
00297   setTargetDAGCombine(ISD::SIGN_EXTEND);
00298 
00299   // We want to use MVC in preference to even a single load/store pair.
00300   MaxStoresPerMemcpy = 0;
00301   MaxStoresPerMemcpyOptSize = 0;
00302 
00303   // The main memset sequence is a byte store followed by an MVC.
00304   // Two STC or MV..I stores win over that, but the kind of fused stores
00305   // generated by target-independent code don't when the byte value is
00306   // variable.  E.g.  "STC <reg>;MHI <reg>,257;STH <reg>" is not better
00307   // than "STC;MVC".  Handle the choice in target-specific code instead.
00308   MaxStoresPerMemset = 0;
00309   MaxStoresPerMemsetOptSize = 0;
00310 }
00311 
00312 EVT SystemZTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
00313   if (!VT.isVector())
00314     return MVT::i32;
00315   return VT.changeVectorElementTypeToInteger();
00316 }
00317 
00318 bool SystemZTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
00319   VT = VT.getScalarType();
00320 
00321   if (!VT.isSimple())
00322     return false;
00323 
00324   switch (VT.getSimpleVT().SimpleTy) {
00325   case MVT::f32:
00326   case MVT::f64:
00327     return true;
00328   case MVT::f128:
00329     return false;
00330   default:
00331     break;
00332   }
00333 
00334   return false;
00335 }
00336 
00337 bool SystemZTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
00338   // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
00339   return Imm.isZero() || Imm.isNegZero();
00340 }
00341 
00342 bool SystemZTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
00343                                                           unsigned,
00344                                                           bool *Fast) const {
00345   // Unaligned accesses should never be slower than the expanded version.
00346   // We check specifically for aligned accesses in the few cases where
00347   // they are required.
00348   if (Fast)
00349     *Fast = true;
00350   return true;
00351 }
00352   
00353 bool SystemZTargetLowering::isLegalAddressingMode(const AddrMode &AM,
00354                                                   Type *Ty) const {
00355   // Punt on globals for now, although they can be used in limited
00356   // RELATIVE LONG cases.
00357   if (AM.BaseGV)
00358     return false;
00359 
00360   // Require a 20-bit signed offset.
00361   if (!isInt<20>(AM.BaseOffs))
00362     return false;
00363 
00364   // Indexing is OK but no scale factor can be applied.
00365   return AM.Scale == 0 || AM.Scale == 1;
00366 }
00367 
00368 bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
00369   if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
00370     return false;
00371   unsigned FromBits = FromType->getPrimitiveSizeInBits();
00372   unsigned ToBits = ToType->getPrimitiveSizeInBits();
00373   return FromBits > ToBits;
00374 }
00375 
00376 bool SystemZTargetLowering::isTruncateFree(EVT FromVT, EVT ToVT) const {
00377   if (!FromVT.isInteger() || !ToVT.isInteger())
00378     return false;
00379   unsigned FromBits = FromVT.getSizeInBits();
00380   unsigned ToBits = ToVT.getSizeInBits();
00381   return FromBits > ToBits;
00382 }
00383 
00384 //===----------------------------------------------------------------------===//
00385 // Inline asm support
00386 //===----------------------------------------------------------------------===//
00387 
00388 TargetLowering::ConstraintType
00389 SystemZTargetLowering::getConstraintType(const std::string &Constraint) const {
00390   if (Constraint.size() == 1) {
00391     switch (Constraint[0]) {
00392     case 'a': // Address register
00393     case 'd': // Data register (equivalent to 'r')
00394     case 'f': // Floating-point register
00395     case 'h': // High-part register
00396     case 'r': // General-purpose register
00397       return C_RegisterClass;
00398 
00399     case 'Q': // Memory with base and unsigned 12-bit displacement
00400     case 'R': // Likewise, plus an index
00401     case 'S': // Memory with base and signed 20-bit displacement
00402     case 'T': // Likewise, plus an index
00403     case 'm': // Equivalent to 'T'.
00404       return C_Memory;
00405 
00406     case 'I': // Unsigned 8-bit constant
00407     case 'J': // Unsigned 12-bit constant
00408     case 'K': // Signed 16-bit constant
00409     case 'L': // Signed 20-bit displacement (on all targets we support)
00410     case 'M': // 0x7fffffff
00411       return C_Other;
00412 
00413     default:
00414       break;
00415     }
00416   }
00417   return TargetLowering::getConstraintType(Constraint);
00418 }
00419 
00420 TargetLowering::ConstraintWeight SystemZTargetLowering::
00421 getSingleConstraintMatchWeight(AsmOperandInfo &info,
00422                                const char *constraint) const {
00423   ConstraintWeight weight = CW_Invalid;
00424   Value *CallOperandVal = info.CallOperandVal;
00425   // If we don't have a value, we can't do a match,
00426   // but allow it at the lowest weight.
00427   if (CallOperandVal == NULL)
00428     return CW_Default;
00429   Type *type = CallOperandVal->getType();
00430   // Look at the constraint type.
00431   switch (*constraint) {
00432   default:
00433     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
00434     break;
00435 
00436   case 'a': // Address register
00437   case 'd': // Data register (equivalent to 'r')
00438   case 'h': // High-part register
00439   case 'r': // General-purpose register
00440     if (CallOperandVal->getType()->isIntegerTy())
00441       weight = CW_Register;
00442     break;
00443 
00444   case 'f': // Floating-point register
00445     if (type->isFloatingPointTy())
00446       weight = CW_Register;
00447     break;
00448 
00449   case 'I': // Unsigned 8-bit constant
00450     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
00451       if (isUInt<8>(C->getZExtValue()))
00452         weight = CW_Constant;
00453     break;
00454 
00455   case 'J': // Unsigned 12-bit constant
00456     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
00457       if (isUInt<12>(C->getZExtValue()))
00458         weight = CW_Constant;
00459     break;
00460 
00461   case 'K': // Signed 16-bit constant
00462     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
00463       if (isInt<16>(C->getSExtValue()))
00464         weight = CW_Constant;
00465     break;
00466 
00467   case 'L': // Signed 20-bit displacement (on all targets we support)
00468     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
00469       if (isInt<20>(C->getSExtValue()))
00470         weight = CW_Constant;
00471     break;
00472 
00473   case 'M': // 0x7fffffff
00474     if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
00475       if (C->getZExtValue() == 0x7fffffff)
00476         weight = CW_Constant;
00477     break;
00478   }
00479   return weight;
00480 }
00481 
00482 // Parse a "{tNNN}" register constraint for which the register type "t"
00483 // has already been verified.  MC is the class associated with "t" and
00484 // Map maps 0-based register numbers to LLVM register numbers.
00485 static std::pair<unsigned, const TargetRegisterClass *>
00486 parseRegisterNumber(const std::string &Constraint,
00487                     const TargetRegisterClass *RC, const unsigned *Map) {
00488   assert(*(Constraint.end()-1) == '}' && "Missing '}'");
00489   if (isdigit(Constraint[2])) {
00490     std::string Suffix(Constraint.data() + 2, Constraint.size() - 2);
00491     unsigned Index = atoi(Suffix.c_str());
00492     if (Index < 16 && Map[Index])
00493       return std::make_pair(Map[Index], RC);
00494   }
00495   return std::make_pair(0u, static_cast<TargetRegisterClass*>(0));
00496 }
00497 
00498 std::pair<unsigned, const TargetRegisterClass *> SystemZTargetLowering::
00499 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const {
00500   if (Constraint.size() == 1) {
00501     // GCC Constraint Letters
00502     switch (Constraint[0]) {
00503     default: break;
00504     case 'd': // Data register (equivalent to 'r')
00505     case 'r': // General-purpose register
00506       if (VT == MVT::i64)
00507         return std::make_pair(0U, &SystemZ::GR64BitRegClass);
00508       else if (VT == MVT::i128)
00509         return std::make_pair(0U, &SystemZ::GR128BitRegClass);
00510       return std::make_pair(0U, &SystemZ::GR32BitRegClass);
00511 
00512     case 'a': // Address register
00513       if (VT == MVT::i64)
00514         return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
00515       else if (VT == MVT::i128)
00516         return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
00517       return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
00518 
00519     case 'h': // High-part register (an LLVM extension)
00520       return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
00521 
00522     case 'f': // Floating-point register
00523       if (VT == MVT::f64)
00524         return std::make_pair(0U, &SystemZ::FP64BitRegClass);
00525       else if (VT == MVT::f128)
00526         return std::make_pair(0U, &SystemZ::FP128BitRegClass);
00527       return std::make_pair(0U, &SystemZ::FP32BitRegClass);
00528     }
00529   }
00530   if (Constraint[0] == '{') {
00531     // We need to override the default register parsing for GPRs and FPRs
00532     // because the interpretation depends on VT.  The internal names of
00533     // the registers are also different from the external names
00534     // (F0D and F0S instead of F0, etc.).
00535     if (Constraint[1] == 'r') {
00536       if (VT == MVT::i32)
00537         return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
00538                                    SystemZMC::GR32Regs);
00539       if (VT == MVT::i128)
00540         return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
00541                                    SystemZMC::GR128Regs);
00542       return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
00543                                  SystemZMC::GR64Regs);
00544     }
00545     if (Constraint[1] == 'f') {
00546       if (VT == MVT::f32)
00547         return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
00548                                    SystemZMC::FP32Regs);
00549       if (VT == MVT::f128)
00550         return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
00551                                    SystemZMC::FP128Regs);
00552       return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
00553                                  SystemZMC::FP64Regs);
00554     }
00555   }
00556   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
00557 }
00558 
00559 void SystemZTargetLowering::
00560 LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
00561                              std::vector<SDValue> &Ops,
00562                              SelectionDAG &DAG) const {
00563   // Only support length 1 constraints for now.
00564   if (Constraint.length() == 1) {
00565     switch (Constraint[0]) {
00566     case 'I': // Unsigned 8-bit constant
00567       if (auto *C = dyn_cast<ConstantSDNode>(Op))
00568         if (isUInt<8>(C->getZExtValue()))
00569           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(),
00570                                               Op.getValueType()));
00571       return;
00572 
00573     case 'J': // Unsigned 12-bit constant
00574       if (auto *C = dyn_cast<ConstantSDNode>(Op))
00575         if (isUInt<12>(C->getZExtValue()))
00576           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(),
00577                                               Op.getValueType()));
00578       return;
00579 
00580     case 'K': // Signed 16-bit constant
00581       if (auto *C = dyn_cast<ConstantSDNode>(Op))
00582         if (isInt<16>(C->getSExtValue()))
00583           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(),
00584                                               Op.getValueType()));
00585       return;
00586 
00587     case 'L': // Signed 20-bit displacement (on all targets we support)
00588       if (auto *C = dyn_cast<ConstantSDNode>(Op))
00589         if (isInt<20>(C->getSExtValue()))
00590           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(),
00591                                               Op.getValueType()));
00592       return;
00593 
00594     case 'M': // 0x7fffffff
00595       if (auto *C = dyn_cast<ConstantSDNode>(Op))
00596         if (C->getZExtValue() == 0x7fffffff)
00597           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(),
00598                                               Op.getValueType()));
00599       return;
00600     }
00601   }
00602   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
00603 }
00604 
00605 //===----------------------------------------------------------------------===//
00606 // Calling conventions
00607 //===----------------------------------------------------------------------===//
00608 
00609 #include "SystemZGenCallingConv.inc"
00610 
00611 bool SystemZTargetLowering::allowTruncateForTailCall(Type *FromType,
00612                                                      Type *ToType) const {
00613   return isTruncateFree(FromType, ToType);
00614 }
00615 
00616 bool SystemZTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
00617   if (!CI->isTailCall())
00618     return false;
00619   return true;
00620 }
00621 
00622 // Value is a value that has been passed to us in the location described by VA
00623 // (and so has type VA.getLocVT()).  Convert Value to VA.getValVT(), chaining
00624 // any loads onto Chain.
00625 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDLoc DL,
00626                                    CCValAssign &VA, SDValue Chain,
00627                                    SDValue Value) {
00628   // If the argument has been promoted from a smaller type, insert an
00629   // assertion to capture this.
00630   if (VA.getLocInfo() == CCValAssign::SExt)
00631     Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value,
00632                         DAG.getValueType(VA.getValVT()));
00633   else if (VA.getLocInfo() == CCValAssign::ZExt)
00634     Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value,
00635                         DAG.getValueType(VA.getValVT()));
00636 
00637   if (VA.isExtInLoc())
00638     Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
00639   else if (VA.getLocInfo() == CCValAssign::Indirect)
00640     Value = DAG.getLoad(VA.getValVT(), DL, Chain, Value,
00641                         MachinePointerInfo(), false, false, false, 0);
00642   else
00643     assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
00644   return Value;
00645 }
00646 
00647 // Value is a value of type VA.getValVT() that we need to copy into
00648 // the location described by VA.  Return a copy of Value converted to
00649 // VA.getValVT().  The caller is responsible for handling indirect values.
00650 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDLoc DL,
00651                                    CCValAssign &VA, SDValue Value) {
00652   switch (VA.getLocInfo()) {
00653   case CCValAssign::SExt:
00654     return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
00655   case CCValAssign::ZExt:
00656     return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
00657   case CCValAssign::AExt:
00658     return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
00659   case CCValAssign::Full:
00660     return Value;
00661   default:
00662     llvm_unreachable("Unhandled getLocInfo()");
00663   }
00664 }
00665 
00666 SDValue SystemZTargetLowering::
00667 LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
00668                      const SmallVectorImpl<ISD::InputArg> &Ins,
00669                      SDLoc DL, SelectionDAG &DAG,
00670                      SmallVectorImpl<SDValue> &InVals) const {
00671   MachineFunction &MF = DAG.getMachineFunction();
00672   MachineFrameInfo *MFI = MF.getFrameInfo();
00673   MachineRegisterInfo &MRI = MF.getRegInfo();
00674   SystemZMachineFunctionInfo *FuncInfo =
00675     MF.getInfo<SystemZMachineFunctionInfo>();
00676   auto *TFL = static_cast<const SystemZFrameLowering *>(TM.getFrameLowering());
00677 
00678   // Assign locations to all of the incoming arguments.
00679   SmallVector<CCValAssign, 16> ArgLocs;
00680   CCState CCInfo(CallConv, IsVarArg, MF, TM, ArgLocs, *DAG.getContext());
00681   CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
00682 
00683   unsigned NumFixedGPRs = 0;
00684   unsigned NumFixedFPRs = 0;
00685   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
00686     SDValue ArgValue;
00687     CCValAssign &VA = ArgLocs[I];
00688     EVT LocVT = VA.getLocVT();
00689     if (VA.isRegLoc()) {
00690       // Arguments passed in registers
00691       const TargetRegisterClass *RC;
00692       switch (LocVT.getSimpleVT().SimpleTy) {
00693       default:
00694         // Integers smaller than i64 should be promoted to i64.
00695         llvm_unreachable("Unexpected argument type");
00696       case MVT::i32:
00697         NumFixedGPRs += 1;
00698         RC = &SystemZ::GR32BitRegClass;
00699         break;
00700       case MVT::i64:
00701         NumFixedGPRs += 1;
00702         RC = &SystemZ::GR64BitRegClass;
00703         break;
00704       case MVT::f32:
00705         NumFixedFPRs += 1;
00706         RC = &SystemZ::FP32BitRegClass;
00707         break;
00708       case MVT::f64:
00709         NumFixedFPRs += 1;
00710         RC = &SystemZ::FP64BitRegClass;
00711         break;
00712       }
00713 
00714       unsigned VReg = MRI.createVirtualRegister(RC);
00715       MRI.addLiveIn(VA.getLocReg(), VReg);
00716       ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
00717     } else {
00718       assert(VA.isMemLoc() && "Argument not register or memory");
00719 
00720       // Create the frame index object for this incoming parameter.
00721       int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
00722                                       VA.getLocMemOffset(), true);
00723 
00724       // Create the SelectionDAG nodes corresponding to a load
00725       // from this parameter.  Unpromoted ints and floats are
00726       // passed as right-justified 8-byte values.
00727       EVT PtrVT = getPointerTy();
00728       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
00729       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
00730         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4));
00731       ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
00732                              MachinePointerInfo::getFixedStack(FI),
00733                              false, false, false, 0);
00734     }
00735 
00736     // Convert the value of the argument register into the value that's
00737     // being passed.
00738     InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
00739   }
00740 
00741   if (IsVarArg) {
00742     // Save the number of non-varargs registers for later use by va_start, etc.
00743     FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
00744     FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
00745 
00746     // Likewise the address (in the form of a frame index) of where the
00747     // first stack vararg would be.  The 1-byte size here is arbitrary.
00748     int64_t StackSize = CCInfo.getNextStackOffset();
00749     FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize, true));
00750 
00751     // ...and a similar frame index for the caller-allocated save area
00752     // that will be used to store the incoming registers.
00753     int64_t RegSaveOffset = TFL->getOffsetOfLocalArea();
00754     unsigned RegSaveIndex = MFI->CreateFixedObject(1, RegSaveOffset, true);
00755     FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
00756 
00757     // Store the FPR varargs in the reserved frame slots.  (We store the
00758     // GPRs as part of the prologue.)
00759     if (NumFixedFPRs < SystemZ::NumArgFPRs) {
00760       SDValue MemOps[SystemZ::NumArgFPRs];
00761       for (unsigned I = NumFixedFPRs; I < SystemZ::NumArgFPRs; ++I) {
00762         unsigned Offset = TFL->getRegSpillOffset(SystemZ::ArgFPRs[I]);
00763         int FI = MFI->CreateFixedObject(8, RegSaveOffset + Offset, true);
00764         SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
00765         unsigned VReg = MF.addLiveIn(SystemZ::ArgFPRs[I],
00766                                      &SystemZ::FP64BitRegClass);
00767         SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
00768         MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
00769                                  MachinePointerInfo::getFixedStack(FI),
00770                                  false, false, 0);
00771 
00772       }
00773       // Join the stores, which are independent of one another.
00774       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
00775                           &MemOps[NumFixedFPRs],
00776                           SystemZ::NumArgFPRs - NumFixedFPRs);
00777     }
00778   }
00779 
00780   return Chain;
00781 }
00782 
00783 static bool canUseSiblingCall(CCState ArgCCInfo,
00784                               SmallVectorImpl<CCValAssign> &ArgLocs) {
00785   // Punt if there are any indirect or stack arguments, or if the call
00786   // needs the call-saved argument register R6.
00787   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
00788     CCValAssign &VA = ArgLocs[I];
00789     if (VA.getLocInfo() == CCValAssign::Indirect)
00790       return false;
00791     if (!VA.isRegLoc())
00792       return false;
00793     unsigned Reg = VA.getLocReg();
00794     if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
00795       return false;
00796   }
00797   return true;
00798 }
00799 
00800 SDValue
00801 SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI,
00802                                  SmallVectorImpl<SDValue> &InVals) const {
00803   SelectionDAG &DAG = CLI.DAG;
00804   SDLoc &DL = CLI.DL;
00805   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
00806   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
00807   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
00808   SDValue Chain = CLI.Chain;
00809   SDValue Callee = CLI.Callee;
00810   bool &IsTailCall = CLI.IsTailCall;
00811   CallingConv::ID CallConv = CLI.CallConv;
00812   bool IsVarArg = CLI.IsVarArg;
00813   MachineFunction &MF = DAG.getMachineFunction();
00814   EVT PtrVT = getPointerTy();
00815 
00816   // Analyze the operands of the call, assigning locations to each operand.
00817   SmallVector<CCValAssign, 16> ArgLocs;
00818   CCState ArgCCInfo(CallConv, IsVarArg, MF, TM, ArgLocs, *DAG.getContext());
00819   ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
00820 
00821   // We don't support GuaranteedTailCallOpt, only automatically-detected
00822   // sibling calls.
00823   if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs))
00824     IsTailCall = false;
00825 
00826   // Get a count of how many bytes are to be pushed on the stack.
00827   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
00828 
00829   // Mark the start of the call.
00830   if (!IsTailCall)
00831     Chain = DAG.getCALLSEQ_START(Chain, DAG.getConstant(NumBytes, PtrVT, true),
00832                                  DL);
00833 
00834   // Copy argument values to their designated locations.
00835   SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass;
00836   SmallVector<SDValue, 8> MemOpChains;
00837   SDValue StackPtr;
00838   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
00839     CCValAssign &VA = ArgLocs[I];
00840     SDValue ArgValue = OutVals[I];
00841 
00842     if (VA.getLocInfo() == CCValAssign::Indirect) {
00843       // Store the argument in a stack slot and pass its address.
00844       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
00845       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
00846       MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, SpillSlot,
00847                                          MachinePointerInfo::getFixedStack(FI),
00848                                          false, false, 0));
00849       ArgValue = SpillSlot;
00850     } else
00851       ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
00852 
00853     if (VA.isRegLoc())
00854       // Queue up the argument copies and emit them at the end.
00855       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
00856     else {
00857       assert(VA.isMemLoc() && "Argument not register or memory");
00858 
00859       // Work out the address of the stack slot.  Unpromoted ints and
00860       // floats are passed as right-justified 8-byte values.
00861       if (!StackPtr.getNode())
00862         StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT);
00863       unsigned Offset = SystemZMC::CallFrameSize + VA.getLocMemOffset();
00864       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
00865         Offset += 4;
00866       SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
00867                                     DAG.getIntPtrConstant(Offset));
00868 
00869       // Emit the store.
00870       MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, Address,
00871                                          MachinePointerInfo(),
00872                                          false, false, 0));
00873     }
00874   }
00875 
00876   // Join the stores, which are independent of one another.
00877   if (!MemOpChains.empty())
00878     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
00879                         &MemOpChains[0], MemOpChains.size());
00880 
00881   // Accept direct calls by converting symbolic call addresses to the
00882   // associated Target* opcodes.  Force %r1 to be used for indirect
00883   // tail calls.
00884   SDValue Glue;
00885   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
00886     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
00887     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
00888   } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
00889     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
00890     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
00891   } else if (IsTailCall) {
00892     Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
00893     Glue = Chain.getValue(1);
00894     Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
00895   }
00896 
00897   // Build a sequence of copy-to-reg nodes, chained and glued together.
00898   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
00899     Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
00900                              RegsToPass[I].second, Glue);
00901     Glue = Chain.getValue(1);
00902   }
00903 
00904   // The first call operand is the chain and the second is the target address.
00905   SmallVector<SDValue, 8> Ops;
00906   Ops.push_back(Chain);
00907   Ops.push_back(Callee);
00908 
00909   // Add argument registers to the end of the list so that they are
00910   // known live into the call.
00911   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
00912     Ops.push_back(DAG.getRegister(RegsToPass[I].first,
00913                                   RegsToPass[I].second.getValueType()));
00914 
00915   // Glue the call to the argument copies, if any.
00916   if (Glue.getNode())
00917     Ops.push_back(Glue);
00918 
00919   // Emit the call.
00920   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
00921   if (IsTailCall)
00922     return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, &Ops[0], Ops.size());
00923   Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, &Ops[0], Ops.size());
00924   Glue = Chain.getValue(1);
00925 
00926   // Mark the end of the call, which is glued to the call itself.
00927   Chain = DAG.getCALLSEQ_END(Chain,
00928                              DAG.getConstant(NumBytes, PtrVT, true),
00929                              DAG.getConstant(0, PtrVT, true),
00930                              Glue, DL);
00931   Glue = Chain.getValue(1);
00932 
00933   // Assign locations to each value returned by this call.
00934   SmallVector<CCValAssign, 16> RetLocs;
00935   CCState RetCCInfo(CallConv, IsVarArg, MF, TM, RetLocs, *DAG.getContext());
00936   RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
00937 
00938   // Copy all of the result registers out of their specified physreg.
00939   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
00940     CCValAssign &VA = RetLocs[I];
00941 
00942     // Copy the value out, gluing the copy to the end of the call sequence.
00943     SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
00944                                           VA.getLocVT(), Glue);
00945     Chain = RetValue.getValue(1);
00946     Glue = RetValue.getValue(2);
00947 
00948     // Convert the value of the return register into the value that's
00949     // being returned.
00950     InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
00951   }
00952 
00953   return Chain;
00954 }
00955 
00956 SDValue
00957 SystemZTargetLowering::LowerReturn(SDValue Chain,
00958                                    CallingConv::ID CallConv, bool IsVarArg,
00959                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
00960                                    const SmallVectorImpl<SDValue> &OutVals,
00961                                    SDLoc DL, SelectionDAG &DAG) const {
00962   MachineFunction &MF = DAG.getMachineFunction();
00963 
00964   // Assign locations to each returned value.
00965   SmallVector<CCValAssign, 16> RetLocs;
00966   CCState RetCCInfo(CallConv, IsVarArg, MF, TM, RetLocs, *DAG.getContext());
00967   RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
00968 
00969   // Quick exit for void returns
00970   if (RetLocs.empty())
00971     return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
00972 
00973   // Copy the result values into the output registers.
00974   SDValue Glue;
00975   SmallVector<SDValue, 4> RetOps;
00976   RetOps.push_back(Chain);
00977   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
00978     CCValAssign &VA = RetLocs[I];
00979     SDValue RetValue = OutVals[I];
00980 
00981     // Make the return register live on exit.
00982     assert(VA.isRegLoc() && "Can only return in registers!");
00983 
00984     // Promote the value as required.
00985     RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
00986 
00987     // Chain and glue the copies together.
00988     unsigned Reg = VA.getLocReg();
00989     Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
00990     Glue = Chain.getValue(1);
00991     RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
00992   }
00993 
00994   // Update chain and glue.
00995   RetOps[0] = Chain;
00996   if (Glue.getNode())
00997     RetOps.push_back(Glue);
00998 
00999   return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other,
01000                      RetOps.data(), RetOps.size());
01001 }
01002 
01003 SDValue SystemZTargetLowering::
01004 prepareVolatileOrAtomicLoad(SDValue Chain, SDLoc DL, SelectionDAG &DAG) const {
01005   return DAG.getNode(SystemZISD::SERIALIZE, DL, MVT::Other, Chain);
01006 }
01007 
01008 // CC is a comparison that will be implemented using an integer or
01009 // floating-point comparison.  Return the condition code mask for
01010 // a branch on true.  In the integer case, CCMASK_CMP_UO is set for
01011 // unsigned comparisons and clear for signed ones.  In the floating-point
01012 // case, CCMASK_CMP_UO has its normal mask meaning (unordered).
01013 static unsigned CCMaskForCondCode(ISD::CondCode CC) {
01014 #define CONV(X) \
01015   case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
01016   case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
01017   case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
01018 
01019   switch (CC) {
01020   default:
01021     llvm_unreachable("Invalid integer condition!");
01022 
01023   CONV(EQ);
01024   CONV(NE);
01025   CONV(GT);
01026   CONV(GE);
01027   CONV(LT);
01028   CONV(LE);
01029 
01030   case ISD::SETO:  return SystemZ::CCMASK_CMP_O;
01031   case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
01032   }
01033 #undef CONV
01034 }
01035 
01036 // Return a sequence for getting a 1 from an IPM result when CC has a
01037 // value in CCMask and a 0 when CC has a value in CCValid & ~CCMask.
01038 // The handling of CC values outside CCValid doesn't matter.
01039 static IPMConversion getIPMConversion(unsigned CCValid, unsigned CCMask) {
01040   // Deal with cases where the result can be taken directly from a bit
01041   // of the IPM result.
01042   if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_3)))
01043     return IPMConversion(0, 0, SystemZ::IPM_CC);
01044   if (CCMask == (CCValid & (SystemZ::CCMASK_2 | SystemZ::CCMASK_3)))
01045     return IPMConversion(0, 0, SystemZ::IPM_CC + 1);
01046 
01047   // Deal with cases where we can add a value to force the sign bit
01048   // to contain the right value.  Putting the bit in 31 means we can
01049   // use SRL rather than RISBG(L), and also makes it easier to get a
01050   // 0/-1 value, so it has priority over the other tests below.
01051   //
01052   // These sequences rely on the fact that the upper two bits of the
01053   // IPM result are zero.
01054   uint64_t TopBit = uint64_t(1) << 31;
01055   if (CCMask == (CCValid & SystemZ::CCMASK_0))
01056     return IPMConversion(0, -(1 << SystemZ::IPM_CC), 31);
01057   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_1)))
01058     return IPMConversion(0, -(2 << SystemZ::IPM_CC), 31);
01059   if (CCMask == (CCValid & (SystemZ::CCMASK_0
01060                             | SystemZ::CCMASK_1
01061                             | SystemZ::CCMASK_2)))
01062     return IPMConversion(0, -(3 << SystemZ::IPM_CC), 31);
01063   if (CCMask == (CCValid & SystemZ::CCMASK_3))
01064     return IPMConversion(0, TopBit - (3 << SystemZ::IPM_CC), 31);
01065   if (CCMask == (CCValid & (SystemZ::CCMASK_1
01066                             | SystemZ::CCMASK_2
01067                             | SystemZ::CCMASK_3)))
01068     return IPMConversion(0, TopBit - (1 << SystemZ::IPM_CC), 31);
01069 
01070   // Next try inverting the value and testing a bit.  0/1 could be
01071   // handled this way too, but we dealt with that case above.
01072   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_2)))
01073     return IPMConversion(-1, 0, SystemZ::IPM_CC);
01074 
01075   // Handle cases where adding a value forces a non-sign bit to contain
01076   // the right value.
01077   if (CCMask == (CCValid & (SystemZ::CCMASK_1 | SystemZ::CCMASK_2)))
01078     return IPMConversion(0, 1 << SystemZ::IPM_CC, SystemZ::IPM_CC + 1);
01079   if (CCMask == (CCValid & (SystemZ::CCMASK_0 | SystemZ::CCMASK_3)))
01080     return IPMConversion(0, -(1 << SystemZ::IPM_CC), SystemZ::IPM_CC + 1);
01081 
01082   // The remaining cases are 1, 2, 0/1/3 and 0/2/3.  All these are
01083   // can be done by inverting the low CC bit and applying one of the
01084   // sign-based extractions above.
01085   if (CCMask == (CCValid & SystemZ::CCMASK_1))
01086     return IPMConversion(1 << SystemZ::IPM_CC, -(1 << SystemZ::IPM_CC), 31);
01087   if (CCMask == (CCValid & SystemZ::CCMASK_2))
01088     return IPMConversion(1 << SystemZ::IPM_CC,
01089                          TopBit - (3 << SystemZ::IPM_CC), 31);
01090   if (CCMask == (CCValid & (SystemZ::CCMASK_0
01091                             | SystemZ::CCMASK_1
01092                             | SystemZ::CCMASK_3)))
01093     return IPMConversion(1 << SystemZ::IPM_CC, -(3 << SystemZ::IPM_CC), 31);
01094   if (CCMask == (CCValid & (SystemZ::CCMASK_0
01095                             | SystemZ::CCMASK_2
01096                             | SystemZ::CCMASK_3)))
01097     return IPMConversion(1 << SystemZ::IPM_CC,
01098                          TopBit - (1 << SystemZ::IPM_CC), 31);
01099 
01100   llvm_unreachable("Unexpected CC combination");
01101 }
01102 
01103 // If C can be converted to a comparison against zero, adjust the operands
01104 // as necessary.
01105 static void adjustZeroCmp(SelectionDAG &DAG, Comparison &C) {
01106   if (C.ICmpType == SystemZICMP::UnsignedOnly)
01107     return;
01108 
01109   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
01110   if (!ConstOp1)
01111     return;
01112 
01113   int64_t Value = ConstOp1->getSExtValue();
01114   if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
01115       (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
01116       (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
01117       (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
01118     C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
01119     C.Op1 = DAG.getConstant(0, C.Op1.getValueType());
01120   }
01121 }
01122 
01123 // If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
01124 // adjust the operands as necessary.
01125 static void adjustSubwordCmp(SelectionDAG &DAG, Comparison &C) {
01126   // For us to make any changes, it must a comparison between a single-use
01127   // load and a constant.
01128   if (!C.Op0.hasOneUse() ||
01129       C.Op0.getOpcode() != ISD::LOAD ||
01130       C.Op1.getOpcode() != ISD::Constant)
01131     return;
01132 
01133   // We must have an 8- or 16-bit load.
01134   auto *Load = cast<LoadSDNode>(C.Op0);
01135   unsigned NumBits = Load->getMemoryVT().getStoreSizeInBits();
01136   if (NumBits != 8 && NumBits != 16)
01137     return;
01138 
01139   // The load must be an extending one and the constant must be within the
01140   // range of the unextended value.
01141   auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
01142   uint64_t Value = ConstOp1->getZExtValue();
01143   uint64_t Mask = (1 << NumBits) - 1;
01144   if (Load->getExtensionType() == ISD::SEXTLOAD) {
01145     // Make sure that ConstOp1 is in range of C.Op0.
01146     int64_t SignedValue = ConstOp1->getSExtValue();
01147     if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
01148       return;
01149     if (C.ICmpType != SystemZICMP::SignedOnly) {
01150       // Unsigned comparison between two sign-extended values is equivalent
01151       // to unsigned comparison between two zero-extended values.
01152       Value &= Mask;
01153     } else if (NumBits == 8) {
01154       // Try to treat the comparison as unsigned, so that we can use CLI.
01155       // Adjust CCMask and Value as necessary.
01156       if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
01157         // Test whether the high bit of the byte is set.
01158         Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
01159       else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
01160         // Test whether the high bit of the byte is clear.
01161         Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
01162       else
01163         // No instruction exists for this combination.
01164         return;
01165       C.ICmpType = SystemZICMP::UnsignedOnly;
01166     }
01167   } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
01168     if (Value > Mask)
01169       return;
01170     assert(C.ICmpType == SystemZICMP::Any &&
01171            "Signedness shouldn't matter here.");
01172   } else
01173     return;
01174 
01175   // Make sure that the first operand is an i32 of the right extension type.
01176   ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
01177                               ISD::SEXTLOAD :
01178                               ISD::ZEXTLOAD);
01179   if (C.Op0.getValueType() != MVT::i32 ||
01180       Load->getExtensionType() != ExtType)
01181     C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32,
01182                            Load->getChain(), Load->getBasePtr(),
01183                            Load->getPointerInfo(), Load->getMemoryVT(),
01184                            Load->isVolatile(), Load->isNonTemporal(),
01185                            Load->getAlignment());
01186 
01187   // Make sure that the second operand is an i32 with the right value.
01188   if (C.Op1.getValueType() != MVT::i32 ||
01189       Value != ConstOp1->getZExtValue())
01190     C.Op1 = DAG.getConstant(Value, MVT::i32);
01191 }
01192 
01193 // Return true if Op is either an unextended load, or a load suitable
01194 // for integer register-memory comparisons of type ICmpType.
01195 static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
01196   auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
01197   if (Load) {
01198     // There are no instructions to compare a register with a memory byte.
01199     if (Load->getMemoryVT() == MVT::i8)
01200       return false;
01201     // Otherwise decide on extension type.
01202     switch (Load->getExtensionType()) {
01203     case ISD::NON_EXTLOAD:
01204       return true;
01205     case ISD::SEXTLOAD:
01206       return ICmpType != SystemZICMP::UnsignedOnly;
01207     case ISD::ZEXTLOAD:
01208       return ICmpType != SystemZICMP::SignedOnly;
01209     default:
01210       break;
01211     }
01212   }
01213   return false;
01214 }
01215 
01216 // Return true if it is better to swap the operands of C.
01217 static bool shouldSwapCmpOperands(const Comparison &C) {
01218   // Leave f128 comparisons alone, since they have no memory forms.
01219   if (C.Op0.getValueType() == MVT::f128)
01220     return false;
01221 
01222   // Always keep a floating-point constant second, since comparisons with
01223   // zero can use LOAD TEST and comparisons with other constants make a
01224   // natural memory operand.
01225   if (isa<ConstantFPSDNode>(C.Op1))
01226     return false;
01227 
01228   // Never swap comparisons with zero since there are many ways to optimize
01229   // those later.
01230   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
01231   if (ConstOp1 && ConstOp1->getZExtValue() == 0)
01232     return false;
01233 
01234   // Also keep natural memory operands second if the loaded value is
01235   // only used here.  Several comparisons have memory forms.
01236   if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
01237     return false;
01238 
01239   // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
01240   // In that case we generally prefer the memory to be second.
01241   if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
01242     // The only exceptions are when the second operand is a constant and
01243     // we can use things like CHHSI.
01244     if (!ConstOp1)
01245       return true;
01246     // The unsigned memory-immediate instructions can handle 16-bit
01247     // unsigned integers.
01248     if (C.ICmpType != SystemZICMP::SignedOnly &&
01249         isUInt<16>(ConstOp1->getZExtValue()))
01250       return false;
01251     // The signed memory-immediate instructions can handle 16-bit
01252     // signed integers.
01253     if (C.ICmpType != SystemZICMP::UnsignedOnly &&
01254         isInt<16>(ConstOp1->getSExtValue()))
01255       return false;
01256     return true;
01257   }
01258 
01259   // Try to promote the use of CGFR and CLGFR.
01260   unsigned Opcode0 = C.Op0.getOpcode();
01261   if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
01262     return true;
01263   if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
01264     return true;
01265   if (C.ICmpType != SystemZICMP::SignedOnly &&
01266       Opcode0 == ISD::AND &&
01267       C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
01268       cast<ConstantSDNode>(C.Op0.getOperand(1))->getZExtValue() == 0xffffffff)
01269     return true;
01270 
01271   return false;
01272 }
01273 
01274 // Return a version of comparison CC mask CCMask in which the LT and GT
01275 // actions are swapped.
01276 static unsigned reverseCCMask(unsigned CCMask) {
01277   return ((CCMask & SystemZ::CCMASK_CMP_EQ) |
01278           (CCMask & SystemZ::CCMASK_CMP_GT ? SystemZ::CCMASK_CMP_LT : 0) |
01279           (CCMask & SystemZ::CCMASK_CMP_LT ? SystemZ::CCMASK_CMP_GT : 0) |
01280           (CCMask & SystemZ::CCMASK_CMP_UO));
01281 }
01282 
01283 // Check whether C tests for equality between X and Y and whether X - Y
01284 // or Y - X is also computed.  In that case it's better to compare the
01285 // result of the subtraction against zero.
01286 static void adjustForSubtraction(SelectionDAG &DAG, Comparison &C) {
01287   if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
01288       C.CCMask == SystemZ::CCMASK_CMP_NE) {
01289     for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
01290       SDNode *N = *I;
01291       if (N->getOpcode() == ISD::SUB &&
01292           ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
01293            (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
01294         C.Op0 = SDValue(N, 0);
01295         C.Op1 = DAG.getConstant(0, N->getValueType(0));
01296         return;
01297       }
01298     }
01299   }
01300 }
01301 
01302 // Check whether C compares a floating-point value with zero and if that
01303 // floating-point value is also negated.  In this case we can use the
01304 // negation to set CC, so avoiding separate LOAD AND TEST and
01305 // LOAD (NEGATIVE/COMPLEMENT) instructions.
01306 static void adjustForFNeg(Comparison &C) {
01307   auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
01308   if (C1 && C1->isZero()) {
01309     for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
01310       SDNode *N = *I;
01311       if (N->getOpcode() == ISD::FNEG) {
01312         C.Op0 = SDValue(N, 0);
01313         C.CCMask = reverseCCMask(C.CCMask);
01314         return;
01315       }
01316     }
01317   }
01318 }
01319 
01320 // Check whether C compares (shl X, 32) with 0 and whether X is
01321 // also sign-extended.  In that case it is better to test the result
01322 // of the sign extension using LTGFR.
01323 //
01324 // This case is important because InstCombine transforms a comparison
01325 // with (sext (trunc X)) into a comparison with (shl X, 32).
01326 static void adjustForLTGFR(Comparison &C) {
01327   // Check for a comparison between (shl X, 32) and 0.
01328   if (C.Op0.getOpcode() == ISD::SHL &&
01329       C.Op0.getValueType() == MVT::i64 &&
01330       C.Op1.getOpcode() == ISD::Constant &&
01331       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
01332     auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
01333     if (C1 && C1->getZExtValue() == 32) {
01334       SDValue ShlOp0 = C.Op0.getOperand(0);
01335       // See whether X has any SIGN_EXTEND_INREG uses.
01336       for (auto I = ShlOp0->use_begin(), E = ShlOp0->use_end(); I != E; ++I) {
01337         SDNode *N = *I;
01338         if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
01339             cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
01340           C.Op0 = SDValue(N, 0);
01341           return;
01342         }
01343       }
01344     }
01345   }
01346 }
01347 
01348 // If C compares the truncation of an extending load, try to compare
01349 // the untruncated value instead.  This exposes more opportunities to
01350 // reuse CC.
01351 static void adjustICmpTruncate(SelectionDAG &DAG, Comparison &C) {
01352   if (C.Op0.getOpcode() == ISD::TRUNCATE &&
01353       C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
01354       C.Op1.getOpcode() == ISD::Constant &&
01355       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
01356     auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
01357     if (L->getMemoryVT().getStoreSizeInBits()
01358         <= C.Op0.getValueType().getSizeInBits()) {
01359       unsigned Type = L->getExtensionType();
01360       if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
01361           (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
01362         C.Op0 = C.Op0.getOperand(0);
01363         C.Op1 = DAG.getConstant(0, C.Op0.getValueType());
01364       }
01365     }
01366   }
01367 }
01368 
01369 // Return true if shift operation N has an in-range constant shift value.
01370 // Store it in ShiftVal if so.
01371 static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
01372   auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
01373   if (!Shift)
01374     return false;
01375 
01376   uint64_t Amount = Shift->getZExtValue();
01377   if (Amount >= N.getValueType().getSizeInBits())
01378     return false;
01379 
01380   ShiftVal = Amount;
01381   return true;
01382 }
01383 
01384 // Check whether an AND with Mask is suitable for a TEST UNDER MASK
01385 // instruction and whether the CC value is descriptive enough to handle
01386 // a comparison of type Opcode between the AND result and CmpVal.
01387 // CCMask says which comparison result is being tested and BitSize is
01388 // the number of bits in the operands.  If TEST UNDER MASK can be used,
01389 // return the corresponding CC mask, otherwise return 0.
01390 static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
01391                                      uint64_t Mask, uint64_t CmpVal,
01392                                      unsigned ICmpType) {
01393   assert(Mask != 0 && "ANDs with zero should have been removed by now");
01394 
01395   // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
01396   if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
01397       !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
01398     return 0;
01399 
01400   // Work out the masks for the lowest and highest bits.
01401   unsigned HighShift = 63 - countLeadingZeros(Mask);
01402   uint64_t High = uint64_t(1) << HighShift;
01403   uint64_t Low = uint64_t(1) << countTrailingZeros(Mask);
01404 
01405   // Signed ordered comparisons are effectively unsigned if the sign
01406   // bit is dropped.
01407   bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
01408 
01409   // Check for equality comparisons with 0, or the equivalent.
01410   if (CmpVal == 0) {
01411     if (CCMask == SystemZ::CCMASK_CMP_EQ)
01412       return SystemZ::CCMASK_TM_ALL_0;
01413     if (CCMask == SystemZ::CCMASK_CMP_NE)
01414       return SystemZ::CCMASK_TM_SOME_1;
01415   }
01416   if (EffectivelyUnsigned && CmpVal <= Low) {
01417     if (CCMask == SystemZ::CCMASK_CMP_LT)
01418       return SystemZ::CCMASK_TM_ALL_0;
01419     if (CCMask == SystemZ::CCMASK_CMP_GE)
01420       return SystemZ::CCMASK_TM_SOME_1;
01421   }
01422   if (EffectivelyUnsigned && CmpVal < Low) {
01423     if (CCMask == SystemZ::CCMASK_CMP_LE)
01424       return SystemZ::CCMASK_TM_ALL_0;
01425     if (CCMask == SystemZ::CCMASK_CMP_GT)
01426       return SystemZ::CCMASK_TM_SOME_1;
01427   }
01428 
01429   // Check for equality comparisons with the mask, or the equivalent.
01430   if (CmpVal == Mask) {
01431     if (CCMask == SystemZ::CCMASK_CMP_EQ)
01432       return SystemZ::CCMASK_TM_ALL_1;
01433     if (CCMask == SystemZ::CCMASK_CMP_NE)
01434       return SystemZ::CCMASK_TM_SOME_0;
01435   }
01436   if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
01437     if (CCMask == SystemZ::CCMASK_CMP_GT)
01438       return SystemZ::CCMASK_TM_ALL_1;
01439     if (CCMask == SystemZ::CCMASK_CMP_LE)
01440       return SystemZ::CCMASK_TM_SOME_0;
01441   }
01442   if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
01443     if (CCMask == SystemZ::CCMASK_CMP_GE)
01444       return SystemZ::CCMASK_TM_ALL_1;
01445     if (CCMask == SystemZ::CCMASK_CMP_LT)
01446       return SystemZ::CCMASK_TM_SOME_0;
01447   }
01448 
01449   // Check for ordered comparisons with the top bit.
01450   if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
01451     if (CCMask == SystemZ::CCMASK_CMP_LE)
01452       return SystemZ::CCMASK_TM_MSB_0;
01453     if (CCMask == SystemZ::CCMASK_CMP_GT)
01454       return SystemZ::CCMASK_TM_MSB_1;
01455   }
01456   if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
01457     if (CCMask == SystemZ::CCMASK_CMP_LT)
01458       return SystemZ::CCMASK_TM_MSB_0;
01459     if (CCMask == SystemZ::CCMASK_CMP_GE)
01460       return SystemZ::CCMASK_TM_MSB_1;
01461   }
01462 
01463   // If there are just two bits, we can do equality checks for Low and High
01464   // as well.
01465   if (Mask == Low + High) {
01466     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
01467       return SystemZ::CCMASK_TM_MIXED_MSB_0;
01468     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
01469       return SystemZ::CCMASK_TM_MIXED_MSB_0 ^ SystemZ::CCMASK_ANY;
01470     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
01471       return SystemZ::CCMASK_TM_MIXED_MSB_1;
01472     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
01473       return SystemZ::CCMASK_TM_MIXED_MSB_1 ^ SystemZ::CCMASK_ANY;
01474   }
01475 
01476   // Looks like we've exhausted our options.
01477   return 0;
01478 }
01479 
01480 // See whether C can be implemented as a TEST UNDER MASK instruction.
01481 // Update the arguments with the TM version if so.
01482 static void adjustForTestUnderMask(SelectionDAG &DAG, Comparison &C) {
01483   // Check that we have a comparison with a constant.
01484   auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
01485   if (!ConstOp1)
01486     return;
01487   uint64_t CmpVal = ConstOp1->getZExtValue();
01488 
01489   // Check whether the nonconstant input is an AND with a constant mask.
01490   Comparison NewC(C);
01491   uint64_t MaskVal;
01492   ConstantSDNode *Mask = 0;
01493   if (C.Op0.getOpcode() == ISD::AND) {
01494     NewC.Op0 = C.Op0.getOperand(0);
01495     NewC.Op1 = C.Op0.getOperand(1);
01496     Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
01497     if (!Mask)
01498       return;
01499     MaskVal = Mask->getZExtValue();
01500   } else {
01501     // There is no instruction to compare with a 64-bit immediate
01502     // so use TMHH instead if possible.  We need an unsigned ordered
01503     // comparison with an i64 immediate.
01504     if (NewC.Op0.getValueType() != MVT::i64 ||
01505         NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
01506         NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
01507         NewC.ICmpType == SystemZICMP::SignedOnly)
01508       return;
01509     // Convert LE and GT comparisons into LT and GE.
01510     if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
01511         NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
01512       if (CmpVal == uint64_t(-1))
01513         return;
01514       CmpVal += 1;
01515       NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
01516     }
01517     // If the low N bits of Op1 are zero than the low N bits of Op0 can
01518     // be masked off without changing the result.
01519     MaskVal = -(CmpVal & -CmpVal);
01520     NewC.ICmpType = SystemZICMP::UnsignedOnly;
01521   }
01522 
01523   // Check whether the combination of mask, comparison value and comparison
01524   // type are suitable.
01525   unsigned BitSize = NewC.Op0.getValueType().getSizeInBits();
01526   unsigned NewCCMask, ShiftVal;
01527   if (NewC.ICmpType != SystemZICMP::SignedOnly &&
01528       NewC.Op0.getOpcode() == ISD::SHL &&
01529       isSimpleShift(NewC.Op0, ShiftVal) &&
01530       (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
01531                                         MaskVal >> ShiftVal,
01532                                         CmpVal >> ShiftVal,
01533                                         SystemZICMP::Any))) {
01534     NewC.Op0 = NewC.Op0.getOperand(0);
01535     MaskVal >>= ShiftVal;
01536   } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
01537              NewC.Op0.getOpcode() == ISD::SRL &&
01538              isSimpleShift(NewC.Op0, ShiftVal) &&
01539              (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
01540                                                MaskVal << ShiftVal,
01541                                                CmpVal << ShiftVal,
01542                                                SystemZICMP::UnsignedOnly))) {
01543     NewC.Op0 = NewC.Op0.getOperand(0);
01544     MaskVal <<= ShiftVal;
01545   } else {
01546     NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
01547                                      NewC.ICmpType);
01548     if (!NewCCMask)
01549       return;
01550   }
01551 
01552   // Go ahead and make the change.
01553   C.Opcode = SystemZISD::TM;
01554   C.Op0 = NewC.Op0;
01555   if (Mask && Mask->getZExtValue() == MaskVal)
01556     C.Op1 = SDValue(Mask, 0);
01557   else
01558     C.Op1 = DAG.getConstant(MaskVal, C.Op0.getValueType());
01559   C.CCValid = SystemZ::CCMASK_TM;
01560   C.CCMask = NewCCMask;
01561 }
01562 
01563 // Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
01564 static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
01565                          ISD::CondCode Cond) {
01566   Comparison C(CmpOp0, CmpOp1);
01567   C.CCMask = CCMaskForCondCode(Cond);
01568   if (C.Op0.getValueType().isFloatingPoint()) {
01569     C.CCValid = SystemZ::CCMASK_FCMP;
01570     C.Opcode = SystemZISD::FCMP;
01571     adjustForFNeg(C);
01572   } else {
01573     C.CCValid = SystemZ::CCMASK_ICMP;
01574     C.Opcode = SystemZISD::ICMP;
01575     // Choose the type of comparison.  Equality and inequality tests can
01576     // use either signed or unsigned comparisons.  The choice also doesn't
01577     // matter if both sign bits are known to be clear.  In those cases we
01578     // want to give the main isel code the freedom to choose whichever
01579     // form fits best.
01580     if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
01581         C.CCMask == SystemZ::CCMASK_CMP_NE ||
01582         (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
01583       C.ICmpType = SystemZICMP::Any;
01584     else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
01585       C.ICmpType = SystemZICMP::UnsignedOnly;
01586     else
01587       C.ICmpType = SystemZICMP::SignedOnly;
01588     C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
01589     adjustZeroCmp(DAG, C);
01590     adjustSubwordCmp(DAG, C);
01591     adjustForSubtraction(DAG, C);
01592     adjustForLTGFR(C);
01593     adjustICmpTruncate(DAG, C);
01594   }
01595 
01596   if (shouldSwapCmpOperands(C)) {
01597     std::swap(C.Op0, C.Op1);
01598     C.CCMask = reverseCCMask(C.CCMask);
01599   }
01600 
01601   adjustForTestUnderMask(DAG, C);
01602   return C;
01603 }
01604 
01605 // Emit the comparison instruction described by C.
01606 static SDValue emitCmp(SelectionDAG &DAG, SDLoc DL, Comparison &C) {
01607   if (C.Opcode == SystemZISD::ICMP)
01608     return DAG.getNode(SystemZISD::ICMP, DL, MVT::Glue, C.Op0, C.Op1,
01609                        DAG.getConstant(C.ICmpType, MVT::i32));
01610   if (C.Opcode == SystemZISD::TM) {
01611     bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
01612                          bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_1));
01613     return DAG.getNode(SystemZISD::TM, DL, MVT::Glue, C.Op0, C.Op1,
01614                        DAG.getConstant(RegisterOnly, MVT::i32));
01615   }
01616   return DAG.getNode(C.Opcode, DL, MVT::Glue, C.Op0, C.Op1);
01617 }
01618 
01619 // Implement a 32-bit *MUL_LOHI operation by extending both operands to
01620 // 64 bits.  Extend is the extension type to use.  Store the high part
01621 // in Hi and the low part in Lo.
01622 static void lowerMUL_LOHI32(SelectionDAG &DAG, SDLoc DL,
01623                             unsigned Extend, SDValue Op0, SDValue Op1,
01624                             SDValue &Hi, SDValue &Lo) {
01625   Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
01626   Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
01627   SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
01628   Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, DAG.getConstant(32, MVT::i64));
01629   Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
01630   Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
01631 }
01632 
01633 // Lower a binary operation that produces two VT results, one in each
01634 // half of a GR128 pair.  Op0 and Op1 are the VT operands to the operation,
01635 // Extend extends Op0 to a GR128, and Opcode performs the GR128 operation
01636 // on the extended Op0 and (unextended) Op1.  Store the even register result
01637 // in Even and the odd register result in Odd.
01638 static void lowerGR128Binary(SelectionDAG &DAG, SDLoc DL, EVT VT,
01639                              unsigned Extend, unsigned Opcode,
01640                              SDValue Op0, SDValue Op1,
01641                              SDValue &Even, SDValue &Odd) {
01642   SDNode *In128 = DAG.getMachineNode(Extend, DL, MVT::Untyped, Op0);
01643   SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped,
01644                                SDValue(In128, 0), Op1);
01645   bool Is32Bit = is32Bit(VT);
01646   Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
01647   Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
01648 }
01649 
01650 // Return an i32 value that is 1 if the CC value produced by Glue is
01651 // in the mask CCMask and 0 otherwise.  CC is known to have a value
01652 // in CCValid, so other values can be ignored.
01653 static SDValue emitSETCC(SelectionDAG &DAG, SDLoc DL, SDValue Glue,
01654                          unsigned CCValid, unsigned CCMask) {
01655   IPMConversion Conversion = getIPMConversion(CCValid, CCMask);
01656   SDValue Result = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, Glue);
01657 
01658   if (Conversion.XORValue)
01659     Result = DAG.getNode(ISD::XOR, DL, MVT::i32, Result,
01660                          DAG.getConstant(Conversion.XORValue, MVT::i32));
01661 
01662   if (Conversion.AddValue)
01663     Result = DAG.getNode(ISD::ADD, DL, MVT::i32, Result,
01664                          DAG.getConstant(Conversion.AddValue, MVT::i32));
01665 
01666   // The SHR/AND sequence should get optimized to an RISBG.
01667   Result = DAG.getNode(ISD::SRL, DL, MVT::i32, Result,
01668                        DAG.getConstant(Conversion.Bit, MVT::i32));
01669   if (Conversion.Bit != 31)
01670     Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result,
01671                          DAG.getConstant(1, MVT::i32));
01672   return Result;
01673 }
01674 
01675 SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
01676                                           SelectionDAG &DAG) const {
01677   SDValue CmpOp0   = Op.getOperand(0);
01678   SDValue CmpOp1   = Op.getOperand(1);
01679   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
01680   SDLoc DL(Op);
01681 
01682   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC));
01683   SDValue Glue = emitCmp(DAG, DL, C);
01684   return emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
01685 }
01686 
01687 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
01688   SDValue Chain    = Op.getOperand(0);
01689   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
01690   SDValue CmpOp0   = Op.getOperand(2);
01691   SDValue CmpOp1   = Op.getOperand(3);
01692   SDValue Dest     = Op.getOperand(4);
01693   SDLoc DL(Op);
01694 
01695   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC));
01696   SDValue Glue = emitCmp(DAG, DL, C);
01697   return DAG.getNode(SystemZISD::BR_CCMASK, DL, Op.getValueType(),
01698                      Chain, DAG.getConstant(C.CCValid, MVT::i32),
01699                      DAG.getConstant(C.CCMask, MVT::i32), Dest, Glue);
01700 }
01701 
01702 // Return true if Pos is CmpOp and Neg is the negative of CmpOp,
01703 // allowing Pos and Neg to be wider than CmpOp.
01704 static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
01705   return (Neg.getOpcode() == ISD::SUB &&
01706           Neg.getOperand(0).getOpcode() == ISD::Constant &&
01707           cast<ConstantSDNode>(Neg.getOperand(0))->getZExtValue() == 0 &&
01708           Neg.getOperand(1) == Pos &&
01709           (Pos == CmpOp ||
01710            (Pos.getOpcode() == ISD::SIGN_EXTEND &&
01711             Pos.getOperand(0) == CmpOp)));
01712 }
01713 
01714 // Return the absolute or negative absolute of Op; IsNegative decides which.
01715 static SDValue getAbsolute(SelectionDAG &DAG, SDLoc DL, SDValue Op,
01716                            bool IsNegative) {
01717   Op = DAG.getNode(SystemZISD::IABS, DL, Op.getValueType(), Op);
01718   if (IsNegative)
01719     Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
01720                      DAG.getConstant(0, Op.getValueType()), Op);
01721   return Op;
01722 }
01723 
01724 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
01725                                               SelectionDAG &DAG) const {
01726   SDValue CmpOp0   = Op.getOperand(0);
01727   SDValue CmpOp1   = Op.getOperand(1);
01728   SDValue TrueOp   = Op.getOperand(2);
01729   SDValue FalseOp  = Op.getOperand(3);
01730   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
01731   SDLoc DL(Op);
01732 
01733   Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC));
01734 
01735   // Check for absolute and negative-absolute selections, including those
01736   // where the comparison value is sign-extended (for LPGFR and LNGFR).
01737   // This check supplements the one in DAGCombiner.
01738   if (C.Opcode == SystemZISD::ICMP &&
01739       C.CCMask != SystemZ::CCMASK_CMP_EQ &&
01740       C.CCMask != SystemZ::CCMASK_CMP_NE &&
01741       C.Op1.getOpcode() == ISD::Constant &&
01742       cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
01743     if (isAbsolute(C.Op0, TrueOp, FalseOp))
01744       return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
01745     if (isAbsolute(C.Op0, FalseOp, TrueOp))
01746       return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
01747   }
01748 
01749   SDValue Glue = emitCmp(DAG, DL, C);
01750 
01751   // Special case for handling -1/0 results.  The shifts we use here
01752   // should get optimized with the IPM conversion sequence.
01753   auto *TrueC = dyn_cast<ConstantSDNode>(TrueOp);
01754   auto *FalseC = dyn_cast<ConstantSDNode>(FalseOp);
01755   if (TrueC && FalseC) {
01756     int64_t TrueVal = TrueC->getSExtValue();
01757     int64_t FalseVal = FalseC->getSExtValue();
01758     if ((TrueVal == -1 && FalseVal == 0) || (TrueVal == 0 && FalseVal == -1)) {
01759       // Invert the condition if we want -1 on false.
01760       if (TrueVal == 0)
01761         C.CCMask ^= C.CCValid;
01762       SDValue Result = emitSETCC(DAG, DL, Glue, C.CCValid, C.CCMask);
01763       EVT VT = Op.getValueType();
01764       // Extend the result to VT.  Upper bits are ignored.
01765       if (!is32Bit(VT))
01766         Result = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Result);
01767       // Sign-extend from the low bit.
01768       SDValue ShAmt = DAG.getConstant(VT.getSizeInBits() - 1, MVT::i32);
01769       SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Result, ShAmt);
01770       return DAG.getNode(ISD::SRA, DL, VT, Shl, ShAmt);
01771     }
01772   }
01773 
01774   SmallVector<SDValue, 5> Ops;
01775   Ops.push_back(TrueOp);
01776   Ops.push_back(FalseOp);
01777   Ops.push_back(DAG.getConstant(C.CCValid, MVT::i32));
01778   Ops.push_back(DAG.getConstant(C.CCMask, MVT::i32));
01779   Ops.push_back(Glue);
01780 
01781   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
01782   return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VTs, &Ops[0], Ops.size());
01783 }
01784 
01785 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
01786                                                   SelectionDAG &DAG) const {
01787   SDLoc DL(Node);
01788   const GlobalValue *GV = Node->getGlobal();
01789   int64_t Offset = Node->getOffset();
01790   EVT PtrVT = getPointerTy();
01791   Reloc::Model RM = TM.getRelocationModel();
01792   CodeModel::Model CM = TM.getCodeModel();
01793 
01794   SDValue Result;
01795   if (Subtarget.isPC32DBLSymbol(GV, RM, CM)) {
01796     // Assign anchors at 1<<12 byte boundaries.
01797     uint64_t Anchor = Offset & ~uint64_t(0xfff);
01798     Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
01799     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
01800 
01801     // The offset can be folded into the address if it is aligned to a halfword.
01802     Offset -= Anchor;
01803     if (Offset != 0 && (Offset & 1) == 0) {
01804       SDValue Full = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
01805       Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
01806       Offset = 0;
01807     }
01808   } else {
01809     Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
01810     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
01811     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
01812                          MachinePointerInfo::getGOT(), false, false, false, 0);
01813   }
01814 
01815   // If there was a non-zero offset that we didn't fold, create an explicit
01816   // addition for it.
01817   if (Offset != 0)
01818     Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
01819                          DAG.getConstant(Offset, PtrVT));
01820 
01821   return Result;
01822 }
01823 
01824 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
01825                  SelectionDAG &DAG) const {
01826   SDLoc DL(Node);
01827   const GlobalValue *GV = Node->getGlobal();
01828   EVT PtrVT = getPointerTy();
01829   TLSModel::Model model = TM.getTLSModel(GV);
01830 
01831   if (model != TLSModel::LocalExec)
01832     llvm_unreachable("only local-exec TLS mode supported");
01833 
01834   // The high part of the thread pointer is in access register 0.
01835   SDValue TPHi = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
01836                              DAG.getConstant(0, MVT::i32));
01837   TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
01838 
01839   // The low part of the thread pointer is in access register 1.
01840   SDValue TPLo = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
01841                              DAG.getConstant(1, MVT::i32));
01842   TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
01843 
01844   // Merge them into a single 64-bit address.
01845   SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
01846             DAG.getConstant(32, PtrVT));
01847   SDValue TP = DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
01848 
01849   // Get the offset of GA from the thread pointer.
01850   SystemZConstantPoolValue *CPV =
01851     SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF);
01852 
01853   // Force the offset into the constant pool and load it from there.
01854   SDValue CPAddr = DAG.getConstantPool(CPV, PtrVT, 8);
01855   SDValue Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
01856              CPAddr, MachinePointerInfo::getConstantPool(),
01857              false, false, false, 0);
01858 
01859   // Add the base and offset together.
01860   return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
01861 }
01862 
01863 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
01864                                                  SelectionDAG &DAG) const {
01865   SDLoc DL(Node);
01866   const BlockAddress *BA = Node->getBlockAddress();
01867   int64_t Offset = Node->getOffset();
01868   EVT PtrVT = getPointerTy();
01869 
01870   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
01871   Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
01872   return Result;
01873 }
01874 
01875 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
01876                                               SelectionDAG &DAG) const {
01877   SDLoc DL(JT);
01878   EVT PtrVT = getPointerTy();
01879   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
01880 
01881   // Use LARL to load the address of the table.
01882   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
01883 }
01884 
01885 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
01886                                                  SelectionDAG &DAG) const {
01887   SDLoc DL(CP);
01888   EVT PtrVT = getPointerTy();
01889 
01890   SDValue Result;
01891   if (CP->isMachineConstantPoolEntry())
01892     Result = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
01893                CP->getAlignment());
01894   else
01895     Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
01896                CP->getAlignment(), CP->getOffset());
01897 
01898   // Use LARL to load the address of the constant pool entry.
01899   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
01900 }
01901 
01902 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
01903                                             SelectionDAG &DAG) const {
01904   SDLoc DL(Op);
01905   SDValue In = Op.getOperand(0);
01906   EVT InVT = In.getValueType();
01907   EVT ResVT = Op.getValueType();
01908 
01909   if (InVT == MVT::i32 && ResVT == MVT::f32) {
01910     SDValue In64;
01911     if (Subtarget.hasHighWord()) {
01912       SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
01913                                        MVT::i64);
01914       In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
01915                                        MVT::i64, SDValue(U64, 0), In);
01916     } else {
01917       In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
01918       In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
01919                          DAG.getConstant(32, MVT::i64));
01920     }
01921     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
01922     return DAG.getTargetExtractSubreg(SystemZ::subreg_h32,
01923                                       DL, MVT::f32, Out64);
01924   }
01925   if (InVT == MVT::f32 && ResVT == MVT::i32) {
01926     SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
01927     SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
01928                                              MVT::f64, SDValue(U64, 0), In);
01929     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
01930     if (Subtarget.hasHighWord())
01931       return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
01932                                         MVT::i32, Out64);
01933     SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
01934                                 DAG.getConstant(32, MVT::i64));
01935     return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
01936   }
01937   llvm_unreachable("Unexpected bitcast combination");
01938 }
01939 
01940 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
01941                                             SelectionDAG &DAG) const {
01942   MachineFunction &MF = DAG.getMachineFunction();
01943   SystemZMachineFunctionInfo *FuncInfo =
01944     MF.getInfo<SystemZMachineFunctionInfo>();
01945   EVT PtrVT = getPointerTy();
01946 
01947   SDValue Chain   = Op.getOperand(0);
01948   SDValue Addr    = Op.getOperand(1);
01949   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
01950   SDLoc DL(Op);
01951 
01952   // The initial values of each field.
01953   const unsigned NumFields = 4;
01954   SDValue Fields[NumFields] = {
01955     DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), PtrVT),
01956     DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), PtrVT),
01957     DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
01958     DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
01959   };
01960 
01961   // Store each field into its respective slot.
01962   SDValue MemOps[NumFields];
01963   unsigned Offset = 0;
01964   for (unsigned I = 0; I < NumFields; ++I) {
01965     SDValue FieldAddr = Addr;
01966     if (Offset != 0)
01967       FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
01968                               DAG.getIntPtrConstant(Offset));
01969     MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
01970                              MachinePointerInfo(SV, Offset),
01971                              false, false, 0);
01972     Offset += 8;
01973   }
01974   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps, NumFields);
01975 }
01976 
01977 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
01978                                            SelectionDAG &DAG) const {
01979   SDValue Chain      = Op.getOperand(0);
01980   SDValue DstPtr     = Op.getOperand(1);
01981   SDValue SrcPtr     = Op.getOperand(2);
01982   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
01983   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
01984   SDLoc DL(Op);
01985 
01986   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32),
01987                        /*Align*/8, /*isVolatile*/false, /*AlwaysInline*/false,
01988                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
01989 }
01990 
01991 SDValue SystemZTargetLowering::
01992 lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
01993   SDValue Chain = Op.getOperand(0);
01994   SDValue Size  = Op.getOperand(1);
01995   SDLoc DL(Op);
01996 
01997   unsigned SPReg = getStackPointerRegisterToSaveRestore();
01998 
01999   // Get a reference to the stack pointer.
02000   SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
02001 
02002   // Get the new stack pointer value.
02003   SDValue NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, Size);
02004 
02005   // Copy the new stack pointer back.
02006   Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
02007 
02008   // The allocated data lives above the 160 bytes allocated for the standard
02009   // frame, plus any outgoing stack arguments.  We don't know how much that
02010   // amounts to yet, so emit a special ADJDYNALLOC placeholder.
02011   SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
02012   SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
02013 
02014   SDValue Ops[2] = { Result, Chain };
02015   return DAG.getMergeValues(Ops, 2, DL);
02016 }
02017 
02018 SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
02019                                               SelectionDAG &DAG) const {
02020   EVT VT = Op.getValueType();
02021   SDLoc DL(Op);
02022   SDValue Ops[2];
02023   if (is32Bit(VT))
02024     // Just do a normal 64-bit multiplication and extract the results.
02025     // We define this so that it can be used for constant division.
02026     lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
02027                     Op.getOperand(1), Ops[1], Ops[0]);
02028   else {
02029     // Do a full 128-bit multiplication based on UMUL_LOHI64:
02030     //
02031     //   (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
02032     //
02033     // but using the fact that the upper halves are either all zeros
02034     // or all ones:
02035     //
02036     //   (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
02037     //
02038     // and grouping the right terms together since they are quicker than the
02039     // multiplication:
02040     //
02041     //   (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
02042     SDValue C63 = DAG.getConstant(63, MVT::i64);
02043     SDValue LL = Op.getOperand(0);
02044     SDValue RL = Op.getOperand(1);
02045     SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
02046     SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
02047     // UMUL_LOHI64 returns the low result in the odd register and the high
02048     // result in the even register.  SMUL_LOHI is defined to return the
02049     // low half first, so the results are in reverse order.
02050     lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
02051                      LL, RL, Ops[1], Ops[0]);
02052     SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
02053     SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
02054     SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
02055     Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
02056   }
02057   return DAG.getMergeValues(Ops, 2, DL);
02058 }
02059 
02060 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
02061                                               SelectionDAG &DAG) const {
02062   EVT VT = Op.getValueType();
02063   SDLoc DL(Op);
02064   SDValue Ops[2];
02065   if (is32Bit(VT))
02066     // Just do a normal 64-bit multiplication and extract the results.
02067     // We define this so that it can be used for constant division.
02068     lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
02069                     Op.getOperand(1), Ops[1], Ops[0]);
02070   else
02071     // UMUL_LOHI64 returns the low result in the odd register and the high
02072     // result in the even register.  UMUL_LOHI is defined to return the
02073     // low half first, so the results are in reverse order.
02074     lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
02075                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
02076   return DAG.getMergeValues(Ops, 2, DL);
02077 }
02078 
02079 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
02080                                             SelectionDAG &DAG) const {
02081   SDValue Op0 = Op.getOperand(0);
02082   SDValue Op1 = Op.getOperand(1);
02083   EVT VT = Op.getValueType();
02084   SDLoc DL(Op);
02085   unsigned Opcode;
02086 
02087   // We use DSGF for 32-bit division.
02088   if (is32Bit(VT)) {
02089     Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
02090     Opcode = SystemZISD::SDIVREM32;
02091   } else if (DAG.ComputeNumSignBits(Op1) > 32) {
02092     Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
02093     Opcode = SystemZISD::SDIVREM32;
02094   } else    
02095     Opcode = SystemZISD::SDIVREM64;
02096 
02097   // DSG(F) takes a 64-bit dividend, so the even register in the GR128
02098   // input is "don't care".  The instruction returns the remainder in
02099   // the even register and the quotient in the odd register.
02100   SDValue Ops[2];
02101   lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, Opcode,
02102                    Op0, Op1, Ops[1], Ops[0]);
02103   return DAG.getMergeValues(Ops, 2, DL);
02104 }
02105 
02106 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
02107                                             SelectionDAG &DAG) const {
02108   EVT VT = Op.getValueType();
02109   SDLoc DL(Op);
02110 
02111   // DL(G) uses a double-width dividend, so we need to clear the even
02112   // register in the GR128 input.  The instruction returns the remainder
02113   // in the even register and the quotient in the odd register.
02114   SDValue Ops[2];
02115   if (is32Bit(VT))
02116     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_32, SystemZISD::UDIVREM32,
02117                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
02118   else
02119     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_64, SystemZISD::UDIVREM64,
02120                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
02121   return DAG.getMergeValues(Ops, 2, DL);
02122 }
02123 
02124 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
02125   assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
02126 
02127   // Get the known-zero masks for each operand.
02128   SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
02129   APInt KnownZero[2], KnownOne[2];
02130   DAG.ComputeMaskedBits(Ops[0], KnownZero[0], KnownOne[0]);
02131   DAG.ComputeMaskedBits(Ops[1], KnownZero[1], KnownOne[1]);
02132 
02133   // See if the upper 32 bits of one operand and the lower 32 bits of the
02134   // other are known zero.  They are the low and high operands respectively.
02135   uint64_t Masks[] = { KnownZero[0].getZExtValue(),
02136                        KnownZero[1].getZExtValue() };
02137   unsigned High, Low;
02138   if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
02139     High = 1, Low = 0;
02140   else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
02141     High = 0, Low = 1;
02142   else
02143     return Op;
02144 
02145   SDValue LowOp = Ops[Low];
02146   SDValue HighOp = Ops[High];
02147 
02148   // If the high part is a constant, we're better off using IILH.
02149   if (HighOp.getOpcode() == ISD::Constant)
02150     return Op;
02151 
02152   // If the low part is a constant that is outside the range of LHI,
02153   // then we're better off using IILF.
02154   if (LowOp.getOpcode() == ISD::Constant) {
02155     int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
02156     if (!isInt<16>(Value))
02157       return Op;
02158   }
02159 
02160   // Check whether the high part is an AND that doesn't change the
02161   // high 32 bits and just masks out low bits.  We can skip it if so.
02162   if (HighOp.getOpcode() == ISD::AND &&
02163       HighOp.getOperand(1).getOpcode() == ISD::Constant) {
02164     SDValue HighOp0 = HighOp.getOperand(0);
02165     uint64_t Mask = cast<ConstantSDNode>(HighOp.getOperand(1))->getZExtValue();
02166     if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
02167       HighOp = HighOp0;
02168   }
02169 
02170   // Take advantage of the fact that all GR32 operations only change the
02171   // low 32 bits by truncating Low to an i32 and inserting it directly
02172   // using a subreg.  The interesting cases are those where the truncation
02173   // can be folded.
02174   SDLoc DL(Op);
02175   SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
02176   return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
02177                                    MVT::i64, HighOp, Low32);
02178 }
02179 
02180 // Op is an atomic load.  Lower it into a normal volatile load.
02181 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
02182                                                 SelectionDAG &DAG) const {
02183   auto *Node = cast<AtomicSDNode>(Op.getNode());
02184   return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), Op.getValueType(),
02185                         Node->getChain(), Node->getBasePtr(),
02186                         Node->getMemoryVT(), Node->getMemOperand());
02187 }
02188 
02189 // Op is an atomic store.  Lower it into a normal volatile store followed
02190 // by a serialization.
02191 SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
02192                                                  SelectionDAG &DAG) const {
02193   auto *Node = cast<AtomicSDNode>(Op.getNode());
02194   SDValue Chain = DAG.getTruncStore(Node->getChain(), SDLoc(Op), Node->getVal(),
02195                                     Node->getBasePtr(), Node->getMemoryVT(),
02196                                     Node->getMemOperand());
02197   return SDValue(DAG.getMachineNode(SystemZ::Serialize, SDLoc(Op), MVT::Other,
02198                                     Chain), 0);
02199 }
02200 
02201 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation.  Lower the first
02202 // two into the fullword ATOMIC_LOADW_* operation given by Opcode.
02203 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op,
02204                                                    SelectionDAG &DAG,
02205                                                    unsigned Opcode) const {
02206   auto *Node = cast<AtomicSDNode>(Op.getNode());
02207 
02208   // 32-bit operations need no code outside the main loop.
02209   EVT NarrowVT = Node->getMemoryVT();
02210   EVT WideVT = MVT::i32;
02211   if (NarrowVT == WideVT)
02212     return Op;
02213 
02214   int64_t BitSize = NarrowVT.getSizeInBits();
02215   SDValue ChainIn = Node->getChain();
02216   SDValue Addr = Node->getBasePtr();
02217   SDValue Src2 = Node->getVal();
02218   MachineMemOperand *MMO = Node->getMemOperand();
02219   SDLoc DL(Node);
02220   EVT PtrVT = Addr.getValueType();
02221 
02222   // Convert atomic subtracts of constants into additions.
02223   if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
02224     if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
02225       Opcode = SystemZISD::ATOMIC_LOADW_ADD;
02226       Src2 = DAG.getConstant(-Const->getSExtValue(), Src2.getValueType());
02227     }
02228 
02229   // Get the address of the containing word.
02230   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
02231                                     DAG.getConstant(-4, PtrVT));
02232 
02233   // Get the number of bits that the word must be rotated left in order
02234   // to bring the field to the top bits of a GR32.
02235   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
02236                                  DAG.getConstant(3, PtrVT));
02237   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
02238 
02239   // Get the complementing shift amount, for rotating a field in the top
02240   // bits back to its proper position.
02241   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
02242                                     DAG.getConstant(0, WideVT), BitShift);
02243 
02244   // Extend the source operand to 32 bits and prepare it for the inner loop.
02245   // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
02246   // operations require the source to be shifted in advance.  (This shift
02247   // can be folded if the source is constant.)  For AND and NAND, the lower
02248   // bits must be set, while for other opcodes they should be left clear.
02249   if (Opcode != SystemZISD::ATOMIC_SWAPW)
02250     Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
02251                        DAG.getConstant(32 - BitSize, WideVT));
02252   if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
02253       Opcode == SystemZISD::ATOMIC_LOADW_NAND)
02254     Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
02255                        DAG.getConstant(uint32_t(-1) >> BitSize, WideVT));
02256 
02257   // Construct the ATOMIC_LOADW_* node.
02258   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
02259   SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
02260                     DAG.getConstant(BitSize, WideVT) };
02261   SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
02262                                              array_lengthof(Ops),
02263                                              NarrowVT, MMO);
02264 
02265   // Rotate the result of the final CS so that the field is in the lower
02266   // bits of a GR32, then truncate it.
02267   SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
02268                                     DAG.getConstant(BitSize, WideVT));
02269   SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
02270 
02271   SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
02272   return DAG.getMergeValues(RetOps, 2, DL);
02273 }
02274 
02275 // Op is an ATOMIC_LOAD_SUB operation.  Lower 8- and 16-bit operations
02276 // into ATOMIC_LOADW_SUBs and decide whether to convert 32- and 64-bit
02277 // operations into additions.
02278 SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
02279                                                     SelectionDAG &DAG) const {
02280   auto *Node = cast<AtomicSDNode>(Op.getNode());
02281   EVT MemVT = Node->getMemoryVT();
02282   if (MemVT == MVT::i32 || MemVT == MVT::i64) {
02283     // A full-width operation.
02284     assert(Op.getValueType() == MemVT && "Mismatched VTs");
02285     SDValue Src2 = Node->getVal();
02286     SDValue NegSrc2;
02287     SDLoc DL(Src2);
02288 
02289     if (auto *Op2 = dyn_cast<ConstantSDNode>(Src2)) {
02290       // Use an addition if the operand is constant and either LAA(G) is
02291       // available or the negative value is in the range of A(G)FHI.
02292       int64_t Value = (-Op2->getAPIntValue()).getSExtValue();
02293       if (isInt<32>(Value) || TM.getSubtargetImpl()->hasInterlockedAccess1())
02294         NegSrc2 = DAG.getConstant(Value, MemVT);
02295     } else if (TM.getSubtargetImpl()->hasInterlockedAccess1())
02296       // Use LAA(G) if available.
02297       NegSrc2 = DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, MemVT),
02298                             Src2);
02299 
02300     if (NegSrc2.getNode())
02301       return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT,
02302                            Node->getChain(), Node->getBasePtr(), NegSrc2,
02303                            Node->getMemOperand(), Node->getOrdering(),
02304                            Node->getSynchScope());
02305 
02306     // Use the node as-is.
02307     return Op;
02308   }
02309 
02310   return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
02311 }
02312 
02313 // Node is an 8- or 16-bit ATOMIC_CMP_SWAP operation.  Lower the first two
02314 // into a fullword ATOMIC_CMP_SWAPW operation.
02315 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
02316                                                     SelectionDAG &DAG) const {
02317   auto *Node = cast<AtomicSDNode>(Op.getNode());
02318 
02319   // We have native support for 32-bit compare and swap.
02320   EVT NarrowVT = Node->getMemoryVT();
02321   EVT WideVT = MVT::i32;
02322   if (NarrowVT == WideVT)
02323     return Op;
02324 
02325   int64_t BitSize = NarrowVT.getSizeInBits();
02326   SDValue ChainIn = Node->getOperand(0);
02327   SDValue Addr = Node->getOperand(1);
02328   SDValue CmpVal = Node->getOperand(2);
02329   SDValue SwapVal = Node->getOperand(3);
02330   MachineMemOperand *MMO = Node->getMemOperand();
02331   SDLoc DL(Node);
02332   EVT PtrVT = Addr.getValueType();
02333 
02334   // Get the address of the containing word.
02335   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
02336                                     DAG.getConstant(-4, PtrVT));
02337 
02338   // Get the number of bits that the word must be rotated left in order
02339   // to bring the field to the top bits of a GR32.
02340   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
02341                                  DAG.getConstant(3, PtrVT));
02342   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
02343 
02344   // Get the complementing shift amount, for rotating a field in the top
02345   // bits back to its proper position.
02346   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
02347                                     DAG.getConstant(0, WideVT), BitShift);
02348 
02349   // Construct the ATOMIC_CMP_SWAPW node.
02350   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
02351   SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
02352                     NegBitShift, DAG.getConstant(BitSize, WideVT) };
02353   SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
02354                                              VTList, Ops, array_lengthof(Ops),
02355                                              NarrowVT, MMO);
02356   return AtomicOp;
02357 }
02358 
02359 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
02360                                               SelectionDAG &DAG) const {
02361   MachineFunction &MF = DAG.getMachineFunction();
02362   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
02363   return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
02364                             SystemZ::R15D, Op.getValueType());
02365 }
02366 
02367 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
02368                                                  SelectionDAG &DAG) const {
02369   MachineFunction &MF = DAG.getMachineFunction();
02370   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
02371   return DAG.getCopyToReg(Op.getOperand(0), SDLoc(Op),
02372                           SystemZ::R15D, Op.getOperand(1));
02373 }
02374 
02375 SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
02376                                              SelectionDAG &DAG) const {
02377   bool IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
02378   if (!IsData)
02379     // Just preserve the chain.
02380     return Op.getOperand(0);
02381 
02382   bool IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
02383   unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
02384   auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
02385   SDValue Ops[] = {
02386     Op.getOperand(0),
02387     DAG.getConstant(Code, MVT::i32),
02388     Op.getOperand(1)
02389   };
02390   return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, SDLoc(Op),
02391                                  Node->getVTList(), Ops, array_lengthof(Ops),
02392                                  Node->getMemoryVT(), Node->getMemOperand());
02393 }
02394 
02395 SDValue SystemZTargetLowering::LowerOperation(SDValue Op,
02396                                               SelectionDAG &DAG) const {
02397   switch (Op.getOpcode()) {
02398   case ISD::BR_CC:
02399     return lowerBR_CC(Op, DAG);
02400   case ISD::SELECT_CC:
02401     return lowerSELECT_CC(Op, DAG);
02402   case ISD::SETCC:
02403     return lowerSETCC(Op, DAG);
02404   case ISD::GlobalAddress:
02405     return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
02406   case ISD::GlobalTLSAddress:
02407     return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
02408   case ISD::BlockAddress:
02409     return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
02410   case ISD::JumpTable:
02411     return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
02412   case ISD::ConstantPool:
02413     return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
02414   case ISD::BITCAST:
02415     return lowerBITCAST(Op, DAG);
02416   case ISD::VASTART:
02417     return lowerVASTART(Op, DAG);
02418   case ISD::VACOPY:
02419     return lowerVACOPY(Op, DAG);
02420   case ISD::DYNAMIC_STACKALLOC:
02421     return lowerDYNAMIC_STACKALLOC(Op, DAG);
02422   case ISD::SMUL_LOHI:
02423     return lowerSMUL_LOHI(Op, DAG);
02424   case ISD::UMUL_LOHI:
02425     return lowerUMUL_LOHI(Op, DAG);
02426   case ISD::SDIVREM:
02427     return lowerSDIVREM(Op, DAG);
02428   case ISD::UDIVREM:
02429     return lowerUDIVREM(Op, DAG);
02430   case ISD::OR:
02431     return lowerOR(Op, DAG);
02432   case ISD::ATOMIC_SWAP:
02433     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_SWAPW);
02434   case ISD::ATOMIC_STORE:
02435     return lowerATOMIC_STORE(Op, DAG);
02436   case ISD::ATOMIC_LOAD:
02437     return lowerATOMIC_LOAD(Op, DAG);
02438   case ISD::ATOMIC_LOAD_ADD:
02439     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
02440   case ISD::ATOMIC_LOAD_SUB:
02441     return lowerATOMIC_LOAD_SUB(Op, DAG);
02442   case ISD::ATOMIC_LOAD_AND:
02443     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
02444   case ISD::ATOMIC_LOAD_OR:
02445     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
02446   case ISD::ATOMIC_LOAD_XOR:
02447     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
02448   case ISD::ATOMIC_LOAD_NAND:
02449     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
02450   case ISD::ATOMIC_LOAD_MIN:
02451     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
02452   case ISD::ATOMIC_LOAD_MAX:
02453     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
02454   case ISD::ATOMIC_LOAD_UMIN:
02455     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
02456   case ISD::ATOMIC_LOAD_UMAX:
02457     return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
02458   case ISD::ATOMIC_CMP_SWAP:
02459     return lowerATOMIC_CMP_SWAP(Op, DAG);
02460   case ISD::STACKSAVE:
02461     return lowerSTACKSAVE(Op, DAG);
02462   case ISD::STACKRESTORE:
02463     return lowerSTACKRESTORE(Op, DAG);
02464   case ISD::PREFETCH:
02465     return lowerPREFETCH(Op, DAG);
02466   default:
02467     llvm_unreachable("Unexpected node to lower");
02468   }
02469 }
02470 
02471 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
02472 #define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME
02473   switch (Opcode) {
02474     OPCODE(RET_FLAG);
02475     OPCODE(CALL);
02476     OPCODE(SIBCALL);
02477     OPCODE(PCREL_WRAPPER);
02478     OPCODE(PCREL_OFFSET);
02479     OPCODE(IABS);
02480     OPCODE(ICMP);
02481     OPCODE(FCMP);
02482     OPCODE(TM);
02483     OPCODE(BR_CCMASK);
02484     OPCODE(SELECT_CCMASK);
02485     OPCODE(ADJDYNALLOC);
02486     OPCODE(EXTRACT_ACCESS);
02487     OPCODE(UMUL_LOHI64);
02488     OPCODE(SDIVREM64);
02489     OPCODE(UDIVREM32);
02490     OPCODE(UDIVREM64);
02491     OPCODE(MVC);
02492     OPCODE(MVC_LOOP);
02493     OPCODE(NC);
02494     OPCODE(NC_LOOP);
02495     OPCODE(OC);
02496     OPCODE(OC_LOOP);
02497     OPCODE(XC);
02498     OPCODE(XC_LOOP);
02499     OPCODE(CLC);
02500     OPCODE(CLC_LOOP);
02501     OPCODE(STRCMP);
02502     OPCODE(STPCPY);
02503     OPCODE(SEARCH_STRING);
02504     OPCODE(IPM);
02505     OPCODE(SERIALIZE);
02506     OPCODE(ATOMIC_SWAPW);
02507     OPCODE(ATOMIC_LOADW_ADD);
02508     OPCODE(ATOMIC_LOADW_SUB);
02509     OPCODE(ATOMIC_LOADW_AND);
02510     OPCODE(ATOMIC_LOADW_OR);
02511     OPCODE(ATOMIC_LOADW_XOR);
02512     OPCODE(ATOMIC_LOADW_NAND);
02513     OPCODE(ATOMIC_LOADW_MIN);
02514     OPCODE(ATOMIC_LOADW_MAX);
02515     OPCODE(ATOMIC_LOADW_UMIN);
02516     OPCODE(ATOMIC_LOADW_UMAX);
02517     OPCODE(ATOMIC_CMP_SWAPW);
02518     OPCODE(PREFETCH);
02519   }
02520   return NULL;
02521 #undef OPCODE
02522 }
02523 
02524 SDValue SystemZTargetLowering::PerformDAGCombine(SDNode *N,
02525                                                  DAGCombinerInfo &DCI) const {
02526   SelectionDAG &DAG = DCI.DAG;
02527   unsigned Opcode = N->getOpcode();
02528   if (Opcode == ISD::SIGN_EXTEND) {
02529     // Convert (sext (ashr (shl X, C1), C2)) to
02530     // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
02531     // cheap as narrower ones.
02532     SDValue N0 = N->getOperand(0);
02533     EVT VT = N->getValueType(0);
02534     if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
02535       auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
02536       SDValue Inner = N0.getOperand(0);
02537       if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
02538         if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
02539           unsigned Extra = (VT.getSizeInBits() -
02540                             N0.getValueType().getSizeInBits());
02541           unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
02542           unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
02543           EVT ShiftVT = N0.getOperand(1).getValueType();
02544           SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
02545                                     Inner.getOperand(0));
02546           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
02547                                     DAG.getConstant(NewShlAmt, ShiftVT));
02548           return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
02549                              DAG.getConstant(NewSraAmt, ShiftVT));
02550         }
02551       }
02552     }
02553   }
02554   return SDValue();
02555 }
02556 
02557 //===----------------------------------------------------------------------===//
02558 // Custom insertion
02559 //===----------------------------------------------------------------------===//
02560 
02561 // Create a new basic block after MBB.
02562 static MachineBasicBlock *emitBlockAfter(MachineBasicBlock *MBB) {
02563   MachineFunction &MF = *MBB->getParent();
02564   MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(MBB->getBasicBlock());
02565   MF.insert(std::next(MachineFunction::iterator(MBB)), NewMBB);
02566   return NewMBB;
02567 }
02568 
02569 // Split MBB after MI and return the new block (the one that contains
02570 // instructions after MI).
02571 static MachineBasicBlock *splitBlockAfter(MachineInstr *MI,
02572                                           MachineBasicBlock *MBB) {
02573   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
02574   NewMBB->splice(NewMBB->begin(), MBB,
02575                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
02576   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
02577   return NewMBB;
02578 }
02579 
02580 // Split MBB before MI and return the new block (the one that contains MI).
02581 static MachineBasicBlock *splitBlockBefore(MachineInstr *MI,
02582                                            MachineBasicBlock *MBB) {
02583   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
02584   NewMBB->splice(NewMBB->begin(), MBB, MI, MBB->end());
02585   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
02586   return NewMBB;
02587 }
02588 
02589 // Force base value Base into a register before MI.  Return the register.
02590 static unsigned forceReg(MachineInstr *MI, MachineOperand &Base,
02591                          const SystemZInstrInfo *TII) {
02592   if (Base.isReg())
02593     return Base.getReg();
02594 
02595   MachineBasicBlock *MBB = MI->getParent();
02596   MachineFunction &MF = *MBB->getParent();
02597   MachineRegisterInfo &MRI = MF.getRegInfo();
02598 
02599   unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
02600   BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LA), Reg)
02601     .addOperand(Base).addImm(0).addReg(0);
02602   return Reg;
02603 }
02604 
02605 // Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
02606 MachineBasicBlock *
02607 SystemZTargetLowering::emitSelect(MachineInstr *MI,
02608                                   MachineBasicBlock *MBB) const {
02609   const SystemZInstrInfo *TII = TM.getInstrInfo();
02610 
02611   unsigned DestReg  = MI->getOperand(0).getReg();
02612   unsigned TrueReg  = MI->getOperand(1).getReg();
02613   unsigned FalseReg = MI->getOperand(2).getReg();
02614   unsigned CCValid  = MI->getOperand(3).getImm();
02615   unsigned CCMask   = MI->getOperand(4).getImm();
02616   DebugLoc DL       = MI->getDebugLoc();
02617 
02618   MachineBasicBlock *StartMBB = MBB;
02619   MachineBasicBlock *JoinMBB  = splitBlockBefore(MI, MBB);
02620   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
02621 
02622   //  StartMBB:
02623   //   BRC CCMask, JoinMBB
02624   //   # fallthrough to FalseMBB
02625   MBB = StartMBB;
02626   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
02627     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
02628   MBB->addSuccessor(JoinMBB);
02629   MBB->addSuccessor(FalseMBB);
02630 
02631   //  FalseMBB:
02632   //   # fallthrough to JoinMBB
02633   MBB = FalseMBB;
02634   MBB->addSuccessor(JoinMBB);
02635 
02636   //  JoinMBB:
02637   //   %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
02638   //  ...
02639   MBB = JoinMBB;
02640   BuildMI(*MBB, MI, DL, TII->get(SystemZ::PHI), DestReg)
02641     .addReg(TrueReg).addMBB(StartMBB)
02642     .addReg(FalseReg).addMBB(FalseMBB);
02643 
02644   MI->eraseFromParent();
02645   return JoinMBB;
02646 }
02647 
02648 // Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
02649 // StoreOpcode is the store to use and Invert says whether the store should
02650 // happen when the condition is false rather than true.  If a STORE ON
02651 // CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
02652 MachineBasicBlock *
02653 SystemZTargetLowering::emitCondStore(MachineInstr *MI,
02654                                      MachineBasicBlock *MBB,
02655                                      unsigned StoreOpcode, unsigned STOCOpcode,
02656                                      bool Invert) const {
02657   const SystemZInstrInfo *TII = TM.getInstrInfo();
02658 
02659   unsigned SrcReg     = MI->getOperand(0).getReg();
02660   MachineOperand Base = MI->getOperand(1);
02661   int64_t Disp        = MI->getOperand(2).getImm();
02662   unsigned IndexReg   = MI->getOperand(3).getReg();
02663   unsigned CCValid    = MI->getOperand(4).getImm();
02664   unsigned CCMask     = MI->getOperand(5).getImm();
02665   DebugLoc DL         = MI->getDebugLoc();
02666 
02667   StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
02668 
02669   // Use STOCOpcode if possible.  We could use different store patterns in
02670   // order to avoid matching the index register, but the performance trade-offs
02671   // might be more complicated in that case.
02672   if (STOCOpcode && !IndexReg && TM.getSubtargetImpl()->hasLoadStoreOnCond()) {
02673     if (Invert)
02674       CCMask ^= CCValid;
02675     BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
02676       .addReg(SrcReg).addOperand(Base).addImm(Disp)
02677       .addImm(CCValid).addImm(CCMask);
02678     MI->eraseFromParent();
02679     return MBB;
02680   }
02681 
02682   // Get the condition needed to branch around the store.
02683   if (!Invert)
02684     CCMask ^= CCValid;
02685 
02686   MachineBasicBlock *StartMBB = MBB;
02687   MachineBasicBlock *JoinMBB  = splitBlockBefore(MI, MBB);
02688   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
02689 
02690   //  StartMBB:
02691   //   BRC CCMask, JoinMBB
02692   //   # fallthrough to FalseMBB
02693   MBB = StartMBB;
02694   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
02695     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
02696   MBB->addSuccessor(JoinMBB);
02697   MBB->addSuccessor(FalseMBB);
02698 
02699   //  FalseMBB:
02700   //   store %SrcReg, %Disp(%Index,%Base)
02701   //   # fallthrough to JoinMBB
02702   MBB = FalseMBB;
02703   BuildMI(MBB, DL, TII->get(StoreOpcode))
02704     .addReg(SrcReg).addOperand(Base).addImm(Disp).addReg(IndexReg);
02705   MBB->addSuccessor(JoinMBB);
02706 
02707   MI->eraseFromParent();
02708   return JoinMBB;
02709 }
02710 
02711 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_LOAD{,W}_*
02712 // or ATOMIC_SWAP{,W} instruction MI.  BinOpcode is the instruction that
02713 // performs the binary operation elided by "*", or 0 for ATOMIC_SWAP{,W}.
02714 // BitSize is the width of the field in bits, or 0 if this is a partword
02715 // ATOMIC_LOADW_* or ATOMIC_SWAPW instruction, in which case the bitsize
02716 // is one of the operands.  Invert says whether the field should be
02717 // inverted after performing BinOpcode (e.g. for NAND).
02718 MachineBasicBlock *
02719 SystemZTargetLowering::emitAtomicLoadBinary(MachineInstr *MI,
02720                                             MachineBasicBlock *MBB,
02721                                             unsigned BinOpcode,
02722                                             unsigned BitSize,
02723                                             bool Invert) const {
02724   const SystemZInstrInfo *TII = TM.getInstrInfo();
02725   MachineFunction &MF = *MBB->getParent();
02726   MachineRegisterInfo &MRI = MF.getRegInfo();
02727   bool IsSubWord = (BitSize < 32);
02728 
02729   // Extract the operands.  Base can be a register or a frame index.
02730   // Src2 can be a register or immediate.
02731   unsigned Dest        = MI->getOperand(0).getReg();
02732   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
02733   int64_t Disp         = MI->getOperand(2).getImm();
02734   MachineOperand Src2  = earlyUseOperand(MI->getOperand(3));
02735   unsigned BitShift    = (IsSubWord ? MI->getOperand(4).getReg() : 0);
02736   unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
02737   DebugLoc DL          = MI->getDebugLoc();
02738   if (IsSubWord)
02739     BitSize = MI->getOperand(6).getImm();
02740 
02741   // Subword operations use 32-bit registers.
02742   const TargetRegisterClass *RC = (BitSize <= 32 ?
02743                                    &SystemZ::GR32BitRegClass :
02744                                    &SystemZ::GR64BitRegClass);
02745   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
02746   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
02747 
02748   // Get the right opcodes for the displacement.
02749   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
02750   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
02751   assert(LOpcode && CSOpcode && "Displacement out of range");
02752 
02753   // Create virtual registers for temporary results.
02754   unsigned OrigVal       = MRI.createVirtualRegister(RC);
02755   unsigned OldVal        = MRI.createVirtualRegister(RC);
02756   unsigned NewVal        = (BinOpcode || IsSubWord ?
02757                             MRI.createVirtualRegister(RC) : Src2.getReg());
02758   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
02759   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
02760 
02761   // Insert a basic block for the main loop.
02762   MachineBasicBlock *StartMBB = MBB;
02763   MachineBasicBlock *DoneMBB  = splitBlockBefore(MI, MBB);
02764   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
02765 
02766   //  StartMBB:
02767   //   ...
02768   //   %OrigVal = L Disp(%Base)
02769   //   # fall through to LoopMMB
02770   MBB = StartMBB;
02771   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
02772     .addOperand(Base).addImm(Disp).addReg(0);
02773   MBB->addSuccessor(LoopMBB);
02774 
02775   //  LoopMBB:
02776   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
02777   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
02778   //   %RotatedNewVal = OP %RotatedOldVal, %Src2
02779   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
02780   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
02781   //   JNE LoopMBB
02782   //   # fall through to DoneMMB
02783   MBB = LoopMBB;
02784   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
02785     .addReg(OrigVal).addMBB(StartMBB)
02786     .addReg(Dest).addMBB(LoopMBB);
02787   if (IsSubWord)
02788     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
02789       .addReg(OldVal).addReg(BitShift).addImm(0);
02790   if (Invert) {
02791     // Perform the operation normally and then invert every bit of the field.
02792     unsigned Tmp = MRI.createVirtualRegister(RC);
02793     BuildMI(MBB, DL, TII->get(BinOpcode), Tmp)
02794       .addReg(RotatedOldVal).addOperand(Src2);
02795     if (BitSize < 32)
02796       // XILF with the upper BitSize bits set.
02797       BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
02798         .addReg(Tmp).addImm(uint32_t(~0 << (32 - BitSize)));
02799     else if (BitSize == 32)
02800       // XILF with every bit set.
02801       BuildMI(MBB, DL, TII->get(SystemZ::XILF), RotatedNewVal)
02802         .addReg(Tmp).addImm(~uint32_t(0));
02803     else {
02804       // Use LCGR and add -1 to the result, which is more compact than
02805       // an XILF, XILH pair.
02806       unsigned Tmp2 = MRI.createVirtualRegister(RC);
02807       BuildMI(MBB, DL, TII->get(SystemZ::LCGR), Tmp2).addReg(Tmp);
02808       BuildMI(MBB, DL, TII->get(SystemZ::AGHI), RotatedNewVal)
02809         .addReg(Tmp2).addImm(-1);
02810     }
02811   } else if (BinOpcode)
02812     // A simply binary operation.
02813     BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
02814       .addReg(RotatedOldVal).addOperand(Src2);
02815   else if (IsSubWord)
02816     // Use RISBG to rotate Src2 into position and use it to replace the
02817     // field in RotatedOldVal.
02818     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
02819       .addReg(RotatedOldVal).addReg(Src2.getReg())
02820       .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize);
02821   if (IsSubWord)
02822     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
02823       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
02824   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
02825     .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
02826   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
02827     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
02828   MBB->addSuccessor(LoopMBB);
02829   MBB->addSuccessor(DoneMBB);
02830 
02831   MI->eraseFromParent();
02832   return DoneMBB;
02833 }
02834 
02835 // Implement EmitInstrWithCustomInserter for pseudo
02836 // ATOMIC_LOAD{,W}_{,U}{MIN,MAX} instruction MI.  CompareOpcode is the
02837 // instruction that should be used to compare the current field with the
02838 // minimum or maximum value.  KeepOldMask is the BRC condition-code mask
02839 // for when the current field should be kept.  BitSize is the width of
02840 // the field in bits, or 0 if this is a partword ATOMIC_LOADW_* instruction.
02841 MachineBasicBlock *
02842 SystemZTargetLowering::emitAtomicLoadMinMax(MachineInstr *MI,
02843                                             MachineBasicBlock *MBB,
02844                                             unsigned CompareOpcode,
02845                                             unsigned KeepOldMask,
02846                                             unsigned BitSize) const {
02847   const SystemZInstrInfo *TII = TM.getInstrInfo();
02848   MachineFunction &MF = *MBB->getParent();
02849   MachineRegisterInfo &MRI = MF.getRegInfo();
02850   bool IsSubWord = (BitSize < 32);
02851 
02852   // Extract the operands.  Base can be a register or a frame index.
02853   unsigned Dest        = MI->getOperand(0).getReg();
02854   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
02855   int64_t  Disp        = MI->getOperand(2).getImm();
02856   unsigned Src2        = MI->getOperand(3).getReg();
02857   unsigned BitShift    = (IsSubWord ? MI->getOperand(4).getReg() : 0);
02858   unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
02859   DebugLoc DL          = MI->getDebugLoc();
02860   if (IsSubWord)
02861     BitSize = MI->getOperand(6).getImm();
02862 
02863   // Subword operations use 32-bit registers.
02864   const TargetRegisterClass *RC = (BitSize <= 32 ?
02865                                    &SystemZ::GR32BitRegClass :
02866                                    &SystemZ::GR64BitRegClass);
02867   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
02868   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
02869 
02870   // Get the right opcodes for the displacement.
02871   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
02872   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
02873   assert(LOpcode && CSOpcode && "Displacement out of range");
02874 
02875   // Create virtual registers for temporary results.
02876   unsigned OrigVal       = MRI.createVirtualRegister(RC);
02877   unsigned OldVal        = MRI.createVirtualRegister(RC);
02878   unsigned NewVal        = MRI.createVirtualRegister(RC);
02879   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
02880   unsigned RotatedAltVal = (IsSubWord ? MRI.createVirtualRegister(RC) : Src2);
02881   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
02882 
02883   // Insert 3 basic blocks for the loop.
02884   MachineBasicBlock *StartMBB  = MBB;
02885   MachineBasicBlock *DoneMBB   = splitBlockBefore(MI, MBB);
02886   MachineBasicBlock *LoopMBB   = emitBlockAfter(StartMBB);
02887   MachineBasicBlock *UseAltMBB = emitBlockAfter(LoopMBB);
02888   MachineBasicBlock *UpdateMBB = emitBlockAfter(UseAltMBB);
02889 
02890   //  StartMBB:
02891   //   ...
02892   //   %OrigVal     = L Disp(%Base)
02893   //   # fall through to LoopMMB
02894   MBB = StartMBB;
02895   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
02896     .addOperand(Base).addImm(Disp).addReg(0);
02897   MBB->addSuccessor(LoopMBB);
02898 
02899   //  LoopMBB:
02900   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
02901   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
02902   //   CompareOpcode %RotatedOldVal, %Src2
02903   //   BRC KeepOldMask, UpdateMBB
02904   MBB = LoopMBB;
02905   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
02906     .addReg(OrigVal).addMBB(StartMBB)
02907     .addReg(Dest).addMBB(UpdateMBB);
02908   if (IsSubWord)
02909     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
02910       .addReg(OldVal).addReg(BitShift).addImm(0);
02911   BuildMI(MBB, DL, TII->get(CompareOpcode))
02912     .addReg(RotatedOldVal).addReg(Src2);
02913   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
02914     .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
02915   MBB->addSuccessor(UpdateMBB);
02916   MBB->addSuccessor(UseAltMBB);
02917 
02918   //  UseAltMBB:
02919   //   %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
02920   //   # fall through to UpdateMMB
02921   MBB = UseAltMBB;
02922   if (IsSubWord)
02923     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
02924       .addReg(RotatedOldVal).addReg(Src2)
02925       .addImm(32).addImm(31 + BitSize).addImm(0);
02926   MBB->addSuccessor(UpdateMBB);
02927 
02928   //  UpdateMBB:
02929   //   %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
02930   //                        [ %RotatedAltVal, UseAltMBB ]
02931   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
02932   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
02933   //   JNE LoopMBB
02934   //   # fall through to DoneMMB
02935   MBB = UpdateMBB;
02936   BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
02937     .addReg(RotatedOldVal).addMBB(LoopMBB)
02938     .addReg(RotatedAltVal).addMBB(UseAltMBB);
02939   if (IsSubWord)
02940     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
02941       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
02942   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
02943     .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
02944   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
02945     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
02946   MBB->addSuccessor(LoopMBB);
02947   MBB->addSuccessor(DoneMBB);
02948 
02949   MI->eraseFromParent();
02950   return DoneMBB;
02951 }
02952 
02953 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_CMP_SWAPW
02954 // instruction MI.
02955 MachineBasicBlock *
02956 SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr *MI,
02957                                           MachineBasicBlock *MBB) const {
02958   const SystemZInstrInfo *TII = TM.getInstrInfo();
02959   MachineFunction &MF = *MBB->getParent();
02960   MachineRegisterInfo &MRI = MF.getRegInfo();
02961 
02962   // Extract the operands.  Base can be a register or a frame index.
02963   unsigned Dest        = MI->getOperand(0).getReg();
02964   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
02965   int64_t  Disp        = MI->getOperand(2).getImm();
02966   unsigned OrigCmpVal  = MI->getOperand(3).getReg();
02967   unsigned OrigSwapVal = MI->getOperand(4).getReg();
02968   unsigned BitShift    = MI->getOperand(5).getReg();
02969   unsigned NegBitShift = MI->getOperand(6).getReg();
02970   int64_t  BitSize     = MI->getOperand(7).getImm();
02971   DebugLoc DL          = MI->getDebugLoc();
02972 
02973   const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
02974 
02975   // Get the right opcodes for the displacement.
02976   unsigned LOpcode  = TII->getOpcodeForOffset(SystemZ::L,  Disp);
02977   unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
02978   assert(LOpcode && CSOpcode && "Displacement out of range");
02979 
02980   // Create virtual registers for temporary results.
02981   unsigned OrigOldVal   = MRI.createVirtualRegister(RC);
02982   unsigned OldVal       = MRI.createVirtualRegister(RC);
02983   unsigned CmpVal       = MRI.createVirtualRegister(RC);
02984   unsigned SwapVal      = MRI.createVirtualRegister(RC);
02985   unsigned StoreVal     = MRI.createVirtualRegister(RC);
02986   unsigned RetryOldVal  = MRI.createVirtualRegister(RC);
02987   unsigned RetryCmpVal  = MRI.createVirtualRegister(RC);
02988   unsigned RetrySwapVal = MRI.createVirtualRegister(RC);
02989 
02990   // Insert 2 basic blocks for the loop.
02991   MachineBasicBlock *StartMBB = MBB;
02992   MachineBasicBlock *DoneMBB  = splitBlockBefore(MI, MBB);
02993   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
02994   MachineBasicBlock *SetMBB   = emitBlockAfter(LoopMBB);
02995 
02996   //  StartMBB:
02997   //   ...
02998   //   %OrigOldVal     = L Disp(%Base)
02999   //   # fall through to LoopMMB
03000   MBB = StartMBB;
03001   BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
03002     .addOperand(Base).addImm(Disp).addReg(0);
03003   MBB->addSuccessor(LoopMBB);
03004 
03005   //  LoopMBB:
03006   //   %OldVal        = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
03007   //   %CmpVal        = phi [ %OrigCmpVal, EntryBB ], [ %RetryCmpVal, SetMBB ]
03008   //   %SwapVal       = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
03009   //   %Dest          = RLL %OldVal, BitSize(%BitShift)
03010   //                      ^^ The low BitSize bits contain the field
03011   //                         of interest.
03012   //   %RetryCmpVal   = RISBG32 %CmpVal, %Dest, 32, 63-BitSize, 0
03013   //                      ^^ Replace the upper 32-BitSize bits of the
03014   //                         comparison value with those that we loaded,
03015   //                         so that we can use a full word comparison.
03016   //   CR %Dest, %RetryCmpVal
03017   //   JNE DoneMBB
03018   //   # Fall through to SetMBB
03019   MBB = LoopMBB;
03020   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
03021     .addReg(OrigOldVal).addMBB(StartMBB)
03022     .addReg(RetryOldVal).addMBB(SetMBB);
03023   BuildMI(MBB, DL, TII->get(SystemZ::PHI), CmpVal)
03024     .addReg(OrigCmpVal).addMBB(StartMBB)
03025     .addReg(RetryCmpVal).addMBB(SetMBB);
03026   BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
03027     .addReg(OrigSwapVal).addMBB(StartMBB)
03028     .addReg(RetrySwapVal).addMBB(SetMBB);
03029   BuildMI(MBB, DL, TII->get(SystemZ::RLL), Dest)
03030     .addReg(OldVal).addReg(BitShift).addImm(BitSize);
03031   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetryCmpVal)
03032     .addReg(CmpVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
03033   BuildMI(MBB, DL, TII->get(SystemZ::CR))
03034     .addReg(Dest).addReg(RetryCmpVal);
03035   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
03036     .addImm(SystemZ::CCMASK_ICMP)
03037     .addImm(SystemZ::CCMASK_CMP_NE).addMBB(DoneMBB);
03038   MBB->addSuccessor(DoneMBB);
03039   MBB->addSuccessor(SetMBB);
03040 
03041   //  SetMBB:
03042   //   %RetrySwapVal = RISBG32 %SwapVal, %Dest, 32, 63-BitSize, 0
03043   //                      ^^ Replace the upper 32-BitSize bits of the new
03044   //                         value with those that we loaded.
03045   //   %StoreVal    = RLL %RetrySwapVal, -BitSize(%NegBitShift)
03046   //                      ^^ Rotate the new field to its proper position.
03047   //   %RetryOldVal = CS %Dest, %StoreVal, Disp(%Base)
03048   //   JNE LoopMBB
03049   //   # fall through to ExitMMB
03050   MBB = SetMBB;
03051   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
03052     .addReg(SwapVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
03053   BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
03054     .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
03055   BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
03056     .addReg(OldVal).addReg(StoreVal).addOperand(Base).addImm(Disp);
03057   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
03058     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
03059   MBB->addSuccessor(LoopMBB);
03060   MBB->addSuccessor(DoneMBB);
03061 
03062   MI->eraseFromParent();
03063   return DoneMBB;
03064 }
03065 
03066 // Emit an extension from a GR32 or GR64 to a GR128.  ClearEven is true
03067 // if the high register of the GR128 value must be cleared or false if
03068 // it's "don't care".  SubReg is subreg_l32 when extending a GR32
03069 // and subreg_l64 when extending a GR64.
03070 MachineBasicBlock *
03071 SystemZTargetLowering::emitExt128(MachineInstr *MI,
03072                                   MachineBasicBlock *MBB,
03073                                   bool ClearEven, unsigned SubReg) const {
03074   const SystemZInstrInfo *TII = TM.getInstrInfo();
03075   MachineFunction &MF = *MBB->getParent();
03076   MachineRegisterInfo &MRI = MF.getRegInfo();
03077   DebugLoc DL = MI->getDebugLoc();
03078 
03079   unsigned Dest  = MI->getOperand(0).getReg();
03080   unsigned Src   = MI->getOperand(1).getReg();
03081   unsigned In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
03082 
03083   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128);
03084   if (ClearEven) {
03085     unsigned NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
03086     unsigned Zero64   = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
03087 
03088     BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64)
03089       .addImm(0);
03090     BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128)
03091       .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_h64);
03092     In128 = NewIn128;
03093   }
03094   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
03095     .addReg(In128).addReg(Src).addImm(SubReg);
03096 
03097   MI->eraseFromParent();
03098   return MBB;
03099 }
03100 
03101 MachineBasicBlock *
03102 SystemZTargetLowering::emitMemMemWrapper(MachineInstr *MI,
03103                                          MachineBasicBlock *MBB,
03104                                          unsigned Opcode) const {
03105   const SystemZInstrInfo *TII = TM.getInstrInfo();
03106   MachineFunction &MF = *MBB->getParent();
03107   MachineRegisterInfo &MRI = MF.getRegInfo();
03108   DebugLoc DL = MI->getDebugLoc();
03109 
03110   MachineOperand DestBase = earlyUseOperand(MI->getOperand(0));
03111   uint64_t       DestDisp = MI->getOperand(1).getImm();
03112   MachineOperand SrcBase  = earlyUseOperand(MI->getOperand(2));
03113   uint64_t       SrcDisp  = MI->getOperand(3).getImm();
03114   uint64_t       Length   = MI->getOperand(4).getImm();
03115 
03116   // When generating more than one CLC, all but the last will need to
03117   // branch to the end when a difference is found.
03118   MachineBasicBlock *EndMBB = (Length > 256 && Opcode == SystemZ::CLC ?
03119                                splitBlockAfter(MI, MBB) : 0);
03120 
03121   // Check for the loop form, in which operand 5 is the trip count.
03122   if (MI->getNumExplicitOperands() > 5) {
03123     bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
03124 
03125     uint64_t StartCountReg = MI->getOperand(5).getReg();
03126     uint64_t StartSrcReg   = forceReg(MI, SrcBase, TII);
03127     uint64_t StartDestReg  = (HaveSingleBase ? StartSrcReg :
03128                               forceReg(MI, DestBase, TII));
03129 
03130     const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
03131     uint64_t ThisSrcReg  = MRI.createVirtualRegister(RC);
03132     uint64_t ThisDestReg = (HaveSingleBase ? ThisSrcReg :
03133                             MRI.createVirtualRegister(RC));
03134     uint64_t NextSrcReg  = MRI.createVirtualRegister(RC);
03135     uint64_t NextDestReg = (HaveSingleBase ? NextSrcReg :
03136                             MRI.createVirtualRegister(RC));
03137 
03138     RC = &SystemZ::GR64BitRegClass;
03139     uint64_t ThisCountReg = MRI.createVirtualRegister(RC);
03140     uint64_t NextCountReg = MRI.createVirtualRegister(RC);
03141 
03142     MachineBasicBlock *StartMBB = MBB;
03143     MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
03144     MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
03145     MachineBasicBlock *NextMBB = (EndMBB ? emitBlockAfter(LoopMBB) : LoopMBB);
03146 
03147     //  StartMBB:
03148     //   # fall through to LoopMMB
03149     MBB->addSuccessor(LoopMBB);
03150 
03151     //  LoopMBB:
03152     //   %ThisDestReg = phi [ %StartDestReg, StartMBB ],
03153     //                      [ %NextDestReg, NextMBB ]
03154     //   %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
03155     //                     [ %NextSrcReg, NextMBB ]
03156     //   %ThisCountReg = phi [ %StartCountReg, StartMBB ],
03157     //                       [ %NextCountReg, NextMBB ]
03158     //   ( PFD 2, 768+DestDisp(%ThisDestReg) )
03159     //   Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
03160     //   ( JLH EndMBB )
03161     //
03162     // The prefetch is used only for MVC.  The JLH is used only for CLC.
03163     MBB = LoopMBB;
03164 
03165     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
03166       .addReg(StartDestReg).addMBB(StartMBB)
03167       .addReg(NextDestReg).addMBB(NextMBB);
03168     if (!HaveSingleBase)
03169       BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
03170         .addReg(StartSrcReg).addMBB(StartMBB)
03171         .addReg(NextSrcReg).addMBB(NextMBB);
03172     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
03173       .addReg(StartCountReg).addMBB(StartMBB)
03174       .addReg(NextCountReg).addMBB(NextMBB);
03175     if (Opcode == SystemZ::MVC)
03176       BuildMI(MBB, DL, TII->get(SystemZ::PFD))
03177         .addImm(SystemZ::PFD_WRITE)
03178         .addReg(ThisDestReg).addImm(DestDisp + 768).addReg(0);
03179     BuildMI(MBB, DL, TII->get(Opcode))
03180       .addReg(ThisDestReg).addImm(DestDisp).addImm(256)
03181       .addReg(ThisSrcReg).addImm(SrcDisp);
03182     if (EndMBB) {
03183       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
03184         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
03185         .addMBB(EndMBB);
03186       MBB->addSuccessor(EndMBB);
03187       MBB->addSuccessor(NextMBB);
03188     }
03189 
03190     // NextMBB:
03191     //   %NextDestReg = LA 256(%ThisDestReg)
03192     //   %NextSrcReg = LA 256(%ThisSrcReg)
03193     //   %NextCountReg = AGHI %ThisCountReg, -1
03194     //   CGHI %NextCountReg, 0
03195     //   JLH LoopMBB
03196     //   # fall through to DoneMMB
03197     //
03198     // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
03199     MBB = NextMBB;
03200 
03201     BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
03202       .addReg(ThisDestReg).addImm(256).addReg(0);
03203     if (!HaveSingleBase)
03204       BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
03205         .addReg(ThisSrcReg).addImm(256).addReg(0);
03206     BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
03207       .addReg(ThisCountReg).addImm(-1);
03208     BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
03209       .addReg(NextCountReg).addImm(0);
03210     BuildMI(MBB, DL, TII->get(SystemZ::BRC))
03211       .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
03212       .addMBB(LoopMBB);
03213     MBB->addSuccessor(LoopMBB);
03214     MBB->addSuccessor(DoneMBB);
03215 
03216     DestBase = MachineOperand::CreateReg(NextDestReg, false);
03217     SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
03218     Length &= 255;
03219     MBB = DoneMBB;
03220   }
03221   // Handle any remaining bytes with straight-line code.
03222   while (Length > 0) {
03223     uint64_t ThisLength = std::min(Length, uint64_t(256));
03224     // The previous iteration might have created out-of-range displacements.
03225     // Apply them using LAY if so.
03226     if (!isUInt<12>(DestDisp)) {
03227       unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
03228       BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
03229         .addOperand(DestBase).addImm(DestDisp).addReg(0);
03230       DestBase = MachineOperand::CreateReg(Reg, false);
03231       DestDisp = 0;
03232     }
03233     if (!isUInt<12>(SrcDisp)) {
03234       unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
03235       BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
03236         .addOperand(SrcBase).addImm(SrcDisp).addReg(0);
03237       SrcBase = MachineOperand::CreateReg(Reg, false);
03238       SrcDisp = 0;
03239     }
03240     BuildMI(*MBB, MI, DL, TII->get(Opcode))
03241       .addOperand(DestBase).addImm(DestDisp).addImm(ThisLength)
03242       .addOperand(SrcBase).addImm(SrcDisp);
03243     DestDisp += ThisLength;
03244     SrcDisp += ThisLength;
03245     Length -= ThisLength;
03246     // If there's another CLC to go, branch to the end if a difference
03247     // was found.
03248     if (EndMBB && Length > 0) {
03249       MachineBasicBlock *NextMBB = splitBlockBefore(MI, MBB);
03250       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
03251         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
03252         .addMBB(EndMBB);
03253       MBB->addSuccessor(EndMBB);
03254       MBB->addSuccessor(NextMBB);
03255       MBB = NextMBB;
03256     }
03257   }
03258   if (EndMBB) {
03259     MBB->addSuccessor(EndMBB);
03260     MBB = EndMBB;
03261     MBB->addLiveIn(SystemZ::CC);
03262   }
03263 
03264   MI->eraseFromParent();
03265   return MBB;
03266 }
03267 
03268 // Decompose string pseudo-instruction MI into a loop that continually performs
03269 // Opcode until CC != 3.
03270 MachineBasicBlock *
03271 SystemZTargetLowering::emitStringWrapper(MachineInstr *MI,
03272                                          MachineBasicBlock *MBB,
03273                                          unsigned Opcode) const {
03274   const SystemZInstrInfo *TII = TM.getInstrInfo();
03275   MachineFunction &MF = *MBB->getParent();
03276   MachineRegisterInfo &MRI = MF.getRegInfo();
03277   DebugLoc DL = MI->getDebugLoc();
03278 
03279   uint64_t End1Reg   = MI->getOperand(0).getReg();
03280   uint64_t Start1Reg = MI->getOperand(1).getReg();
03281   uint64_t Start2Reg = MI->getOperand(2).getReg();
03282   uint64_t CharReg   = MI->getOperand(3).getReg();
03283 
03284   const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
03285   uint64_t This1Reg = MRI.createVirtualRegister(RC);
03286   uint64_t This2Reg = MRI.createVirtualRegister(RC);
03287   uint64_t End2Reg  = MRI.createVirtualRegister(RC);
03288 
03289   MachineBasicBlock *StartMBB = MBB;
03290   MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
03291   MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
03292 
03293   //  StartMBB:
03294   //   # fall through to LoopMMB
03295   MBB->addSuccessor(LoopMBB);
03296 
03297   //  LoopMBB:
03298   //   %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
03299   //   %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
03300   //   R0L = %CharReg
03301   //   %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0L
03302   //   JO LoopMBB
03303   //   # fall through to DoneMMB
03304   //
03305   // The load of R0L can be hoisted by post-RA LICM.
03306   MBB = LoopMBB;
03307 
03308   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
03309     .addReg(Start1Reg).addMBB(StartMBB)
03310     .addReg(End1Reg).addMBB(LoopMBB);
03311   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
03312     .addReg(Start2Reg).addMBB(StartMBB)
03313     .addReg(End2Reg).addMBB(LoopMBB);
03314   BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0L).addReg(CharReg);
03315   BuildMI(MBB, DL, TII->get(Opcode))
03316     .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
03317     .addReg(This1Reg).addReg(This2Reg);
03318   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
03319     .addImm(SystemZ::CCMASK_ANY).addImm(SystemZ::CCMASK_3).addMBB(LoopMBB);
03320   MBB->addSuccessor(LoopMBB);
03321   MBB->addSuccessor(DoneMBB);
03322 
03323   DoneMBB->addLiveIn(SystemZ::CC);
03324 
03325   MI->eraseFromParent();
03326   return DoneMBB;
03327 }
03328 
03329 MachineBasicBlock *SystemZTargetLowering::
03330 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const {
03331   switch (MI->getOpcode()) {
03332   case SystemZ::Select32Mux:
03333   case SystemZ::Select32:
03334   case SystemZ::SelectF32:
03335   case SystemZ::Select64:
03336   case SystemZ::SelectF64:
03337   case SystemZ::SelectF128:
03338     return emitSelect(MI, MBB);
03339 
03340   case SystemZ::CondStore8Mux:
03341     return emitCondStore(MI, MBB, SystemZ::STCMux, 0, false);
03342   case SystemZ::CondStore8MuxInv:
03343     return emitCondStore(MI, MBB, SystemZ::STCMux, 0, true);
03344   case SystemZ::CondStore16Mux:
03345     return emitCondStore(MI, MBB, SystemZ::STHMux, 0, false);
03346   case SystemZ::CondStore16MuxInv:
03347     return emitCondStore(MI, MBB, SystemZ::STHMux, 0, true);
03348   case SystemZ::CondStore8:
03349     return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
03350   case SystemZ::CondStore8Inv:
03351     return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
03352   case SystemZ::CondStore16:
03353     return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
03354   case SystemZ::CondStore16Inv:
03355     return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
03356   case SystemZ::CondStore32:
03357     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
03358   case SystemZ::CondStore32Inv:
03359     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
03360   case SystemZ::CondStore64:
03361     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
03362   case SystemZ::CondStore64Inv:
03363     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
03364   case SystemZ::CondStoreF32:
03365     return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
03366   case SystemZ::CondStoreF32Inv:
03367     return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
03368   case SystemZ::CondStoreF64:
03369     return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
03370   case SystemZ::CondStoreF64Inv:
03371     return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
03372 
03373   case SystemZ::AEXT128_64:
03374     return emitExt128(MI, MBB, false, SystemZ::subreg_l64);
03375   case SystemZ::ZEXT128_32:
03376     return emitExt128(MI, MBB, true, SystemZ::subreg_l32);
03377   case SystemZ::ZEXT128_64:
03378     return emitExt128(MI, MBB, true, SystemZ::subreg_l64);
03379 
03380   case SystemZ::ATOMIC_SWAPW:
03381     return emitAtomicLoadBinary(MI, MBB, 0, 0);
03382   case SystemZ::ATOMIC_SWAP_32:
03383     return emitAtomicLoadBinary(MI, MBB, 0, 32);
03384   case SystemZ::ATOMIC_SWAP_64:
03385     return emitAtomicLoadBinary(MI, MBB, 0, 64);
03386 
03387   case SystemZ::ATOMIC_LOADW_AR:
03388     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 0);
03389   case SystemZ::ATOMIC_LOADW_AFI:
03390     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 0);
03391   case SystemZ::ATOMIC_LOAD_AR:
03392     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 32);
03393   case SystemZ::ATOMIC_LOAD_AHI:
03394     return emitAtomicLoadBinary(MI, MBB, SystemZ::AHI, 32);
03395   case SystemZ::ATOMIC_LOAD_AFI:
03396     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 32);
03397   case SystemZ::ATOMIC_LOAD_AGR:
03398     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGR, 64);
03399   case SystemZ::ATOMIC_LOAD_AGHI:
03400     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGHI, 64);
03401   case SystemZ::ATOMIC_LOAD_AGFI:
03402     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGFI, 64);
03403 
03404   case SystemZ::ATOMIC_LOADW_SR:
03405     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 0);
03406   case SystemZ::ATOMIC_LOAD_SR:
03407     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 32);
03408   case SystemZ::ATOMIC_LOAD_SGR:
03409     return emitAtomicLoadBinary(MI, MBB, SystemZ::SGR, 64);
03410 
03411   case SystemZ::ATOMIC_LOADW_NR:
03412     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0);
03413   case SystemZ::ATOMIC_LOADW_NILH:
03414     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0);
03415   case SystemZ::ATOMIC_LOAD_NR:
03416     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32);
03417   case SystemZ::ATOMIC_LOAD_NILL:
03418     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32);
03419   case SystemZ::ATOMIC_LOAD_NILH:
03420     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32);
03421   case SystemZ::ATOMIC_LOAD_NILF:
03422     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32);
03423   case SystemZ::ATOMIC_LOAD_NGR:
03424     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64);
03425   case SystemZ::ATOMIC_LOAD_NILL64:
03426     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64);
03427   case SystemZ::ATOMIC_LOAD_NILH64:
03428     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64);
03429   case SystemZ::ATOMIC_LOAD_NIHL64:
03430     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64);
03431   case SystemZ::ATOMIC_LOAD_NIHH64:
03432     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64);
03433   case SystemZ::ATOMIC_LOAD_NILF64:
03434     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64);
03435   case SystemZ::ATOMIC_LOAD_NIHF64:
03436     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64);
03437 
03438   case SystemZ::ATOMIC_LOADW_OR:
03439     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 0);
03440   case SystemZ::ATOMIC_LOADW_OILH:
03441     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 0);
03442   case SystemZ::ATOMIC_LOAD_OR:
03443     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 32);
03444   case SystemZ::ATOMIC_LOAD_OILL:
03445     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL, 32);
03446   case SystemZ::ATOMIC_LOAD_OILH:
03447     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 32);
03448   case SystemZ::ATOMIC_LOAD_OILF:
03449     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF, 32);
03450   case SystemZ::ATOMIC_LOAD_OGR:
03451     return emitAtomicLoadBinary(MI, MBB, SystemZ::OGR, 64);
03452   case SystemZ::ATOMIC_LOAD_OILL64:
03453     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL64, 64);
03454   case SystemZ::ATOMIC_LOAD_OILH64:
03455     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH64, 64);
03456   case SystemZ::ATOMIC_LOAD_OIHL64:
03457     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHL64, 64);
03458   case SystemZ::ATOMIC_LOAD_OIHH64:
03459     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHH64, 64);
03460   case SystemZ::ATOMIC_LOAD_OILF64:
03461     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF64, 64);
03462   case SystemZ::ATOMIC_LOAD_OIHF64:
03463     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHF64, 64);
03464 
03465   case SystemZ::ATOMIC_LOADW_XR:
03466     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 0);
03467   case SystemZ::ATOMIC_LOADW_XILF:
03468     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 0);
03469   case SystemZ::ATOMIC_LOAD_XR:
03470     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 32);
03471   case SystemZ::ATOMIC_LOAD_XILF:
03472     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 32);
03473   case SystemZ::ATOMIC_LOAD_XGR:
03474     return emitAtomicLoadBinary(MI, MBB, SystemZ::XGR, 64);
03475   case SystemZ::ATOMIC_LOAD_XILF64:
03476     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF64, 64);
03477   case SystemZ::ATOMIC_LOAD_XIHF64:
03478     return emitAtomicLoadBinary(MI, MBB, SystemZ::XIHF64, 64);
03479 
03480   case SystemZ::ATOMIC_LOADW_NRi:
03481     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0, true);
03482   case SystemZ::ATOMIC_LOADW_NILHi:
03483     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 0, true);
03484   case SystemZ::ATOMIC_LOAD_NRi:
03485     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32, true);
03486   case SystemZ::ATOMIC_LOAD_NILLi:
03487     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 32, true);
03488   case SystemZ::ATOMIC_LOAD_NILHi:
03489     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 32, true);
03490   case SystemZ::ATOMIC_LOAD_NILFi:
03491     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 32, true);
03492   case SystemZ::ATOMIC_LOAD_NGRi:
03493     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64, true);
03494   case SystemZ::ATOMIC_LOAD_NILL64i:
03495     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL64, 64, true);
03496   case SystemZ::ATOMIC_LOAD_NILH64i:
03497     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH64, 64, true);
03498   case SystemZ::ATOMIC_LOAD_NIHL64i:
03499     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL64, 64, true);
03500   case SystemZ::ATOMIC_LOAD_NIHH64i:
03501     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH64, 64, true);
03502   case SystemZ::ATOMIC_LOAD_NILF64i:
03503     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF64, 64, true);
03504   case SystemZ::ATOMIC_LOAD_NIHF64i:
03505     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF64, 64, true);
03506 
03507   case SystemZ::ATOMIC_LOADW_MIN:
03508     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
03509                                 SystemZ::CCMASK_CMP_LE, 0);
03510   case SystemZ::ATOMIC_LOAD_MIN_32:
03511     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
03512                                 SystemZ::CCMASK_CMP_LE, 32);
03513   case SystemZ::ATOMIC_LOAD_MIN_64:
03514     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
03515                                 SystemZ::CCMASK_CMP_LE, 64);
03516 
03517   case SystemZ::ATOMIC_LOADW_MAX:
03518     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
03519                                 SystemZ::CCMASK_CMP_GE, 0);
03520   case SystemZ::ATOMIC_LOAD_MAX_32:
03521     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
03522                                 SystemZ::CCMASK_CMP_GE, 32);
03523   case SystemZ::ATOMIC_LOAD_MAX_64:
03524     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
03525                                 SystemZ::CCMASK_CMP_GE, 64);
03526 
03527   case SystemZ::ATOMIC_LOADW_UMIN:
03528     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
03529                                 SystemZ::CCMASK_CMP_LE, 0);
03530   case SystemZ::ATOMIC_LOAD_UMIN_32:
03531     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
03532                                 SystemZ::CCMASK_CMP_LE, 32);
03533   case SystemZ::ATOMIC_LOAD_UMIN_64:
03534     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
03535                                 SystemZ::CCMASK_CMP_LE, 64);
03536 
03537   case SystemZ::ATOMIC_LOADW_UMAX:
03538     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
03539                                 SystemZ::CCMASK_CMP_GE, 0);
03540   case SystemZ::ATOMIC_LOAD_UMAX_32:
03541     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
03542                                 SystemZ::CCMASK_CMP_GE, 32);
03543   case SystemZ::ATOMIC_LOAD_UMAX_64:
03544     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
03545                                 SystemZ::CCMASK_CMP_GE, 64);
03546 
03547   case SystemZ::ATOMIC_CMP_SWAPW:
03548     return emitAtomicCmpSwapW(MI, MBB);
03549   case SystemZ::MVCSequence:
03550   case SystemZ::MVCLoop:
03551     return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
03552   case SystemZ::NCSequence:
03553   case SystemZ::NCLoop:
03554     return emitMemMemWrapper(MI, MBB, SystemZ::NC);
03555   case SystemZ::OCSequence:
03556   case SystemZ::OCLoop:
03557     return emitMemMemWrapper(MI, MBB, SystemZ::OC);
03558   case SystemZ::XCSequence:
03559   case SystemZ::XCLoop:
03560     return emitMemMemWrapper(MI, MBB, SystemZ::XC);
03561   case SystemZ::CLCSequence:
03562   case SystemZ::CLCLoop:
03563     return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
03564   case SystemZ::CLSTLoop:
03565     return emitStringWrapper(MI, MBB, SystemZ::CLST);
03566   case SystemZ::MVSTLoop:
03567     return emitStringWrapper(MI, MBB, SystemZ::MVST);
03568   case SystemZ::SRSTLoop:
03569     return emitStringWrapper(MI, MBB, SystemZ::SRST);
03570   default:
03571     llvm_unreachable("Unexpected instr type to insert");
03572   }
03573 }