[SystemZ] Try to fold shifts into TMxx
[oota-llvm.git] / lib / Target / SystemZ / SystemZISelLowering.cpp
1 //===-- SystemZISelLowering.cpp - SystemZ DAG lowering implementation -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the SystemZTargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "systemz-lower"
15
16 #include "SystemZISelLowering.h"
17 #include "SystemZCallingConv.h"
18 #include "SystemZConstantPoolValue.h"
19 #include "SystemZMachineFunctionInfo.h"
20 #include "SystemZTargetMachine.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
25
26 using namespace llvm;
27
28 // Classify VT as either 32 or 64 bit.
29 static bool is32Bit(EVT VT) {
30   switch (VT.getSimpleVT().SimpleTy) {
31   case MVT::i32:
32     return true;
33   case MVT::i64:
34     return false;
35   default:
36     llvm_unreachable("Unsupported type");
37   }
38 }
39
40 // Return a version of MachineOperand that can be safely used before the
41 // final use.
42 static MachineOperand earlyUseOperand(MachineOperand Op) {
43   if (Op.isReg())
44     Op.setIsKill(false);
45   return Op;
46 }
47
48 SystemZTargetLowering::SystemZTargetLowering(SystemZTargetMachine &tm)
49   : TargetLowering(tm, new TargetLoweringObjectFileELF()),
50     Subtarget(*tm.getSubtargetImpl()), TM(tm) {
51   MVT PtrVT = getPointerTy();
52
53   // Set up the register classes.
54   addRegisterClass(MVT::i32,  &SystemZ::GR32BitRegClass);
55   addRegisterClass(MVT::i64,  &SystemZ::GR64BitRegClass);
56   addRegisterClass(MVT::f32,  &SystemZ::FP32BitRegClass);
57   addRegisterClass(MVT::f64,  &SystemZ::FP64BitRegClass);
58   addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
59
60   // Compute derived properties from the register classes
61   computeRegisterProperties();
62
63   // Set up special registers.
64   setExceptionPointerRegister(SystemZ::R6D);
65   setExceptionSelectorRegister(SystemZ::R7D);
66   setStackPointerRegisterToSaveRestore(SystemZ::R15D);
67
68   // TODO: It may be better to default to latency-oriented scheduling, however
69   // LLVM's current latency-oriented scheduler can't handle physreg definitions
70   // such as SystemZ has with CC, so set this to the register-pressure
71   // scheduler, because it can.
72   setSchedulingPreference(Sched::RegPressure);
73
74   setBooleanContents(ZeroOrOneBooleanContent);
75   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
76
77   // Instructions are strings of 2-byte aligned 2-byte values.
78   setMinFunctionAlignment(2);
79
80   // Handle operations that are handled in a similar way for all types.
81   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
82        I <= MVT::LAST_FP_VALUETYPE;
83        ++I) {
84     MVT VT = MVT::SimpleValueType(I);
85     if (isTypeLegal(VT)) {
86       // Expand SETCC(X, Y, COND) into SELECT_CC(X, Y, 1, 0, COND).
87       setOperationAction(ISD::SETCC, VT, Expand);
88
89       // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
90       setOperationAction(ISD::SELECT, VT, Expand);
91
92       // Lower SELECT_CC and BR_CC into separate comparisons and branches.
93       setOperationAction(ISD::SELECT_CC, VT, Custom);
94       setOperationAction(ISD::BR_CC,     VT, Custom);
95     }
96   }
97
98   // Expand jump table branches as address arithmetic followed by an
99   // indirect jump.
100   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
101
102   // Expand BRCOND into a BR_CC (see above).
103   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
104
105   // Handle integer types.
106   for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
107        I <= MVT::LAST_INTEGER_VALUETYPE;
108        ++I) {
109     MVT VT = MVT::SimpleValueType(I);
110     if (isTypeLegal(VT)) {
111       // Expand individual DIV and REMs into DIVREMs.
112       setOperationAction(ISD::SDIV, VT, Expand);
113       setOperationAction(ISD::UDIV, VT, Expand);
114       setOperationAction(ISD::SREM, VT, Expand);
115       setOperationAction(ISD::UREM, VT, Expand);
116       setOperationAction(ISD::SDIVREM, VT, Custom);
117       setOperationAction(ISD::UDIVREM, VT, Custom);
118
119       // Expand ATOMIC_LOAD and ATOMIC_STORE using ATOMIC_CMP_SWAP.
120       // FIXME: probably much too conservative.
121       setOperationAction(ISD::ATOMIC_LOAD,  VT, Expand);
122       setOperationAction(ISD::ATOMIC_STORE, VT, Expand);
123
124       // No special instructions for these.
125       setOperationAction(ISD::CTPOP,           VT, Expand);
126       setOperationAction(ISD::CTTZ,            VT, Expand);
127       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
128       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
129       setOperationAction(ISD::ROTR,            VT, Expand);
130
131       // Use *MUL_LOHI where possible instead of MULH*.
132       setOperationAction(ISD::MULHS, VT, Expand);
133       setOperationAction(ISD::MULHU, VT, Expand);
134       setOperationAction(ISD::SMUL_LOHI, VT, Custom);
135       setOperationAction(ISD::UMUL_LOHI, VT, Custom);
136
137       // We have instructions for signed but not unsigned FP conversion.
138       setOperationAction(ISD::FP_TO_UINT, VT, Expand);
139     }
140   }
141
142   // Type legalization will convert 8- and 16-bit atomic operations into
143   // forms that operate on i32s (but still keeping the original memory VT).
144   // Lower them into full i32 operations.
145   setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Custom);
146   setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Custom);
147   setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Custom);
148   setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Custom);
149   setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Custom);
150   setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Custom);
151   setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Custom);
152   setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i32, Custom);
153   setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i32, Custom);
154   setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Custom);
155   setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Custom);
156   setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Custom);
157
158   // We have instructions for signed but not unsigned FP conversion.
159   // Handle unsigned 32-bit types as signed 64-bit types.
160   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote);
161   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
162
163   // We have native support for a 64-bit CTLZ, via FLOGR.
164   setOperationAction(ISD::CTLZ, MVT::i32, Promote);
165   setOperationAction(ISD::CTLZ, MVT::i64, Legal);
166
167   // Give LowerOperation the chance to replace 64-bit ORs with subregs.
168   setOperationAction(ISD::OR, MVT::i64, Custom);
169
170   // FIXME: Can we support these natively?
171   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
172   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
173   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
174
175   // We have native instructions for i8, i16 and i32 extensions, but not i1.
176   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
177   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
178   setLoadExtAction(ISD::EXTLOAD,  MVT::i1, Promote);
179   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
180
181   // Handle the various types of symbolic address.
182   setOperationAction(ISD::ConstantPool,     PtrVT, Custom);
183   setOperationAction(ISD::GlobalAddress,    PtrVT, Custom);
184   setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom);
185   setOperationAction(ISD::BlockAddress,     PtrVT, Custom);
186   setOperationAction(ISD::JumpTable,        PtrVT, Custom);
187
188   // We need to handle dynamic allocations specially because of the
189   // 160-byte area at the bottom of the stack.
190   setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
191
192   // Use custom expanders so that we can force the function to use
193   // a frame pointer.
194   setOperationAction(ISD::STACKSAVE,    MVT::Other, Custom);
195   setOperationAction(ISD::STACKRESTORE, MVT::Other, Custom);
196
197   // Handle prefetches with PFD or PFDRL.
198   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
199
200   // Handle floating-point types.
201   for (unsigned I = MVT::FIRST_FP_VALUETYPE;
202        I <= MVT::LAST_FP_VALUETYPE;
203        ++I) {
204     MVT VT = MVT::SimpleValueType(I);
205     if (isTypeLegal(VT)) {
206       // We can use FI for FRINT.
207       setOperationAction(ISD::FRINT, VT, Legal);
208
209       // We can use the extended form of FI for other rounding operations.
210       if (Subtarget.hasFPExtension()) {
211         setOperationAction(ISD::FNEARBYINT, VT, Legal);
212         setOperationAction(ISD::FFLOOR, VT, Legal);
213         setOperationAction(ISD::FCEIL, VT, Legal);
214         setOperationAction(ISD::FTRUNC, VT, Legal);
215         setOperationAction(ISD::FROUND, VT, Legal);
216       }
217
218       // No special instructions for these.
219       setOperationAction(ISD::FSIN, VT, Expand);
220       setOperationAction(ISD::FCOS, VT, Expand);
221       setOperationAction(ISD::FREM, VT, Expand);
222     }
223   }
224
225   // We have fused multiply-addition for f32 and f64 but not f128.
226   setOperationAction(ISD::FMA, MVT::f32,  Legal);
227   setOperationAction(ISD::FMA, MVT::f64,  Legal);
228   setOperationAction(ISD::FMA, MVT::f128, Expand);
229
230   // Needed so that we don't try to implement f128 constant loads using
231   // a load-and-extend of a f80 constant (in cases where the constant
232   // would fit in an f80).
233   setLoadExtAction(ISD::EXTLOAD, MVT::f80, Expand);
234
235   // Floating-point truncation and stores need to be done separately.
236   setTruncStoreAction(MVT::f64,  MVT::f32, Expand);
237   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
238   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
239
240   // We have 64-bit FPR<->GPR moves, but need special handling for
241   // 32-bit forms.
242   setOperationAction(ISD::BITCAST, MVT::i32, Custom);
243   setOperationAction(ISD::BITCAST, MVT::f32, Custom);
244
245   // VASTART and VACOPY need to deal with the SystemZ-specific varargs
246   // structure, but VAEND is a no-op.
247   setOperationAction(ISD::VASTART, MVT::Other, Custom);
248   setOperationAction(ISD::VACOPY,  MVT::Other, Custom);
249   setOperationAction(ISD::VAEND,   MVT::Other, Expand);
250
251   // We want to use MVC in preference to even a single load/store pair.
252   MaxStoresPerMemcpy = 0;
253   MaxStoresPerMemcpyOptSize = 0;
254
255   // The main memset sequence is a byte store followed by an MVC.
256   // Two STC or MV..I stores win over that, but the kind of fused stores
257   // generated by target-independent code don't when the byte value is
258   // variable.  E.g.  "STC <reg>;MHI <reg>,257;STH <reg>" is not better
259   // than "STC;MVC".  Handle the choice in target-specific code instead.
260   MaxStoresPerMemset = 0;
261   MaxStoresPerMemsetOptSize = 0;
262 }
263
264 bool
265 SystemZTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
266   VT = VT.getScalarType();
267
268   if (!VT.isSimple())
269     return false;
270
271   switch (VT.getSimpleVT().SimpleTy) {
272   case MVT::f32:
273   case MVT::f64:
274     return true;
275   case MVT::f128:
276     return false;
277   default:
278     break;
279   }
280
281   return false;
282 }
283
284 bool SystemZTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
285   // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
286   return Imm.isZero() || Imm.isNegZero();
287 }
288
289 bool SystemZTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
290                                                           bool *Fast) const {
291   // Unaligned accesses should never be slower than the expanded version.
292   // We check specifically for aligned accesses in the few cases where
293   // they are required.
294   if (Fast)
295     *Fast = true;
296   return true;
297 }
298   
299 bool SystemZTargetLowering::isLegalAddressingMode(const AddrMode &AM,
300                                                   Type *Ty) const {
301   // Punt on globals for now, although they can be used in limited
302   // RELATIVE LONG cases.
303   if (AM.BaseGV)
304     return false;
305
306   // Require a 20-bit signed offset.
307   if (!isInt<20>(AM.BaseOffs))
308     return false;
309
310   // Indexing is OK but no scale factor can be applied.
311   return AM.Scale == 0 || AM.Scale == 1;
312 }
313
314 bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
315   if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
316     return false;
317   unsigned FromBits = FromType->getPrimitiveSizeInBits();
318   unsigned ToBits = ToType->getPrimitiveSizeInBits();
319   return FromBits > ToBits;
320 }
321
322 bool SystemZTargetLowering::isTruncateFree(EVT FromVT, EVT ToVT) const {
323   if (!FromVT.isInteger() || !ToVT.isInteger())
324     return false;
325   unsigned FromBits = FromVT.getSizeInBits();
326   unsigned ToBits = ToVT.getSizeInBits();
327   return FromBits > ToBits;
328 }
329
330 //===----------------------------------------------------------------------===//
331 // Inline asm support
332 //===----------------------------------------------------------------------===//
333
334 TargetLowering::ConstraintType
335 SystemZTargetLowering::getConstraintType(const std::string &Constraint) const {
336   if (Constraint.size() == 1) {
337     switch (Constraint[0]) {
338     case 'a': // Address register
339     case 'd': // Data register (equivalent to 'r')
340     case 'f': // Floating-point register
341     case 'r': // General-purpose register
342       return C_RegisterClass;
343
344     case 'Q': // Memory with base and unsigned 12-bit displacement
345     case 'R': // Likewise, plus an index
346     case 'S': // Memory with base and signed 20-bit displacement
347     case 'T': // Likewise, plus an index
348     case 'm': // Equivalent to 'T'.
349       return C_Memory;
350
351     case 'I': // Unsigned 8-bit constant
352     case 'J': // Unsigned 12-bit constant
353     case 'K': // Signed 16-bit constant
354     case 'L': // Signed 20-bit displacement (on all targets we support)
355     case 'M': // 0x7fffffff
356       return C_Other;
357
358     default:
359       break;
360     }
361   }
362   return TargetLowering::getConstraintType(Constraint);
363 }
364
365 TargetLowering::ConstraintWeight SystemZTargetLowering::
366 getSingleConstraintMatchWeight(AsmOperandInfo &info,
367                                const char *constraint) const {
368   ConstraintWeight weight = CW_Invalid;
369   Value *CallOperandVal = info.CallOperandVal;
370   // If we don't have a value, we can't do a match,
371   // but allow it at the lowest weight.
372   if (CallOperandVal == NULL)
373     return CW_Default;
374   Type *type = CallOperandVal->getType();
375   // Look at the constraint type.
376   switch (*constraint) {
377   default:
378     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
379     break;
380
381   case 'a': // Address register
382   case 'd': // Data register (equivalent to 'r')
383   case 'r': // General-purpose register
384     if (CallOperandVal->getType()->isIntegerTy())
385       weight = CW_Register;
386     break;
387
388   case 'f': // Floating-point register
389     if (type->isFloatingPointTy())
390       weight = CW_Register;
391     break;
392
393   case 'I': // Unsigned 8-bit constant
394     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal))
395       if (isUInt<8>(C->getZExtValue()))
396         weight = CW_Constant;
397     break;
398
399   case 'J': // Unsigned 12-bit constant
400     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal))
401       if (isUInt<12>(C->getZExtValue()))
402         weight = CW_Constant;
403     break;
404
405   case 'K': // Signed 16-bit constant
406     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal))
407       if (isInt<16>(C->getSExtValue()))
408         weight = CW_Constant;
409     break;
410
411   case 'L': // Signed 20-bit displacement (on all targets we support)
412     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal))
413       if (isInt<20>(C->getSExtValue()))
414         weight = CW_Constant;
415     break;
416
417   case 'M': // 0x7fffffff
418     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal))
419       if (C->getZExtValue() == 0x7fffffff)
420         weight = CW_Constant;
421     break;
422   }
423   return weight;
424 }
425
426 // Parse a "{tNNN}" register constraint for which the register type "t"
427 // has already been verified.  MC is the class associated with "t" and
428 // Map maps 0-based register numbers to LLVM register numbers.
429 static std::pair<unsigned, const TargetRegisterClass *>
430 parseRegisterNumber(const std::string &Constraint,
431                     const TargetRegisterClass *RC, const unsigned *Map) {
432   assert(*(Constraint.end()-1) == '}' && "Missing '}'");
433   if (isdigit(Constraint[2])) {
434     std::string Suffix(Constraint.data() + 2, Constraint.size() - 2);
435     unsigned Index = atoi(Suffix.c_str());
436     if (Index < 16 && Map[Index])
437       return std::make_pair(Map[Index], RC);
438   }
439   return std::make_pair(0u, static_cast<TargetRegisterClass*>(0));
440 }
441
442 std::pair<unsigned, const TargetRegisterClass *> SystemZTargetLowering::
443 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const {
444   if (Constraint.size() == 1) {
445     // GCC Constraint Letters
446     switch (Constraint[0]) {
447     default: break;
448     case 'd': // Data register (equivalent to 'r')
449     case 'r': // General-purpose register
450       if (VT == MVT::i64)
451         return std::make_pair(0U, &SystemZ::GR64BitRegClass);
452       else if (VT == MVT::i128)
453         return std::make_pair(0U, &SystemZ::GR128BitRegClass);
454       return std::make_pair(0U, &SystemZ::GR32BitRegClass);
455
456     case 'a': // Address register
457       if (VT == MVT::i64)
458         return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
459       else if (VT == MVT::i128)
460         return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
461       return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
462
463     case 'f': // Floating-point register
464       if (VT == MVT::f64)
465         return std::make_pair(0U, &SystemZ::FP64BitRegClass);
466       else if (VT == MVT::f128)
467         return std::make_pair(0U, &SystemZ::FP128BitRegClass);
468       return std::make_pair(0U, &SystemZ::FP32BitRegClass);
469     }
470   }
471   if (Constraint[0] == '{') {
472     // We need to override the default register parsing for GPRs and FPRs
473     // because the interpretation depends on VT.  The internal names of
474     // the registers are also different from the external names
475     // (F0D and F0S instead of F0, etc.).
476     if (Constraint[1] == 'r') {
477       if (VT == MVT::i32)
478         return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
479                                    SystemZMC::GR32Regs);
480       if (VT == MVT::i128)
481         return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
482                                    SystemZMC::GR128Regs);
483       return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
484                                  SystemZMC::GR64Regs);
485     }
486     if (Constraint[1] == 'f') {
487       if (VT == MVT::f32)
488         return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
489                                    SystemZMC::FP32Regs);
490       if (VT == MVT::f128)
491         return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
492                                    SystemZMC::FP128Regs);
493       return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
494                                  SystemZMC::FP64Regs);
495     }
496   }
497   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
498 }
499
500 void SystemZTargetLowering::
501 LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
502                              std::vector<SDValue> &Ops,
503                              SelectionDAG &DAG) const {
504   // Only support length 1 constraints for now.
505   if (Constraint.length() == 1) {
506     switch (Constraint[0]) {
507     case 'I': // Unsigned 8-bit constant
508       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
509         if (isUInt<8>(C->getZExtValue()))
510           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(),
511                                               Op.getValueType()));
512       return;
513
514     case 'J': // Unsigned 12-bit constant
515       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
516         if (isUInt<12>(C->getZExtValue()))
517           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(),
518                                               Op.getValueType()));
519       return;
520
521     case 'K': // Signed 16-bit constant
522       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
523         if (isInt<16>(C->getSExtValue()))
524           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(),
525                                               Op.getValueType()));
526       return;
527
528     case 'L': // Signed 20-bit displacement (on all targets we support)
529       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
530         if (isInt<20>(C->getSExtValue()))
531           Ops.push_back(DAG.getTargetConstant(C->getSExtValue(),
532                                               Op.getValueType()));
533       return;
534
535     case 'M': // 0x7fffffff
536       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
537         if (C->getZExtValue() == 0x7fffffff)
538           Ops.push_back(DAG.getTargetConstant(C->getZExtValue(),
539                                               Op.getValueType()));
540       return;
541     }
542   }
543   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
544 }
545
546 //===----------------------------------------------------------------------===//
547 // Calling conventions
548 //===----------------------------------------------------------------------===//
549
550 #include "SystemZGenCallingConv.inc"
551
552 bool SystemZTargetLowering::allowTruncateForTailCall(Type *FromType,
553                                                      Type *ToType) const {
554   return isTruncateFree(FromType, ToType);
555 }
556
557 bool SystemZTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
558   if (!CI->isTailCall())
559     return false;
560   return true;
561 }
562
563 // Value is a value that has been passed to us in the location described by VA
564 // (and so has type VA.getLocVT()).  Convert Value to VA.getValVT(), chaining
565 // any loads onto Chain.
566 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDLoc DL,
567                                    CCValAssign &VA, SDValue Chain,
568                                    SDValue Value) {
569   // If the argument has been promoted from a smaller type, insert an
570   // assertion to capture this.
571   if (VA.getLocInfo() == CCValAssign::SExt)
572     Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value,
573                         DAG.getValueType(VA.getValVT()));
574   else if (VA.getLocInfo() == CCValAssign::ZExt)
575     Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value,
576                         DAG.getValueType(VA.getValVT()));
577
578   if (VA.isExtInLoc())
579     Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
580   else if (VA.getLocInfo() == CCValAssign::Indirect)
581     Value = DAG.getLoad(VA.getValVT(), DL, Chain, Value,
582                         MachinePointerInfo(), false, false, false, 0);
583   else
584     assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo");
585   return Value;
586 }
587
588 // Value is a value of type VA.getValVT() that we need to copy into
589 // the location described by VA.  Return a copy of Value converted to
590 // VA.getValVT().  The caller is responsible for handling indirect values.
591 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDLoc DL,
592                                    CCValAssign &VA, SDValue Value) {
593   switch (VA.getLocInfo()) {
594   case CCValAssign::SExt:
595     return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
596   case CCValAssign::ZExt:
597     return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
598   case CCValAssign::AExt:
599     return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
600   case CCValAssign::Full:
601     return Value;
602   default:
603     llvm_unreachable("Unhandled getLocInfo()");
604   }
605 }
606
607 SDValue SystemZTargetLowering::
608 LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
609                      const SmallVectorImpl<ISD::InputArg> &Ins,
610                      SDLoc DL, SelectionDAG &DAG,
611                      SmallVectorImpl<SDValue> &InVals) const {
612   MachineFunction &MF = DAG.getMachineFunction();
613   MachineFrameInfo *MFI = MF.getFrameInfo();
614   MachineRegisterInfo &MRI = MF.getRegInfo();
615   SystemZMachineFunctionInfo *FuncInfo =
616     MF.getInfo<SystemZMachineFunctionInfo>();
617   const SystemZFrameLowering *TFL =
618     static_cast<const SystemZFrameLowering *>(TM.getFrameLowering());
619
620   // Assign locations to all of the incoming arguments.
621   SmallVector<CCValAssign, 16> ArgLocs;
622   CCState CCInfo(CallConv, IsVarArg, MF, TM, ArgLocs, *DAG.getContext());
623   CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
624
625   unsigned NumFixedGPRs = 0;
626   unsigned NumFixedFPRs = 0;
627   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
628     SDValue ArgValue;
629     CCValAssign &VA = ArgLocs[I];
630     EVT LocVT = VA.getLocVT();
631     if (VA.isRegLoc()) {
632       // Arguments passed in registers
633       const TargetRegisterClass *RC;
634       switch (LocVT.getSimpleVT().SimpleTy) {
635       default:
636         // Integers smaller than i64 should be promoted to i64.
637         llvm_unreachable("Unexpected argument type");
638       case MVT::i32:
639         NumFixedGPRs += 1;
640         RC = &SystemZ::GR32BitRegClass;
641         break;
642       case MVT::i64:
643         NumFixedGPRs += 1;
644         RC = &SystemZ::GR64BitRegClass;
645         break;
646       case MVT::f32:
647         NumFixedFPRs += 1;
648         RC = &SystemZ::FP32BitRegClass;
649         break;
650       case MVT::f64:
651         NumFixedFPRs += 1;
652         RC = &SystemZ::FP64BitRegClass;
653         break;
654       }
655
656       unsigned VReg = MRI.createVirtualRegister(RC);
657       MRI.addLiveIn(VA.getLocReg(), VReg);
658       ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
659     } else {
660       assert(VA.isMemLoc() && "Argument not register or memory");
661
662       // Create the frame index object for this incoming parameter.
663       int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
664                                       VA.getLocMemOffset(), true);
665
666       // Create the SelectionDAG nodes corresponding to a load
667       // from this parameter.  Unpromoted ints and floats are
668       // passed as right-justified 8-byte values.
669       EVT PtrVT = getPointerTy();
670       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
671       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
672         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4));
673       ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
674                              MachinePointerInfo::getFixedStack(FI),
675                              false, false, false, 0);
676     }
677
678     // Convert the value of the argument register into the value that's
679     // being passed.
680     InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
681   }
682
683   if (IsVarArg) {
684     // Save the number of non-varargs registers for later use by va_start, etc.
685     FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
686     FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
687
688     // Likewise the address (in the form of a frame index) of where the
689     // first stack vararg would be.  The 1-byte size here is arbitrary.
690     int64_t StackSize = CCInfo.getNextStackOffset();
691     FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize, true));
692
693     // ...and a similar frame index for the caller-allocated save area
694     // that will be used to store the incoming registers.
695     int64_t RegSaveOffset = TFL->getOffsetOfLocalArea();
696     unsigned RegSaveIndex = MFI->CreateFixedObject(1, RegSaveOffset, true);
697     FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
698
699     // Store the FPR varargs in the reserved frame slots.  (We store the
700     // GPRs as part of the prologue.)
701     if (NumFixedFPRs < SystemZ::NumArgFPRs) {
702       SDValue MemOps[SystemZ::NumArgFPRs];
703       for (unsigned I = NumFixedFPRs; I < SystemZ::NumArgFPRs; ++I) {
704         unsigned Offset = TFL->getRegSpillOffset(SystemZ::ArgFPRs[I]);
705         int FI = MFI->CreateFixedObject(8, RegSaveOffset + Offset, true);
706         SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
707         unsigned VReg = MF.addLiveIn(SystemZ::ArgFPRs[I],
708                                      &SystemZ::FP64BitRegClass);
709         SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
710         MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
711                                  MachinePointerInfo::getFixedStack(FI),
712                                  false, false, 0);
713
714       }
715       // Join the stores, which are independent of one another.
716       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
717                           &MemOps[NumFixedFPRs],
718                           SystemZ::NumArgFPRs - NumFixedFPRs);
719     }
720   }
721
722   return Chain;
723 }
724
725 static bool canUseSiblingCall(CCState ArgCCInfo,
726                               SmallVectorImpl<CCValAssign> &ArgLocs) {
727   // Punt if there are any indirect or stack arguments, or if the call
728   // needs the call-saved argument register R6.
729   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
730     CCValAssign &VA = ArgLocs[I];
731     if (VA.getLocInfo() == CCValAssign::Indirect)
732       return false;
733     if (!VA.isRegLoc())
734       return false;
735     unsigned Reg = VA.getLocReg();
736     if (Reg == SystemZ::R6W || Reg == SystemZ::R6D)
737       return false;
738   }
739   return true;
740 }
741
742 SDValue
743 SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI,
744                                  SmallVectorImpl<SDValue> &InVals) const {
745   SelectionDAG &DAG = CLI.DAG;
746   SDLoc &DL = CLI.DL;
747   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
748   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
749   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
750   SDValue Chain = CLI.Chain;
751   SDValue Callee = CLI.Callee;
752   bool &IsTailCall = CLI.IsTailCall;
753   CallingConv::ID CallConv = CLI.CallConv;
754   bool IsVarArg = CLI.IsVarArg;
755   MachineFunction &MF = DAG.getMachineFunction();
756   EVT PtrVT = getPointerTy();
757
758   // Analyze the operands of the call, assigning locations to each operand.
759   SmallVector<CCValAssign, 16> ArgLocs;
760   CCState ArgCCInfo(CallConv, IsVarArg, MF, TM, ArgLocs, *DAG.getContext());
761   ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
762
763   // We don't support GuaranteedTailCallOpt, only automatically-detected
764   // sibling calls.
765   if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs))
766     IsTailCall = false;
767
768   // Get a count of how many bytes are to be pushed on the stack.
769   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
770
771   // Mark the start of the call.
772   if (!IsTailCall)
773     Chain = DAG.getCALLSEQ_START(Chain, DAG.getConstant(NumBytes, PtrVT, true),
774                                  DL);
775
776   // Copy argument values to their designated locations.
777   SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass;
778   SmallVector<SDValue, 8> MemOpChains;
779   SDValue StackPtr;
780   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
781     CCValAssign &VA = ArgLocs[I];
782     SDValue ArgValue = OutVals[I];
783
784     if (VA.getLocInfo() == CCValAssign::Indirect) {
785       // Store the argument in a stack slot and pass its address.
786       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
787       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
788       MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, SpillSlot,
789                                          MachinePointerInfo::getFixedStack(FI),
790                                          false, false, 0));
791       ArgValue = SpillSlot;
792     } else
793       ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
794
795     if (VA.isRegLoc())
796       // Queue up the argument copies and emit them at the end.
797       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
798     else {
799       assert(VA.isMemLoc() && "Argument not register or memory");
800
801       // Work out the address of the stack slot.  Unpromoted ints and
802       // floats are passed as right-justified 8-byte values.
803       if (!StackPtr.getNode())
804         StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT);
805       unsigned Offset = SystemZMC::CallFrameSize + VA.getLocMemOffset();
806       if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
807         Offset += 4;
808       SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
809                                     DAG.getIntPtrConstant(Offset));
810
811       // Emit the store.
812       MemOpChains.push_back(DAG.getStore(Chain, DL, ArgValue, Address,
813                                          MachinePointerInfo(),
814                                          false, false, 0));
815     }
816   }
817
818   // Join the stores, which are independent of one another.
819   if (!MemOpChains.empty())
820     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
821                         &MemOpChains[0], MemOpChains.size());
822
823   // Accept direct calls by converting symbolic call addresses to the
824   // associated Target* opcodes.  Force %r1 to be used for indirect
825   // tail calls.
826   SDValue Glue;
827   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
828     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
829     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
830   } else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
831     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
832     Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
833   } else if (IsTailCall) {
834     Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
835     Glue = Chain.getValue(1);
836     Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
837   }
838
839   // Build a sequence of copy-to-reg nodes, chained and glued together.
840   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
841     Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
842                              RegsToPass[I].second, Glue);
843     Glue = Chain.getValue(1);
844   }
845
846   // The first call operand is the chain and the second is the target address.
847   SmallVector<SDValue, 8> Ops;
848   Ops.push_back(Chain);
849   Ops.push_back(Callee);
850
851   // Add argument registers to the end of the list so that they are
852   // known live into the call.
853   for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
854     Ops.push_back(DAG.getRegister(RegsToPass[I].first,
855                                   RegsToPass[I].second.getValueType()));
856
857   // Glue the call to the argument copies, if any.
858   if (Glue.getNode())
859     Ops.push_back(Glue);
860
861   // Emit the call.
862   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
863   if (IsTailCall)
864     return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, &Ops[0], Ops.size());
865   Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, &Ops[0], Ops.size());
866   Glue = Chain.getValue(1);
867
868   // Mark the end of the call, which is glued to the call itself.
869   Chain = DAG.getCALLSEQ_END(Chain,
870                              DAG.getConstant(NumBytes, PtrVT, true),
871                              DAG.getConstant(0, PtrVT, true),
872                              Glue, DL);
873   Glue = Chain.getValue(1);
874
875   // Assign locations to each value returned by this call.
876   SmallVector<CCValAssign, 16> RetLocs;
877   CCState RetCCInfo(CallConv, IsVarArg, MF, TM, RetLocs, *DAG.getContext());
878   RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
879
880   // Copy all of the result registers out of their specified physreg.
881   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
882     CCValAssign &VA = RetLocs[I];
883
884     // Copy the value out, gluing the copy to the end of the call sequence.
885     SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
886                                           VA.getLocVT(), Glue);
887     Chain = RetValue.getValue(1);
888     Glue = RetValue.getValue(2);
889
890     // Convert the value of the return register into the value that's
891     // being returned.
892     InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
893   }
894
895   return Chain;
896 }
897
898 SDValue
899 SystemZTargetLowering::LowerReturn(SDValue Chain,
900                                    CallingConv::ID CallConv, bool IsVarArg,
901                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
902                                    const SmallVectorImpl<SDValue> &OutVals,
903                                    SDLoc DL, SelectionDAG &DAG) const {
904   MachineFunction &MF = DAG.getMachineFunction();
905
906   // Assign locations to each returned value.
907   SmallVector<CCValAssign, 16> RetLocs;
908   CCState RetCCInfo(CallConv, IsVarArg, MF, TM, RetLocs, *DAG.getContext());
909   RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
910
911   // Quick exit for void returns
912   if (RetLocs.empty())
913     return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
914
915   // Copy the result values into the output registers.
916   SDValue Glue;
917   SmallVector<SDValue, 4> RetOps;
918   RetOps.push_back(Chain);
919   for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
920     CCValAssign &VA = RetLocs[I];
921     SDValue RetValue = OutVals[I];
922
923     // Make the return register live on exit.
924     assert(VA.isRegLoc() && "Can only return in registers!");
925
926     // Promote the value as required.
927     RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
928
929     // Chain and glue the copies together.
930     unsigned Reg = VA.getLocReg();
931     Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
932     Glue = Chain.getValue(1);
933     RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
934   }
935
936   // Update chain and glue.
937   RetOps[0] = Chain;
938   if (Glue.getNode())
939     RetOps.push_back(Glue);
940
941   return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other,
942                      RetOps.data(), RetOps.size());
943 }
944
945 // CC is a comparison that will be implemented using an integer or
946 // floating-point comparison.  Return the condition code mask for
947 // a branch on true.  In the integer case, CCMASK_CMP_UO is set for
948 // unsigned comparisons and clear for signed ones.  In the floating-point
949 // case, CCMASK_CMP_UO has its normal mask meaning (unordered).
950 static unsigned CCMaskForCondCode(ISD::CondCode CC) {
951 #define CONV(X) \
952   case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
953   case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
954   case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
955
956   switch (CC) {
957   default:
958     llvm_unreachable("Invalid integer condition!");
959
960   CONV(EQ);
961   CONV(NE);
962   CONV(GT);
963   CONV(GE);
964   CONV(LT);
965   CONV(LE);
966
967   case ISD::SETO:  return SystemZ::CCMASK_CMP_O;
968   case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
969   }
970 #undef CONV
971 }
972
973 // If a comparison described by IsUnsigned, CCMask, CmpOp0 and CmpOp1
974 // can be converted to a comparison against zero, adjust the operands
975 // as necessary.
976 static void adjustZeroCmp(SelectionDAG &DAG, bool &IsUnsigned,
977                           SDValue &CmpOp0, SDValue &CmpOp1,
978                           unsigned &CCMask) {
979   if (IsUnsigned)
980     return;
981
982   ConstantSDNode *ConstOp1 = dyn_cast<ConstantSDNode>(CmpOp1.getNode());
983   if (!ConstOp1)
984     return;
985
986   int64_t Value = ConstOp1->getSExtValue();
987   if ((Value == -1 && CCMask == SystemZ::CCMASK_CMP_GT) ||
988       (Value == -1 && CCMask == SystemZ::CCMASK_CMP_LE) ||
989       (Value == 1 && CCMask == SystemZ::CCMASK_CMP_LT) ||
990       (Value == 1 && CCMask == SystemZ::CCMASK_CMP_GE)) {
991     CCMask ^= SystemZ::CCMASK_CMP_EQ;
992     CmpOp1 = DAG.getConstant(0, CmpOp1.getValueType());
993   }
994 }
995
996 // If a comparison described by IsUnsigned, CCMask, CmpOp0 and CmpOp1
997 // is suitable for CLI(Y), CHHSI or CLHHSI, adjust the operands as necessary.
998 static void adjustSubwordCmp(SelectionDAG &DAG, bool &IsUnsigned,
999                              SDValue &CmpOp0, SDValue &CmpOp1,
1000                              unsigned &CCMask) {
1001   // For us to make any changes, it must a comparison between a single-use
1002   // load and a constant.
1003   if (!CmpOp0.hasOneUse() ||
1004       CmpOp0.getOpcode() != ISD::LOAD ||
1005       CmpOp1.getOpcode() != ISD::Constant)
1006     return;
1007
1008   // We must have an 8- or 16-bit load.
1009   LoadSDNode *Load = cast<LoadSDNode>(CmpOp0);
1010   unsigned NumBits = Load->getMemoryVT().getStoreSizeInBits();
1011   if (NumBits != 8 && NumBits != 16)
1012     return;
1013
1014   // The load must be an extending one and the constant must be within the
1015   // range of the unextended value.
1016   ConstantSDNode *Constant = cast<ConstantSDNode>(CmpOp1);
1017   uint64_t Value = Constant->getZExtValue();
1018   uint64_t Mask = (1 << NumBits) - 1;
1019   if (Load->getExtensionType() == ISD::SEXTLOAD) {
1020     int64_t SignedValue = Constant->getSExtValue();
1021     if (uint64_t(SignedValue) + (1ULL << (NumBits - 1)) > Mask)
1022       return;
1023     // Unsigned comparison between two sign-extended values is equivalent
1024     // to unsigned comparison between two zero-extended values.
1025     if (IsUnsigned)
1026       Value &= Mask;
1027     else if (CCMask == SystemZ::CCMASK_CMP_EQ ||
1028              CCMask == SystemZ::CCMASK_CMP_NE)
1029       // Any choice of IsUnsigned is OK for equality comparisons.
1030       // We could use either CHHSI or CLHHSI for 16-bit comparisons,
1031       // but since we use CLHHSI for zero extensions, it seems better
1032       // to be consistent and do the same here.
1033       Value &= Mask, IsUnsigned = true;
1034     else if (NumBits == 8) {
1035       // Try to treat the comparison as unsigned, so that we can use CLI.
1036       // Adjust CCMask and Value as necessary.
1037       if (Value == 0 && CCMask == SystemZ::CCMASK_CMP_LT)
1038         // Test whether the high bit of the byte is set.
1039         Value = 127, CCMask = SystemZ::CCMASK_CMP_GT, IsUnsigned = true;
1040       else if (Value == 0 && CCMask == SystemZ::CCMASK_CMP_GE)
1041         // Test whether the high bit of the byte is clear.
1042         Value = 128, CCMask = SystemZ::CCMASK_CMP_LT, IsUnsigned = true;
1043       else
1044         // No instruction exists for this combination.
1045         return;
1046     }
1047   } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
1048     if (Value > Mask)
1049       return;
1050     // Signed comparison between two zero-extended values is equivalent
1051     // to unsigned comparison.
1052     IsUnsigned = true;
1053   } else
1054     return;
1055
1056   // Make sure that the first operand is an i32 of the right extension type.
1057   ISD::LoadExtType ExtType = IsUnsigned ? ISD::ZEXTLOAD : ISD::SEXTLOAD;
1058   if (CmpOp0.getValueType() != MVT::i32 ||
1059       Load->getExtensionType() != ExtType)
1060     CmpOp0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32,
1061                             Load->getChain(), Load->getBasePtr(),
1062                             Load->getPointerInfo(), Load->getMemoryVT(),
1063                             Load->isVolatile(), Load->isNonTemporal(),
1064                             Load->getAlignment());
1065
1066   // Make sure that the second operand is an i32 with the right value.
1067   if (CmpOp1.getValueType() != MVT::i32 ||
1068       Value != Constant->getZExtValue())
1069     CmpOp1 = DAG.getConstant(Value, MVT::i32);
1070 }
1071
1072 // Return true if Op is either an unextended load, or a load suitable
1073 // for integer register-memory comparisons of type ICmpType.
1074 static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
1075   LoadSDNode *Load = dyn_cast<LoadSDNode>(Op.getNode());
1076   if (Load) {
1077     // There are no instructions to compare a register with a memory byte.
1078     if (Load->getMemoryVT() == MVT::i8)
1079       return false;
1080     // Otherwise decide on extension type.
1081     switch (Load->getExtensionType()) {
1082     case ISD::NON_EXTLOAD:
1083       return true;
1084     case ISD::SEXTLOAD:
1085       return ICmpType != SystemZICMP::UnsignedOnly;
1086     case ISD::ZEXTLOAD:
1087       return ICmpType != SystemZICMP::SignedOnly;
1088     default:
1089       break;
1090     }
1091   }
1092   return false;
1093 }
1094
1095 // Return true if it is better to swap comparison operands Op0 and Op1.
1096 // ICmpType is the type of an integer comparison.
1097 static bool shouldSwapCmpOperands(SDValue Op0, SDValue Op1,
1098                                   unsigned ICmpType) {
1099   // Leave f128 comparisons alone, since they have no memory forms.
1100   if (Op0.getValueType() == MVT::f128)
1101     return false;
1102
1103   // Always keep a floating-point constant second, since comparisons with
1104   // zero can use LOAD TEST and comparisons with other constants make a
1105   // natural memory operand.
1106   if (isa<ConstantFPSDNode>(Op1))
1107     return false;
1108
1109   // Never swap comparisons with zero since there are many ways to optimize
1110   // those later.
1111   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
1112   if (COp1 && COp1->getZExtValue() == 0)
1113     return false;
1114
1115   // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
1116   // In that case we generally prefer the memory to be second.
1117   if ((isNaturalMemoryOperand(Op0, ICmpType) && Op0.hasOneUse()) &&
1118       !(isNaturalMemoryOperand(Op1, ICmpType) && Op1.hasOneUse())) {
1119     // The only exceptions are when the second operand is a constant and
1120     // we can use things like CHHSI.
1121     if (!COp1)
1122       return true;
1123     // The unsigned memory-immediate instructions can handle 16-bit
1124     // unsigned integers.
1125     if (ICmpType != SystemZICMP::SignedOnly &&
1126         isUInt<16>(COp1->getZExtValue()))
1127       return false;
1128     // The signed memory-immediate instructions can handle 16-bit
1129     // signed integers.
1130     if (ICmpType != SystemZICMP::UnsignedOnly &&
1131         isInt<16>(COp1->getSExtValue()))
1132       return false;
1133     return true;
1134   }
1135   return false;
1136 }
1137
1138 // Return true if shift operation N has an in-range constant shift value.
1139 // Store it in ShiftVal if so.
1140 static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
1141   ConstantSDNode *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
1142   if (!Shift)
1143     return false;
1144
1145   uint64_t Amount = Shift->getZExtValue();
1146   if (Amount >= N.getValueType().getSizeInBits())
1147     return false;
1148
1149   ShiftVal = Amount;
1150   return true;
1151 }
1152
1153 // Check whether an AND with Mask is suitable for a TEST UNDER MASK
1154 // instruction and whether the CC value is descriptive enough to handle
1155 // a comparison of type Opcode between the AND result and CmpVal.
1156 // CCMask says which comparison result is being tested and BitSize is
1157 // the number of bits in the operands.  If TEST UNDER MASK can be used,
1158 // return the corresponding CC mask, otherwise return 0.
1159 static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
1160                                      uint64_t Mask, uint64_t CmpVal,
1161                                      unsigned ICmpType) {
1162   assert(Mask != 0 && "ANDs with zero should have been removed by now");
1163
1164   // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
1165   if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
1166       !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
1167     return 0;
1168
1169   // Work out the masks for the lowest and highest bits.
1170   unsigned HighShift = 63 - countLeadingZeros(Mask);
1171   uint64_t High = uint64_t(1) << HighShift;
1172   uint64_t Low = uint64_t(1) << countTrailingZeros(Mask);
1173
1174   // Signed ordered comparisons are effectively unsigned if the sign
1175   // bit is dropped.
1176   bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
1177
1178   // Check for equality comparisons with 0, or the equivalent.
1179   if (CmpVal == 0) {
1180     if (CCMask == SystemZ::CCMASK_CMP_EQ)
1181       return SystemZ::CCMASK_TM_ALL_0;
1182     if (CCMask == SystemZ::CCMASK_CMP_NE)
1183       return SystemZ::CCMASK_TM_SOME_1;
1184   }
1185   if (EffectivelyUnsigned && CmpVal <= Low) {
1186     if (CCMask == SystemZ::CCMASK_CMP_LT)
1187       return SystemZ::CCMASK_TM_ALL_0;
1188     if (CCMask == SystemZ::CCMASK_CMP_GE)
1189       return SystemZ::CCMASK_TM_SOME_1;
1190   }
1191   if (EffectivelyUnsigned && CmpVal < Low) {
1192     if (CCMask == SystemZ::CCMASK_CMP_LE)
1193       return SystemZ::CCMASK_TM_ALL_0;
1194     if (CCMask == SystemZ::CCMASK_CMP_GT)
1195       return SystemZ::CCMASK_TM_SOME_1;
1196   }
1197
1198   // Check for equality comparisons with the mask, or the equivalent.
1199   if (CmpVal == Mask) {
1200     if (CCMask == SystemZ::CCMASK_CMP_EQ)
1201       return SystemZ::CCMASK_TM_ALL_1;
1202     if (CCMask == SystemZ::CCMASK_CMP_NE)
1203       return SystemZ::CCMASK_TM_SOME_0;
1204   }
1205   if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
1206     if (CCMask == SystemZ::CCMASK_CMP_GT)
1207       return SystemZ::CCMASK_TM_ALL_1;
1208     if (CCMask == SystemZ::CCMASK_CMP_LE)
1209       return SystemZ::CCMASK_TM_SOME_0;
1210   }
1211   if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
1212     if (CCMask == SystemZ::CCMASK_CMP_GE)
1213       return SystemZ::CCMASK_TM_ALL_1;
1214     if (CCMask == SystemZ::CCMASK_CMP_LT)
1215       return SystemZ::CCMASK_TM_SOME_0;
1216   }
1217
1218   // Check for ordered comparisons with the top bit.
1219   if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
1220     if (CCMask == SystemZ::CCMASK_CMP_LE)
1221       return SystemZ::CCMASK_TM_MSB_0;
1222     if (CCMask == SystemZ::CCMASK_CMP_GT)
1223       return SystemZ::CCMASK_TM_MSB_1;
1224   }
1225   if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
1226     if (CCMask == SystemZ::CCMASK_CMP_LT)
1227       return SystemZ::CCMASK_TM_MSB_0;
1228     if (CCMask == SystemZ::CCMASK_CMP_GE)
1229       return SystemZ::CCMASK_TM_MSB_1;
1230   }
1231
1232   // If there are just two bits, we can do equality checks for Low and High
1233   // as well.
1234   if (Mask == Low + High) {
1235     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
1236       return SystemZ::CCMASK_TM_MIXED_MSB_0;
1237     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
1238       return SystemZ::CCMASK_TM_MIXED_MSB_0 ^ SystemZ::CCMASK_ANY;
1239     if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
1240       return SystemZ::CCMASK_TM_MIXED_MSB_1;
1241     if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
1242       return SystemZ::CCMASK_TM_MIXED_MSB_1 ^ SystemZ::CCMASK_ANY;
1243   }
1244
1245   // Looks like we've exhausted our options.
1246   return 0;
1247 }
1248
1249 // See whether the comparison (Opcode CmpOp0, CmpOp1, ICmpType) can be
1250 // implemented as a TEST UNDER MASK instruction when the condition being
1251 // tested is as described by CCValid and CCMask.  Update the arguments
1252 // with the TM version if so.
1253 static void adjustForTestUnderMask(SelectionDAG &DAG, unsigned &Opcode,
1254                                    SDValue &CmpOp0, SDValue &CmpOp1,
1255                                    unsigned &CCValid, unsigned &CCMask,
1256                                    unsigned &ICmpType) {
1257   // Check that we have a comparison with a constant.
1258   ConstantSDNode *ConstCmpOp1 = dyn_cast<ConstantSDNode>(CmpOp1);
1259   if (!ConstCmpOp1)
1260     return;
1261   uint64_t CmpVal = ConstCmpOp1->getZExtValue();
1262
1263   // Check whether the nonconstant input is an AND with a constant mask.
1264   if (CmpOp0.getOpcode() != ISD::AND)
1265     return;
1266   SDValue AndOp0 = CmpOp0.getOperand(0);
1267   SDValue AndOp1 = CmpOp0.getOperand(1);
1268   ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(AndOp1.getNode());
1269   if (!Mask)
1270     return;
1271   uint64_t MaskVal = Mask->getZExtValue();
1272
1273   // Check whether the combination of mask, comparison value and comparison
1274   // type are suitable.
1275   unsigned BitSize = CmpOp0.getValueType().getSizeInBits();
1276   unsigned NewCCMask, ShiftVal;
1277   if (ICmpType != SystemZICMP::SignedOnly &&
1278       AndOp0.getOpcode() == ISD::SHL &&
1279       isSimpleShift(AndOp0, ShiftVal) &&
1280       (NewCCMask = getTestUnderMaskCond(BitSize, CCMask, MaskVal >> ShiftVal,
1281                                         CmpVal >> ShiftVal,
1282                                         SystemZICMP::Any))) {
1283     AndOp0 = AndOp0.getOperand(0);
1284     AndOp1 = DAG.getConstant(MaskVal >> ShiftVal, AndOp0.getValueType());
1285   } else if (ICmpType != SystemZICMP::SignedOnly &&
1286              AndOp0.getOpcode() == ISD::SRL &&
1287              isSimpleShift(AndOp0, ShiftVal) &&
1288              (NewCCMask = getTestUnderMaskCond(BitSize, CCMask,
1289                                                MaskVal << ShiftVal,
1290                                                CmpVal << ShiftVal,
1291                                                SystemZICMP::UnsignedOnly))) {
1292     AndOp0 = AndOp0.getOperand(0);
1293     AndOp1 = DAG.getConstant(MaskVal << ShiftVal, AndOp0.getValueType());
1294   } else {
1295     NewCCMask = getTestUnderMaskCond(BitSize, CCMask, MaskVal, CmpVal,
1296                                      ICmpType);
1297     if (!NewCCMask)
1298       return;
1299   }
1300
1301   // Go ahead and make the change.
1302   Opcode = SystemZISD::TM;
1303   CmpOp0 = AndOp0;
1304   CmpOp1 = AndOp1;
1305   ICmpType = (bool(NewCCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
1306               bool(NewCCMask & SystemZ::CCMASK_TM_MIXED_MSB_1));
1307   CCValid = SystemZ::CCMASK_TM;
1308   CCMask = NewCCMask;
1309 }
1310
1311 // Return a target node that compares CmpOp0 with CmpOp1 and stores a
1312 // 2-bit result in CC.  Set CCValid to the CCMASK_* of all possible
1313 // 2-bit results and CCMask to the subset of those results that are
1314 // associated with Cond.
1315 static SDValue emitCmp(const SystemZTargetMachine &TM, SelectionDAG &DAG,
1316                        SDLoc DL, SDValue CmpOp0, SDValue CmpOp1,
1317                        ISD::CondCode Cond, unsigned &CCValid,
1318                        unsigned &CCMask) {
1319   bool IsUnsigned = false;
1320   CCMask = CCMaskForCondCode(Cond);
1321   unsigned Opcode, ICmpType = 0;
1322   if (CmpOp0.getValueType().isFloatingPoint()) {
1323     CCValid = SystemZ::CCMASK_FCMP;
1324     Opcode = SystemZISD::FCMP;
1325   } else {
1326     IsUnsigned = CCMask & SystemZ::CCMASK_CMP_UO;
1327     CCValid = SystemZ::CCMASK_ICMP;
1328     CCMask &= CCValid;
1329     adjustZeroCmp(DAG, IsUnsigned, CmpOp0, CmpOp1, CCMask);
1330     adjustSubwordCmp(DAG, IsUnsigned, CmpOp0, CmpOp1, CCMask);
1331     Opcode = SystemZISD::ICMP;
1332     // Choose the type of comparison.  Equality and inequality tests can
1333     // use either signed or unsigned comparisons.  The choice also doesn't
1334     // matter if both sign bits are known to be clear.  In those cases we
1335     // want to give the main isel code the freedom to choose whichever
1336     // form fits best.
1337     if (CCMask == SystemZ::CCMASK_CMP_EQ ||
1338         CCMask == SystemZ::CCMASK_CMP_NE ||
1339         (DAG.SignBitIsZero(CmpOp0) && DAG.SignBitIsZero(CmpOp1)))
1340       ICmpType = SystemZICMP::Any;
1341     else if (IsUnsigned)
1342       ICmpType = SystemZICMP::UnsignedOnly;
1343     else
1344       ICmpType = SystemZICMP::SignedOnly;
1345   }
1346
1347   if (shouldSwapCmpOperands(CmpOp0, CmpOp1, ICmpType)) {
1348     std::swap(CmpOp0, CmpOp1);
1349     CCMask = ((CCMask & SystemZ::CCMASK_CMP_EQ) |
1350               (CCMask & SystemZ::CCMASK_CMP_GT ? SystemZ::CCMASK_CMP_LT : 0) |
1351               (CCMask & SystemZ::CCMASK_CMP_LT ? SystemZ::CCMASK_CMP_GT : 0) |
1352               (CCMask & SystemZ::CCMASK_CMP_UO));
1353   }
1354
1355   adjustForTestUnderMask(DAG, Opcode, CmpOp0, CmpOp1, CCValid, CCMask,
1356                          ICmpType);
1357   if (Opcode == SystemZISD::ICMP || Opcode == SystemZISD::TM)
1358     return DAG.getNode(Opcode, DL, MVT::Glue, CmpOp0, CmpOp1,
1359                        DAG.getConstant(ICmpType, MVT::i32));
1360   return DAG.getNode(Opcode, DL, MVT::Glue, CmpOp0, CmpOp1);
1361 }
1362
1363 // Implement a 32-bit *MUL_LOHI operation by extending both operands to
1364 // 64 bits.  Extend is the extension type to use.  Store the high part
1365 // in Hi and the low part in Lo.
1366 static void lowerMUL_LOHI32(SelectionDAG &DAG, SDLoc DL,
1367                             unsigned Extend, SDValue Op0, SDValue Op1,
1368                             SDValue &Hi, SDValue &Lo) {
1369   Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
1370   Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
1371   SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
1372   Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, DAG.getConstant(32, MVT::i64));
1373   Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
1374   Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
1375 }
1376
1377 // Lower a binary operation that produces two VT results, one in each
1378 // half of a GR128 pair.  Op0 and Op1 are the VT operands to the operation,
1379 // Extend extends Op0 to a GR128, and Opcode performs the GR128 operation
1380 // on the extended Op0 and (unextended) Op1.  Store the even register result
1381 // in Even and the odd register result in Odd.
1382 static void lowerGR128Binary(SelectionDAG &DAG, SDLoc DL, EVT VT,
1383                              unsigned Extend, unsigned Opcode,
1384                              SDValue Op0, SDValue Op1,
1385                              SDValue &Even, SDValue &Odd) {
1386   SDNode *In128 = DAG.getMachineNode(Extend, DL, MVT::Untyped, Op0);
1387   SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped,
1388                                SDValue(In128, 0), Op1);
1389   bool Is32Bit = is32Bit(VT);
1390   SDValue SubReg0 = DAG.getTargetConstant(SystemZ::even128(Is32Bit), VT);
1391   SDValue SubReg1 = DAG.getTargetConstant(SystemZ::odd128(Is32Bit), VT);
1392   SDNode *Reg0 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
1393                                     VT, Result, SubReg0);
1394   SDNode *Reg1 = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
1395                                     VT, Result, SubReg1);
1396   Even = SDValue(Reg0, 0);
1397   Odd = SDValue(Reg1, 0);
1398 }
1399
1400 SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
1401   SDValue Chain    = Op.getOperand(0);
1402   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1403   SDValue CmpOp0   = Op.getOperand(2);
1404   SDValue CmpOp1   = Op.getOperand(3);
1405   SDValue Dest     = Op.getOperand(4);
1406   SDLoc DL(Op);
1407
1408   unsigned CCValid, CCMask;
1409   SDValue Flags = emitCmp(TM, DAG, DL, CmpOp0, CmpOp1, CC, CCValid, CCMask);
1410   return DAG.getNode(SystemZISD::BR_CCMASK, DL, Op.getValueType(),
1411                      Chain, DAG.getConstant(CCValid, MVT::i32),
1412                      DAG.getConstant(CCMask, MVT::i32), Dest, Flags);
1413 }
1414
1415 SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
1416                                               SelectionDAG &DAG) const {
1417   SDValue CmpOp0   = Op.getOperand(0);
1418   SDValue CmpOp1   = Op.getOperand(1);
1419   SDValue TrueOp   = Op.getOperand(2);
1420   SDValue FalseOp  = Op.getOperand(3);
1421   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1422   SDLoc DL(Op);
1423
1424   unsigned CCValid, CCMask;
1425   SDValue Flags = emitCmp(TM, DAG, DL, CmpOp0, CmpOp1, CC, CCValid, CCMask);
1426
1427   SmallVector<SDValue, 5> Ops;
1428   Ops.push_back(TrueOp);
1429   Ops.push_back(FalseOp);
1430   Ops.push_back(DAG.getConstant(CCValid, MVT::i32));
1431   Ops.push_back(DAG.getConstant(CCMask, MVT::i32));
1432   Ops.push_back(Flags);
1433
1434   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
1435   return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VTs, &Ops[0], Ops.size());
1436 }
1437
1438 SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
1439                                                   SelectionDAG &DAG) const {
1440   SDLoc DL(Node);
1441   const GlobalValue *GV = Node->getGlobal();
1442   int64_t Offset = Node->getOffset();
1443   EVT PtrVT = getPointerTy();
1444   Reloc::Model RM = TM.getRelocationModel();
1445   CodeModel::Model CM = TM.getCodeModel();
1446
1447   SDValue Result;
1448   if (Subtarget.isPC32DBLSymbol(GV, RM, CM)) {
1449     // Make sure that the offset is aligned to a halfword.  If it isn't,
1450     // create an "anchor" at the previous 12-bit boundary.
1451     // FIXME check whether there is a better way of handling this.
1452     if (Offset & 1) {
1453       Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1454                                           Offset & ~uint64_t(0xfff));
1455       Offset &= 0xfff;
1456     } else {
1457       Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Offset);
1458       Offset = 0;
1459     }
1460     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1461   } else {
1462     Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
1463     Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1464     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
1465                          MachinePointerInfo::getGOT(), false, false, false, 0);
1466   }
1467
1468   // If there was a non-zero offset that we didn't fold, create an explicit
1469   // addition for it.
1470   if (Offset != 0)
1471     Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
1472                          DAG.getConstant(Offset, PtrVT));
1473
1474   return Result;
1475 }
1476
1477 SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
1478                                                      SelectionDAG &DAG) const {
1479   SDLoc DL(Node);
1480   const GlobalValue *GV = Node->getGlobal();
1481   EVT PtrVT = getPointerTy();
1482   TLSModel::Model model = TM.getTLSModel(GV);
1483
1484   if (model != TLSModel::LocalExec)
1485     llvm_unreachable("only local-exec TLS mode supported");
1486
1487   // The high part of the thread pointer is in access register 0.
1488   SDValue TPHi = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
1489                              DAG.getConstant(0, MVT::i32));
1490   TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
1491
1492   // The low part of the thread pointer is in access register 1.
1493   SDValue TPLo = DAG.getNode(SystemZISD::EXTRACT_ACCESS, DL, MVT::i32,
1494                              DAG.getConstant(1, MVT::i32));
1495   TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
1496
1497   // Merge them into a single 64-bit address.
1498   SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
1499                                     DAG.getConstant(32, PtrVT));
1500   SDValue TP = DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
1501
1502   // Get the offset of GA from the thread pointer.
1503   SystemZConstantPoolValue *CPV =
1504     SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF);
1505
1506   // Force the offset into the constant pool and load it from there.
1507   SDValue CPAddr = DAG.getConstantPool(CPV, PtrVT, 8);
1508   SDValue Offset = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(),
1509                                CPAddr, MachinePointerInfo::getConstantPool(),
1510                                false, false, false, 0);
1511
1512   // Add the base and offset together.
1513   return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
1514 }
1515
1516 SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
1517                                                  SelectionDAG &DAG) const {
1518   SDLoc DL(Node);
1519   const BlockAddress *BA = Node->getBlockAddress();
1520   int64_t Offset = Node->getOffset();
1521   EVT PtrVT = getPointerTy();
1522
1523   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
1524   Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1525   return Result;
1526 }
1527
1528 SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
1529                                               SelectionDAG &DAG) const {
1530   SDLoc DL(JT);
1531   EVT PtrVT = getPointerTy();
1532   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1533
1534   // Use LARL to load the address of the table.
1535   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1536 }
1537
1538 SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
1539                                                  SelectionDAG &DAG) const {
1540   SDLoc DL(CP);
1541   EVT PtrVT = getPointerTy();
1542
1543   SDValue Result;
1544   if (CP->isMachineConstantPoolEntry())
1545     Result = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
1546                                        CP->getAlignment());
1547   else
1548     Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
1549                                        CP->getAlignment(), CP->getOffset());
1550
1551   // Use LARL to load the address of the constant pool entry.
1552   return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
1553 }
1554
1555 SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
1556                                             SelectionDAG &DAG) const {
1557   SDLoc DL(Op);
1558   SDValue In = Op.getOperand(0);
1559   EVT InVT = In.getValueType();
1560   EVT ResVT = Op.getValueType();
1561
1562   SDValue SubReg32 = DAG.getTargetConstant(SystemZ::subreg_32bit, MVT::i64);
1563   SDValue Shift32 = DAG.getConstant(32, MVT::i64);
1564   if (InVT == MVT::i32 && ResVT == MVT::f32) {
1565     SDValue In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
1566     SDValue Shift = DAG.getNode(ISD::SHL, DL, MVT::i64, In64, Shift32);
1567     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Shift);
1568     SDNode *Out = DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
1569                                      MVT::f32, Out64, SubReg32);
1570     return SDValue(Out, 0);
1571   }
1572   if (InVT == MVT::f32 && ResVT == MVT::i32) {
1573     SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
1574     SDNode *In64 = DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
1575                                       MVT::f64, SDValue(U64, 0), In, SubReg32);
1576     SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, SDValue(In64, 0));
1577     SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64, Shift32);
1578     SDValue Out = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
1579     return Out;
1580   }
1581   llvm_unreachable("Unexpected bitcast combination");
1582 }
1583
1584 SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
1585                                             SelectionDAG &DAG) const {
1586   MachineFunction &MF = DAG.getMachineFunction();
1587   SystemZMachineFunctionInfo *FuncInfo =
1588     MF.getInfo<SystemZMachineFunctionInfo>();
1589   EVT PtrVT = getPointerTy();
1590
1591   SDValue Chain   = Op.getOperand(0);
1592   SDValue Addr    = Op.getOperand(1);
1593   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1594   SDLoc DL(Op);
1595
1596   // The initial values of each field.
1597   const unsigned NumFields = 4;
1598   SDValue Fields[NumFields] = {
1599     DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), PtrVT),
1600     DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), PtrVT),
1601     DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
1602     DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
1603   };
1604
1605   // Store each field into its respective slot.
1606   SDValue MemOps[NumFields];
1607   unsigned Offset = 0;
1608   for (unsigned I = 0; I < NumFields; ++I) {
1609     SDValue FieldAddr = Addr;
1610     if (Offset != 0)
1611       FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
1612                               DAG.getIntPtrConstant(Offset));
1613     MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
1614                              MachinePointerInfo(SV, Offset),
1615                              false, false, 0);
1616     Offset += 8;
1617   }
1618   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps, NumFields);
1619 }
1620
1621 SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
1622                                            SelectionDAG &DAG) const {
1623   SDValue Chain      = Op.getOperand(0);
1624   SDValue DstPtr     = Op.getOperand(1);
1625   SDValue SrcPtr     = Op.getOperand(2);
1626   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
1627   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
1628   SDLoc DL(Op);
1629
1630   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32),
1631                        /*Align*/8, /*isVolatile*/false, /*AlwaysInline*/false,
1632                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
1633 }
1634
1635 SDValue SystemZTargetLowering::
1636 lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
1637   SDValue Chain = Op.getOperand(0);
1638   SDValue Size  = Op.getOperand(1);
1639   SDLoc DL(Op);
1640
1641   unsigned SPReg = getStackPointerRegisterToSaveRestore();
1642
1643   // Get a reference to the stack pointer.
1644   SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
1645
1646   // Get the new stack pointer value.
1647   SDValue NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, Size);
1648
1649   // Copy the new stack pointer back.
1650   Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
1651
1652   // The allocated data lives above the 160 bytes allocated for the standard
1653   // frame, plus any outgoing stack arguments.  We don't know how much that
1654   // amounts to yet, so emit a special ADJDYNALLOC placeholder.
1655   SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
1656   SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
1657
1658   SDValue Ops[2] = { Result, Chain };
1659   return DAG.getMergeValues(Ops, 2, DL);
1660 }
1661
1662 SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
1663                                               SelectionDAG &DAG) const {
1664   EVT VT = Op.getValueType();
1665   SDLoc DL(Op);
1666   SDValue Ops[2];
1667   if (is32Bit(VT))
1668     // Just do a normal 64-bit multiplication and extract the results.
1669     // We define this so that it can be used for constant division.
1670     lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
1671                     Op.getOperand(1), Ops[1], Ops[0]);
1672   else {
1673     // Do a full 128-bit multiplication based on UMUL_LOHI64:
1674     //
1675     //   (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
1676     //
1677     // but using the fact that the upper halves are either all zeros
1678     // or all ones:
1679     //
1680     //   (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
1681     //
1682     // and grouping the right terms together since they are quicker than the
1683     // multiplication:
1684     //
1685     //   (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
1686     SDValue C63 = DAG.getConstant(63, MVT::i64);
1687     SDValue LL = Op.getOperand(0);
1688     SDValue RL = Op.getOperand(1);
1689     SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
1690     SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
1691     // UMUL_LOHI64 returns the low result in the odd register and the high
1692     // result in the even register.  SMUL_LOHI is defined to return the
1693     // low half first, so the results are in reverse order.
1694     lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
1695                      LL, RL, Ops[1], Ops[0]);
1696     SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
1697     SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
1698     SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
1699     Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
1700   }
1701   return DAG.getMergeValues(Ops, 2, DL);
1702 }
1703
1704 SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
1705                                               SelectionDAG &DAG) const {
1706   EVT VT = Op.getValueType();
1707   SDLoc DL(Op);
1708   SDValue Ops[2];
1709   if (is32Bit(VT))
1710     // Just do a normal 64-bit multiplication and extract the results.
1711     // We define this so that it can be used for constant division.
1712     lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
1713                     Op.getOperand(1), Ops[1], Ops[0]);
1714   else
1715     // UMUL_LOHI64 returns the low result in the odd register and the high
1716     // result in the even register.  UMUL_LOHI is defined to return the
1717     // low half first, so the results are in reverse order.
1718     lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, SystemZISD::UMUL_LOHI64,
1719                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
1720   return DAG.getMergeValues(Ops, 2, DL);
1721 }
1722
1723 SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
1724                                             SelectionDAG &DAG) const {
1725   SDValue Op0 = Op.getOperand(0);
1726   SDValue Op1 = Op.getOperand(1);
1727   EVT VT = Op.getValueType();
1728   SDLoc DL(Op);
1729   unsigned Opcode;
1730
1731   // We use DSGF for 32-bit division.
1732   if (is32Bit(VT)) {
1733     Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
1734     Opcode = SystemZISD::SDIVREM32;
1735   } else if (DAG.ComputeNumSignBits(Op1) > 32) {
1736     Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
1737     Opcode = SystemZISD::SDIVREM32;
1738   } else    
1739     Opcode = SystemZISD::SDIVREM64;
1740
1741   // DSG(F) takes a 64-bit dividend, so the even register in the GR128
1742   // input is "don't care".  The instruction returns the remainder in
1743   // the even register and the quotient in the odd register.
1744   SDValue Ops[2];
1745   lowerGR128Binary(DAG, DL, VT, SystemZ::AEXT128_64, Opcode,
1746                    Op0, Op1, Ops[1], Ops[0]);
1747   return DAG.getMergeValues(Ops, 2, DL);
1748 }
1749
1750 SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
1751                                             SelectionDAG &DAG) const {
1752   EVT VT = Op.getValueType();
1753   SDLoc DL(Op);
1754
1755   // DL(G) uses a double-width dividend, so we need to clear the even
1756   // register in the GR128 input.  The instruction returns the remainder
1757   // in the even register and the quotient in the odd register.
1758   SDValue Ops[2];
1759   if (is32Bit(VT))
1760     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_32, SystemZISD::UDIVREM32,
1761                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
1762   else
1763     lowerGR128Binary(DAG, DL, VT, SystemZ::ZEXT128_64, SystemZISD::UDIVREM64,
1764                      Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
1765   return DAG.getMergeValues(Ops, 2, DL);
1766 }
1767
1768 SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
1769   assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation");
1770
1771   // Get the known-zero masks for each operand.
1772   SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
1773   APInt KnownZero[2], KnownOne[2];
1774   DAG.ComputeMaskedBits(Ops[0], KnownZero[0], KnownOne[0]);
1775   DAG.ComputeMaskedBits(Ops[1], KnownZero[1], KnownOne[1]);
1776
1777   // See if the upper 32 bits of one operand and the lower 32 bits of the
1778   // other are known zero.  They are the low and high operands respectively.
1779   uint64_t Masks[] = { KnownZero[0].getZExtValue(),
1780                        KnownZero[1].getZExtValue() };
1781   unsigned High, Low;
1782   if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
1783     High = 1, Low = 0;
1784   else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
1785     High = 0, Low = 1;
1786   else
1787     return Op;
1788
1789   SDValue LowOp = Ops[Low];
1790   SDValue HighOp = Ops[High];
1791
1792   // If the high part is a constant, we're better off using IILH.
1793   if (HighOp.getOpcode() == ISD::Constant)
1794     return Op;
1795
1796   // If the low part is a constant that is outside the range of LHI,
1797   // then we're better off using IILF.
1798   if (LowOp.getOpcode() == ISD::Constant) {
1799     int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
1800     if (!isInt<16>(Value))
1801       return Op;
1802   }
1803
1804   // Check whether the high part is an AND that doesn't change the
1805   // high 32 bits and just masks out low bits.  We can skip it if so.
1806   if (HighOp.getOpcode() == ISD::AND &&
1807       HighOp.getOperand(1).getOpcode() == ISD::Constant) {
1808     ConstantSDNode *MaskNode = cast<ConstantSDNode>(HighOp.getOperand(1));
1809     uint64_t Mask = MaskNode->getZExtValue() | Masks[High];
1810     if ((Mask >> 32) == 0xffffffff)
1811       HighOp = HighOp.getOperand(0);
1812   }
1813
1814   // Take advantage of the fact that all GR32 operations only change the
1815   // low 32 bits by truncating Low to an i32 and inserting it directly
1816   // using a subreg.  The interesting cases are those where the truncation
1817   // can be folded.
1818   SDLoc DL(Op);
1819   SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
1820   SDValue SubReg32 = DAG.getTargetConstant(SystemZ::subreg_32bit, MVT::i64);
1821   SDNode *Result = DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
1822                                       MVT::i64, HighOp, Low32, SubReg32);
1823   return SDValue(Result, 0);
1824 }
1825
1826 // Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation.  Lower the first
1827 // two into the fullword ATOMIC_LOADW_* operation given by Opcode.
1828 SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
1829                                                 SelectionDAG &DAG,
1830                                                 unsigned Opcode) const {
1831   AtomicSDNode *Node = cast<AtomicSDNode>(Op.getNode());
1832
1833   // 32-bit operations need no code outside the main loop.
1834   EVT NarrowVT = Node->getMemoryVT();
1835   EVT WideVT = MVT::i32;
1836   if (NarrowVT == WideVT)
1837     return Op;
1838
1839   int64_t BitSize = NarrowVT.getSizeInBits();
1840   SDValue ChainIn = Node->getChain();
1841   SDValue Addr = Node->getBasePtr();
1842   SDValue Src2 = Node->getVal();
1843   MachineMemOperand *MMO = Node->getMemOperand();
1844   SDLoc DL(Node);
1845   EVT PtrVT = Addr.getValueType();
1846
1847   // Convert atomic subtracts of constants into additions.
1848   if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
1849     if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Src2)) {
1850       Opcode = SystemZISD::ATOMIC_LOADW_ADD;
1851       Src2 = DAG.getConstant(-Const->getSExtValue(), Src2.getValueType());
1852     }
1853
1854   // Get the address of the containing word.
1855   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
1856                                     DAG.getConstant(-4, PtrVT));
1857
1858   // Get the number of bits that the word must be rotated left in order
1859   // to bring the field to the top bits of a GR32.
1860   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
1861                                  DAG.getConstant(3, PtrVT));
1862   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
1863
1864   // Get the complementing shift amount, for rotating a field in the top
1865   // bits back to its proper position.
1866   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
1867                                     DAG.getConstant(0, WideVT), BitShift);
1868
1869   // Extend the source operand to 32 bits and prepare it for the inner loop.
1870   // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
1871   // operations require the source to be shifted in advance.  (This shift
1872   // can be folded if the source is constant.)  For AND and NAND, the lower
1873   // bits must be set, while for other opcodes they should be left clear.
1874   if (Opcode != SystemZISD::ATOMIC_SWAPW)
1875     Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
1876                        DAG.getConstant(32 - BitSize, WideVT));
1877   if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
1878       Opcode == SystemZISD::ATOMIC_LOADW_NAND)
1879     Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
1880                        DAG.getConstant(uint32_t(-1) >> BitSize, WideVT));
1881
1882   // Construct the ATOMIC_LOADW_* node.
1883   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
1884   SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
1885                     DAG.getConstant(BitSize, WideVT) };
1886   SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
1887                                              array_lengthof(Ops),
1888                                              NarrowVT, MMO);
1889
1890   // Rotate the result of the final CS so that the field is in the lower
1891   // bits of a GR32, then truncate it.
1892   SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
1893                                     DAG.getConstant(BitSize, WideVT));
1894   SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
1895
1896   SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
1897   return DAG.getMergeValues(RetOps, 2, DL);
1898 }
1899
1900 // Node is an 8- or 16-bit ATOMIC_CMP_SWAP operation.  Lower the first two
1901 // into a fullword ATOMIC_CMP_SWAPW operation.
1902 SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
1903                                                     SelectionDAG &DAG) const {
1904   AtomicSDNode *Node = cast<AtomicSDNode>(Op.getNode());
1905
1906   // We have native support for 32-bit compare and swap.
1907   EVT NarrowVT = Node->getMemoryVT();
1908   EVT WideVT = MVT::i32;
1909   if (NarrowVT == WideVT)
1910     return Op;
1911
1912   int64_t BitSize = NarrowVT.getSizeInBits();
1913   SDValue ChainIn = Node->getOperand(0);
1914   SDValue Addr = Node->getOperand(1);
1915   SDValue CmpVal = Node->getOperand(2);
1916   SDValue SwapVal = Node->getOperand(3);
1917   MachineMemOperand *MMO = Node->getMemOperand();
1918   SDLoc DL(Node);
1919   EVT PtrVT = Addr.getValueType();
1920
1921   // Get the address of the containing word.
1922   SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
1923                                     DAG.getConstant(-4, PtrVT));
1924
1925   // Get the number of bits that the word must be rotated left in order
1926   // to bring the field to the top bits of a GR32.
1927   SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
1928                                  DAG.getConstant(3, PtrVT));
1929   BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
1930
1931   // Get the complementing shift amount, for rotating a field in the top
1932   // bits back to its proper position.
1933   SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
1934                                     DAG.getConstant(0, WideVT), BitShift);
1935
1936   // Construct the ATOMIC_CMP_SWAPW node.
1937   SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
1938   SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
1939                     NegBitShift, DAG.getConstant(BitSize, WideVT) };
1940   SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
1941                                              VTList, Ops, array_lengthof(Ops),
1942                                              NarrowVT, MMO);
1943   return AtomicOp;
1944 }
1945
1946 SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
1947                                               SelectionDAG &DAG) const {
1948   MachineFunction &MF = DAG.getMachineFunction();
1949   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
1950   return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
1951                             SystemZ::R15D, Op.getValueType());
1952 }
1953
1954 SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
1955                                                  SelectionDAG &DAG) const {
1956   MachineFunction &MF = DAG.getMachineFunction();
1957   MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
1958   return DAG.getCopyToReg(Op.getOperand(0), SDLoc(Op),
1959                           SystemZ::R15D, Op.getOperand(1));
1960 }
1961
1962 SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
1963                                              SelectionDAG &DAG) const {
1964   bool IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1965   if (!IsData)
1966     // Just preserve the chain.
1967     return Op.getOperand(0);
1968
1969   bool IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1970   unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
1971   MemIntrinsicSDNode *Node = cast<MemIntrinsicSDNode>(Op.getNode());
1972   SDValue Ops[] = {
1973     Op.getOperand(0),
1974     DAG.getConstant(Code, MVT::i32),
1975     Op.getOperand(1)
1976   };
1977   return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, SDLoc(Op),
1978                                  Node->getVTList(), Ops, array_lengthof(Ops),
1979                                  Node->getMemoryVT(), Node->getMemOperand());
1980 }
1981
1982 SDValue SystemZTargetLowering::LowerOperation(SDValue Op,
1983                                               SelectionDAG &DAG) const {
1984   switch (Op.getOpcode()) {
1985   case ISD::BR_CC:
1986     return lowerBR_CC(Op, DAG);
1987   case ISD::SELECT_CC:
1988     return lowerSELECT_CC(Op, DAG);
1989   case ISD::GlobalAddress:
1990     return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
1991   case ISD::GlobalTLSAddress:
1992     return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
1993   case ISD::BlockAddress:
1994     return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
1995   case ISD::JumpTable:
1996     return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
1997   case ISD::ConstantPool:
1998     return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
1999   case ISD::BITCAST:
2000     return lowerBITCAST(Op, DAG);
2001   case ISD::VASTART:
2002     return lowerVASTART(Op, DAG);
2003   case ISD::VACOPY:
2004     return lowerVACOPY(Op, DAG);
2005   case ISD::DYNAMIC_STACKALLOC:
2006     return lowerDYNAMIC_STACKALLOC(Op, DAG);
2007   case ISD::SMUL_LOHI:
2008     return lowerSMUL_LOHI(Op, DAG);
2009   case ISD::UMUL_LOHI:
2010     return lowerUMUL_LOHI(Op, DAG);
2011   case ISD::SDIVREM:
2012     return lowerSDIVREM(Op, DAG);
2013   case ISD::UDIVREM:
2014     return lowerUDIVREM(Op, DAG);
2015   case ISD::OR:
2016     return lowerOR(Op, DAG);
2017   case ISD::ATOMIC_SWAP:
2018     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_SWAPW);
2019   case ISD::ATOMIC_LOAD_ADD:
2020     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
2021   case ISD::ATOMIC_LOAD_SUB:
2022     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
2023   case ISD::ATOMIC_LOAD_AND:
2024     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
2025   case ISD::ATOMIC_LOAD_OR:
2026     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
2027   case ISD::ATOMIC_LOAD_XOR:
2028     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
2029   case ISD::ATOMIC_LOAD_NAND:
2030     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
2031   case ISD::ATOMIC_LOAD_MIN:
2032     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
2033   case ISD::ATOMIC_LOAD_MAX:
2034     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
2035   case ISD::ATOMIC_LOAD_UMIN:
2036     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
2037   case ISD::ATOMIC_LOAD_UMAX:
2038     return lowerATOMIC_LOAD(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
2039   case ISD::ATOMIC_CMP_SWAP:
2040     return lowerATOMIC_CMP_SWAP(Op, DAG);
2041   case ISD::STACKSAVE:
2042     return lowerSTACKSAVE(Op, DAG);
2043   case ISD::STACKRESTORE:
2044     return lowerSTACKRESTORE(Op, DAG);
2045   case ISD::PREFETCH:
2046     return lowerPREFETCH(Op, DAG);
2047   default:
2048     llvm_unreachable("Unexpected node to lower");
2049   }
2050 }
2051
2052 const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
2053 #define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME
2054   switch (Opcode) {
2055     OPCODE(RET_FLAG);
2056     OPCODE(CALL);
2057     OPCODE(SIBCALL);
2058     OPCODE(PCREL_WRAPPER);
2059     OPCODE(ICMP);
2060     OPCODE(FCMP);
2061     OPCODE(TM);
2062     OPCODE(BR_CCMASK);
2063     OPCODE(SELECT_CCMASK);
2064     OPCODE(ADJDYNALLOC);
2065     OPCODE(EXTRACT_ACCESS);
2066     OPCODE(UMUL_LOHI64);
2067     OPCODE(SDIVREM64);
2068     OPCODE(UDIVREM32);
2069     OPCODE(UDIVREM64);
2070     OPCODE(MVC);
2071     OPCODE(MVC_LOOP);
2072     OPCODE(NC);
2073     OPCODE(NC_LOOP);
2074     OPCODE(OC);
2075     OPCODE(OC_LOOP);
2076     OPCODE(XC);
2077     OPCODE(XC_LOOP);
2078     OPCODE(CLC);
2079     OPCODE(CLC_LOOP);
2080     OPCODE(STRCMP);
2081     OPCODE(STPCPY);
2082     OPCODE(SEARCH_STRING);
2083     OPCODE(IPM);
2084     OPCODE(ATOMIC_SWAPW);
2085     OPCODE(ATOMIC_LOADW_ADD);
2086     OPCODE(ATOMIC_LOADW_SUB);
2087     OPCODE(ATOMIC_LOADW_AND);
2088     OPCODE(ATOMIC_LOADW_OR);
2089     OPCODE(ATOMIC_LOADW_XOR);
2090     OPCODE(ATOMIC_LOADW_NAND);
2091     OPCODE(ATOMIC_LOADW_MIN);
2092     OPCODE(ATOMIC_LOADW_MAX);
2093     OPCODE(ATOMIC_LOADW_UMIN);
2094     OPCODE(ATOMIC_LOADW_UMAX);
2095     OPCODE(ATOMIC_CMP_SWAPW);
2096     OPCODE(PREFETCH);
2097   }
2098   return NULL;
2099 #undef OPCODE
2100 }
2101
2102 //===----------------------------------------------------------------------===//
2103 // Custom insertion
2104 //===----------------------------------------------------------------------===//
2105
2106 // Create a new basic block after MBB.
2107 static MachineBasicBlock *emitBlockAfter(MachineBasicBlock *MBB) {
2108   MachineFunction &MF = *MBB->getParent();
2109   MachineBasicBlock *NewMBB = MF.CreateMachineBasicBlock(MBB->getBasicBlock());
2110   MF.insert(llvm::next(MachineFunction::iterator(MBB)), NewMBB);
2111   return NewMBB;
2112 }
2113
2114 // Split MBB after MI and return the new block (the one that contains
2115 // instructions after MI).
2116 static MachineBasicBlock *splitBlockAfter(MachineInstr *MI,
2117                                           MachineBasicBlock *MBB) {
2118   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
2119   NewMBB->splice(NewMBB->begin(), MBB,
2120                  llvm::next(MachineBasicBlock::iterator(MI)),
2121                  MBB->end());
2122   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
2123   return NewMBB;
2124 }
2125
2126 // Split MBB before MI and return the new block (the one that contains MI).
2127 static MachineBasicBlock *splitBlockBefore(MachineInstr *MI,
2128                                            MachineBasicBlock *MBB) {
2129   MachineBasicBlock *NewMBB = emitBlockAfter(MBB);
2130   NewMBB->splice(NewMBB->begin(), MBB, MI, MBB->end());
2131   NewMBB->transferSuccessorsAndUpdatePHIs(MBB);
2132   return NewMBB;
2133 }
2134
2135 // Force base value Base into a register before MI.  Return the register.
2136 static unsigned forceReg(MachineInstr *MI, MachineOperand &Base,
2137                          const SystemZInstrInfo *TII) {
2138   if (Base.isReg())
2139     return Base.getReg();
2140
2141   MachineBasicBlock *MBB = MI->getParent();
2142   MachineFunction &MF = *MBB->getParent();
2143   MachineRegisterInfo &MRI = MF.getRegInfo();
2144
2145   unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
2146   BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LA), Reg)
2147     .addOperand(Base).addImm(0).addReg(0);
2148   return Reg;
2149 }
2150
2151 // Implement EmitInstrWithCustomInserter for pseudo Select* instruction MI.
2152 MachineBasicBlock *
2153 SystemZTargetLowering::emitSelect(MachineInstr *MI,
2154                                   MachineBasicBlock *MBB) const {
2155   const SystemZInstrInfo *TII = TM.getInstrInfo();
2156
2157   unsigned DestReg  = MI->getOperand(0).getReg();
2158   unsigned TrueReg  = MI->getOperand(1).getReg();
2159   unsigned FalseReg = MI->getOperand(2).getReg();
2160   unsigned CCValid  = MI->getOperand(3).getImm();
2161   unsigned CCMask   = MI->getOperand(4).getImm();
2162   DebugLoc DL       = MI->getDebugLoc();
2163
2164   MachineBasicBlock *StartMBB = MBB;
2165   MachineBasicBlock *JoinMBB  = splitBlockBefore(MI, MBB);
2166   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
2167
2168   //  StartMBB:
2169   //   BRC CCMask, JoinMBB
2170   //   # fallthrough to FalseMBB
2171   MBB = StartMBB;
2172   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2173     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
2174   MBB->addSuccessor(JoinMBB);
2175   MBB->addSuccessor(FalseMBB);
2176
2177   //  FalseMBB:
2178   //   # fallthrough to JoinMBB
2179   MBB = FalseMBB;
2180   MBB->addSuccessor(JoinMBB);
2181
2182   //  JoinMBB:
2183   //   %Result = phi [ %FalseReg, FalseMBB ], [ %TrueReg, StartMBB ]
2184   //  ...
2185   MBB = JoinMBB;
2186   BuildMI(*MBB, MI, DL, TII->get(SystemZ::PHI), DestReg)
2187     .addReg(TrueReg).addMBB(StartMBB)
2188     .addReg(FalseReg).addMBB(FalseMBB);
2189
2190   MI->eraseFromParent();
2191   return JoinMBB;
2192 }
2193
2194 // Implement EmitInstrWithCustomInserter for pseudo CondStore* instruction MI.
2195 // StoreOpcode is the store to use and Invert says whether the store should
2196 // happen when the condition is false rather than true.  If a STORE ON
2197 // CONDITION is available, STOCOpcode is its opcode, otherwise it is 0.
2198 MachineBasicBlock *
2199 SystemZTargetLowering::emitCondStore(MachineInstr *MI,
2200                                      MachineBasicBlock *MBB,
2201                                      unsigned StoreOpcode, unsigned STOCOpcode,
2202                                      bool Invert) const {
2203   const SystemZInstrInfo *TII = TM.getInstrInfo();
2204
2205   unsigned SrcReg     = MI->getOperand(0).getReg();
2206   MachineOperand Base = MI->getOperand(1);
2207   int64_t Disp        = MI->getOperand(2).getImm();
2208   unsigned IndexReg   = MI->getOperand(3).getReg();
2209   unsigned CCValid    = MI->getOperand(4).getImm();
2210   unsigned CCMask     = MI->getOperand(5).getImm();
2211   DebugLoc DL         = MI->getDebugLoc();
2212
2213   StoreOpcode = TII->getOpcodeForOffset(StoreOpcode, Disp);
2214
2215   // Use STOCOpcode if possible.  We could use different store patterns in
2216   // order to avoid matching the index register, but the performance trade-offs
2217   // might be more complicated in that case.
2218   if (STOCOpcode && !IndexReg && TM.getSubtargetImpl()->hasLoadStoreOnCond()) {
2219     if (Invert)
2220       CCMask ^= CCValid;
2221     BuildMI(*MBB, MI, DL, TII->get(STOCOpcode))
2222       .addReg(SrcReg).addOperand(Base).addImm(Disp)
2223       .addImm(CCValid).addImm(CCMask);
2224     MI->eraseFromParent();
2225     return MBB;
2226   }
2227
2228   // Get the condition needed to branch around the store.
2229   if (!Invert)
2230     CCMask ^= CCValid;
2231
2232   MachineBasicBlock *StartMBB = MBB;
2233   MachineBasicBlock *JoinMBB  = splitBlockBefore(MI, MBB);
2234   MachineBasicBlock *FalseMBB = emitBlockAfter(StartMBB);
2235
2236   //  StartMBB:
2237   //   BRC CCMask, JoinMBB
2238   //   # fallthrough to FalseMBB
2239   MBB = StartMBB;
2240   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2241     .addImm(CCValid).addImm(CCMask).addMBB(JoinMBB);
2242   MBB->addSuccessor(JoinMBB);
2243   MBB->addSuccessor(FalseMBB);
2244
2245   //  FalseMBB:
2246   //   store %SrcReg, %Disp(%Index,%Base)
2247   //   # fallthrough to JoinMBB
2248   MBB = FalseMBB;
2249   BuildMI(MBB, DL, TII->get(StoreOpcode))
2250     .addReg(SrcReg).addOperand(Base).addImm(Disp).addReg(IndexReg);
2251   MBB->addSuccessor(JoinMBB);
2252
2253   MI->eraseFromParent();
2254   return JoinMBB;
2255 }
2256
2257 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_LOAD{,W}_*
2258 // or ATOMIC_SWAP{,W} instruction MI.  BinOpcode is the instruction that
2259 // performs the binary operation elided by "*", or 0 for ATOMIC_SWAP{,W}.
2260 // BitSize is the width of the field in bits, or 0 if this is a partword
2261 // ATOMIC_LOADW_* or ATOMIC_SWAPW instruction, in which case the bitsize
2262 // is one of the operands.  Invert says whether the field should be
2263 // inverted after performing BinOpcode (e.g. for NAND).
2264 MachineBasicBlock *
2265 SystemZTargetLowering::emitAtomicLoadBinary(MachineInstr *MI,
2266                                             MachineBasicBlock *MBB,
2267                                             unsigned BinOpcode,
2268                                             unsigned BitSize,
2269                                             bool Invert) const {
2270   const SystemZInstrInfo *TII = TM.getInstrInfo();
2271   MachineFunction &MF = *MBB->getParent();
2272   MachineRegisterInfo &MRI = MF.getRegInfo();
2273   bool IsSubWord = (BitSize < 32);
2274
2275   // Extract the operands.  Base can be a register or a frame index.
2276   // Src2 can be a register or immediate.
2277   unsigned Dest        = MI->getOperand(0).getReg();
2278   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
2279   int64_t Disp         = MI->getOperand(2).getImm();
2280   MachineOperand Src2  = earlyUseOperand(MI->getOperand(3));
2281   unsigned BitShift    = (IsSubWord ? MI->getOperand(4).getReg() : 0);
2282   unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
2283   DebugLoc DL          = MI->getDebugLoc();
2284   if (IsSubWord)
2285     BitSize = MI->getOperand(6).getImm();
2286
2287   // Subword operations use 32-bit registers.
2288   const TargetRegisterClass *RC = (BitSize <= 32 ?
2289                                    &SystemZ::GR32BitRegClass :
2290                                    &SystemZ::GR64BitRegClass);
2291   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
2292   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
2293
2294   // Get the right opcodes for the displacement.
2295   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
2296   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
2297   assert(LOpcode && CSOpcode && "Displacement out of range");
2298
2299   // Create virtual registers for temporary results.
2300   unsigned OrigVal       = MRI.createVirtualRegister(RC);
2301   unsigned OldVal        = MRI.createVirtualRegister(RC);
2302   unsigned NewVal        = (BinOpcode || IsSubWord ?
2303                             MRI.createVirtualRegister(RC) : Src2.getReg());
2304   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
2305   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
2306
2307   // Insert a basic block for the main loop.
2308   MachineBasicBlock *StartMBB = MBB;
2309   MachineBasicBlock *DoneMBB  = splitBlockBefore(MI, MBB);
2310   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
2311
2312   //  StartMBB:
2313   //   ...
2314   //   %OrigVal = L Disp(%Base)
2315   //   # fall through to LoopMMB
2316   MBB = StartMBB;
2317   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
2318     .addOperand(Base).addImm(Disp).addReg(0);
2319   MBB->addSuccessor(LoopMBB);
2320
2321   //  LoopMBB:
2322   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, LoopMBB ]
2323   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
2324   //   %RotatedNewVal = OP %RotatedOldVal, %Src2
2325   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
2326   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
2327   //   JNE LoopMBB
2328   //   # fall through to DoneMMB
2329   MBB = LoopMBB;
2330   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
2331     .addReg(OrigVal).addMBB(StartMBB)
2332     .addReg(Dest).addMBB(LoopMBB);
2333   if (IsSubWord)
2334     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
2335       .addReg(OldVal).addReg(BitShift).addImm(0);
2336   if (Invert) {
2337     // Perform the operation normally and then invert every bit of the field.
2338     unsigned Tmp = MRI.createVirtualRegister(RC);
2339     BuildMI(MBB, DL, TII->get(BinOpcode), Tmp)
2340       .addReg(RotatedOldVal).addOperand(Src2);
2341     if (BitSize < 32)
2342       // XILF with the upper BitSize bits set.
2343       BuildMI(MBB, DL, TII->get(SystemZ::XILF32), RotatedNewVal)
2344         .addReg(Tmp).addImm(uint32_t(~0 << (32 - BitSize)));
2345     else if (BitSize == 32)
2346       // XILF with every bit set.
2347       BuildMI(MBB, DL, TII->get(SystemZ::XILF32), RotatedNewVal)
2348         .addReg(Tmp).addImm(~uint32_t(0));
2349     else {
2350       // Use LCGR and add -1 to the result, which is more compact than
2351       // an XILF, XILH pair.
2352       unsigned Tmp2 = MRI.createVirtualRegister(RC);
2353       BuildMI(MBB, DL, TII->get(SystemZ::LCGR), Tmp2).addReg(Tmp);
2354       BuildMI(MBB, DL, TII->get(SystemZ::AGHI), RotatedNewVal)
2355         .addReg(Tmp2).addImm(-1);
2356     }
2357   } else if (BinOpcode)
2358     // A simply binary operation.
2359     BuildMI(MBB, DL, TII->get(BinOpcode), RotatedNewVal)
2360       .addReg(RotatedOldVal).addOperand(Src2);
2361   else if (IsSubWord)
2362     // Use RISBG to rotate Src2 into position and use it to replace the
2363     // field in RotatedOldVal.
2364     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedNewVal)
2365       .addReg(RotatedOldVal).addReg(Src2.getReg())
2366       .addImm(32).addImm(31 + BitSize).addImm(32 - BitSize);
2367   if (IsSubWord)
2368     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
2369       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
2370   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
2371     .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
2372   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2373     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
2374   MBB->addSuccessor(LoopMBB);
2375   MBB->addSuccessor(DoneMBB);
2376
2377   MI->eraseFromParent();
2378   return DoneMBB;
2379 }
2380
2381 // Implement EmitInstrWithCustomInserter for pseudo
2382 // ATOMIC_LOAD{,W}_{,U}{MIN,MAX} instruction MI.  CompareOpcode is the
2383 // instruction that should be used to compare the current field with the
2384 // minimum or maximum value.  KeepOldMask is the BRC condition-code mask
2385 // for when the current field should be kept.  BitSize is the width of
2386 // the field in bits, or 0 if this is a partword ATOMIC_LOADW_* instruction.
2387 MachineBasicBlock *
2388 SystemZTargetLowering::emitAtomicLoadMinMax(MachineInstr *MI,
2389                                             MachineBasicBlock *MBB,
2390                                             unsigned CompareOpcode,
2391                                             unsigned KeepOldMask,
2392                                             unsigned BitSize) const {
2393   const SystemZInstrInfo *TII = TM.getInstrInfo();
2394   MachineFunction &MF = *MBB->getParent();
2395   MachineRegisterInfo &MRI = MF.getRegInfo();
2396   bool IsSubWord = (BitSize < 32);
2397
2398   // Extract the operands.  Base can be a register or a frame index.
2399   unsigned Dest        = MI->getOperand(0).getReg();
2400   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
2401   int64_t  Disp        = MI->getOperand(2).getImm();
2402   unsigned Src2        = MI->getOperand(3).getReg();
2403   unsigned BitShift    = (IsSubWord ? MI->getOperand(4).getReg() : 0);
2404   unsigned NegBitShift = (IsSubWord ? MI->getOperand(5).getReg() : 0);
2405   DebugLoc DL          = MI->getDebugLoc();
2406   if (IsSubWord)
2407     BitSize = MI->getOperand(6).getImm();
2408
2409   // Subword operations use 32-bit registers.
2410   const TargetRegisterClass *RC = (BitSize <= 32 ?
2411                                    &SystemZ::GR32BitRegClass :
2412                                    &SystemZ::GR64BitRegClass);
2413   unsigned LOpcode  = BitSize <= 32 ? SystemZ::L  : SystemZ::LG;
2414   unsigned CSOpcode = BitSize <= 32 ? SystemZ::CS : SystemZ::CSG;
2415
2416   // Get the right opcodes for the displacement.
2417   LOpcode  = TII->getOpcodeForOffset(LOpcode,  Disp);
2418   CSOpcode = TII->getOpcodeForOffset(CSOpcode, Disp);
2419   assert(LOpcode && CSOpcode && "Displacement out of range");
2420
2421   // Create virtual registers for temporary results.
2422   unsigned OrigVal       = MRI.createVirtualRegister(RC);
2423   unsigned OldVal        = MRI.createVirtualRegister(RC);
2424   unsigned NewVal        = MRI.createVirtualRegister(RC);
2425   unsigned RotatedOldVal = (IsSubWord ? MRI.createVirtualRegister(RC) : OldVal);
2426   unsigned RotatedAltVal = (IsSubWord ? MRI.createVirtualRegister(RC) : Src2);
2427   unsigned RotatedNewVal = (IsSubWord ? MRI.createVirtualRegister(RC) : NewVal);
2428
2429   // Insert 3 basic blocks for the loop.
2430   MachineBasicBlock *StartMBB  = MBB;
2431   MachineBasicBlock *DoneMBB   = splitBlockBefore(MI, MBB);
2432   MachineBasicBlock *LoopMBB   = emitBlockAfter(StartMBB);
2433   MachineBasicBlock *UseAltMBB = emitBlockAfter(LoopMBB);
2434   MachineBasicBlock *UpdateMBB = emitBlockAfter(UseAltMBB);
2435
2436   //  StartMBB:
2437   //   ...
2438   //   %OrigVal     = L Disp(%Base)
2439   //   # fall through to LoopMMB
2440   MBB = StartMBB;
2441   BuildMI(MBB, DL, TII->get(LOpcode), OrigVal)
2442     .addOperand(Base).addImm(Disp).addReg(0);
2443   MBB->addSuccessor(LoopMBB);
2444
2445   //  LoopMBB:
2446   //   %OldVal        = phi [ %OrigVal, StartMBB ], [ %Dest, UpdateMBB ]
2447   //   %RotatedOldVal = RLL %OldVal, 0(%BitShift)
2448   //   CompareOpcode %RotatedOldVal, %Src2
2449   //   BRC KeepOldMask, UpdateMBB
2450   MBB = LoopMBB;
2451   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
2452     .addReg(OrigVal).addMBB(StartMBB)
2453     .addReg(Dest).addMBB(UpdateMBB);
2454   if (IsSubWord)
2455     BuildMI(MBB, DL, TII->get(SystemZ::RLL), RotatedOldVal)
2456       .addReg(OldVal).addReg(BitShift).addImm(0);
2457   BuildMI(MBB, DL, TII->get(CompareOpcode))
2458     .addReg(RotatedOldVal).addReg(Src2);
2459   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2460     .addImm(SystemZ::CCMASK_ICMP).addImm(KeepOldMask).addMBB(UpdateMBB);
2461   MBB->addSuccessor(UpdateMBB);
2462   MBB->addSuccessor(UseAltMBB);
2463
2464   //  UseAltMBB:
2465   //   %RotatedAltVal = RISBG %RotatedOldVal, %Src2, 32, 31 + BitSize, 0
2466   //   # fall through to UpdateMMB
2467   MBB = UseAltMBB;
2468   if (IsSubWord)
2469     BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RotatedAltVal)
2470       .addReg(RotatedOldVal).addReg(Src2)
2471       .addImm(32).addImm(31 + BitSize).addImm(0);
2472   MBB->addSuccessor(UpdateMBB);
2473
2474   //  UpdateMBB:
2475   //   %RotatedNewVal = PHI [ %RotatedOldVal, LoopMBB ],
2476   //                        [ %RotatedAltVal, UseAltMBB ]
2477   //   %NewVal        = RLL %RotatedNewVal, 0(%NegBitShift)
2478   //   %Dest          = CS %OldVal, %NewVal, Disp(%Base)
2479   //   JNE LoopMBB
2480   //   # fall through to DoneMMB
2481   MBB = UpdateMBB;
2482   BuildMI(MBB, DL, TII->get(SystemZ::PHI), RotatedNewVal)
2483     .addReg(RotatedOldVal).addMBB(LoopMBB)
2484     .addReg(RotatedAltVal).addMBB(UseAltMBB);
2485   if (IsSubWord)
2486     BuildMI(MBB, DL, TII->get(SystemZ::RLL), NewVal)
2487       .addReg(RotatedNewVal).addReg(NegBitShift).addImm(0);
2488   BuildMI(MBB, DL, TII->get(CSOpcode), Dest)
2489     .addReg(OldVal).addReg(NewVal).addOperand(Base).addImm(Disp);
2490   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2491     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
2492   MBB->addSuccessor(LoopMBB);
2493   MBB->addSuccessor(DoneMBB);
2494
2495   MI->eraseFromParent();
2496   return DoneMBB;
2497 }
2498
2499 // Implement EmitInstrWithCustomInserter for pseudo ATOMIC_CMP_SWAPW
2500 // instruction MI.
2501 MachineBasicBlock *
2502 SystemZTargetLowering::emitAtomicCmpSwapW(MachineInstr *MI,
2503                                           MachineBasicBlock *MBB) const {
2504   const SystemZInstrInfo *TII = TM.getInstrInfo();
2505   MachineFunction &MF = *MBB->getParent();
2506   MachineRegisterInfo &MRI = MF.getRegInfo();
2507
2508   // Extract the operands.  Base can be a register or a frame index.
2509   unsigned Dest        = MI->getOperand(0).getReg();
2510   MachineOperand Base  = earlyUseOperand(MI->getOperand(1));
2511   int64_t  Disp        = MI->getOperand(2).getImm();
2512   unsigned OrigCmpVal  = MI->getOperand(3).getReg();
2513   unsigned OrigSwapVal = MI->getOperand(4).getReg();
2514   unsigned BitShift    = MI->getOperand(5).getReg();
2515   unsigned NegBitShift = MI->getOperand(6).getReg();
2516   int64_t  BitSize     = MI->getOperand(7).getImm();
2517   DebugLoc DL          = MI->getDebugLoc();
2518
2519   const TargetRegisterClass *RC = &SystemZ::GR32BitRegClass;
2520
2521   // Get the right opcodes for the displacement.
2522   unsigned LOpcode  = TII->getOpcodeForOffset(SystemZ::L,  Disp);
2523   unsigned CSOpcode = TII->getOpcodeForOffset(SystemZ::CS, Disp);
2524   assert(LOpcode && CSOpcode && "Displacement out of range");
2525
2526   // Create virtual registers for temporary results.
2527   unsigned OrigOldVal   = MRI.createVirtualRegister(RC);
2528   unsigned OldVal       = MRI.createVirtualRegister(RC);
2529   unsigned CmpVal       = MRI.createVirtualRegister(RC);
2530   unsigned SwapVal      = MRI.createVirtualRegister(RC);
2531   unsigned StoreVal     = MRI.createVirtualRegister(RC);
2532   unsigned RetryOldVal  = MRI.createVirtualRegister(RC);
2533   unsigned RetryCmpVal  = MRI.createVirtualRegister(RC);
2534   unsigned RetrySwapVal = MRI.createVirtualRegister(RC);
2535
2536   // Insert 2 basic blocks for the loop.
2537   MachineBasicBlock *StartMBB = MBB;
2538   MachineBasicBlock *DoneMBB  = splitBlockBefore(MI, MBB);
2539   MachineBasicBlock *LoopMBB  = emitBlockAfter(StartMBB);
2540   MachineBasicBlock *SetMBB   = emitBlockAfter(LoopMBB);
2541
2542   //  StartMBB:
2543   //   ...
2544   //   %OrigOldVal     = L Disp(%Base)
2545   //   # fall through to LoopMMB
2546   MBB = StartMBB;
2547   BuildMI(MBB, DL, TII->get(LOpcode), OrigOldVal)
2548     .addOperand(Base).addImm(Disp).addReg(0);
2549   MBB->addSuccessor(LoopMBB);
2550
2551   //  LoopMBB:
2552   //   %OldVal        = phi [ %OrigOldVal, EntryBB ], [ %RetryOldVal, SetMBB ]
2553   //   %CmpVal        = phi [ %OrigCmpVal, EntryBB ], [ %RetryCmpVal, SetMBB ]
2554   //   %SwapVal       = phi [ %OrigSwapVal, EntryBB ], [ %RetrySwapVal, SetMBB ]
2555   //   %Dest          = RLL %OldVal, BitSize(%BitShift)
2556   //                      ^^ The low BitSize bits contain the field
2557   //                         of interest.
2558   //   %RetryCmpVal   = RISBG32 %CmpVal, %Dest, 32, 63-BitSize, 0
2559   //                      ^^ Replace the upper 32-BitSize bits of the
2560   //                         comparison value with those that we loaded,
2561   //                         so that we can use a full word comparison.
2562   //   CR %Dest, %RetryCmpVal
2563   //   JNE DoneMBB
2564   //   # Fall through to SetMBB
2565   MBB = LoopMBB;
2566   BuildMI(MBB, DL, TII->get(SystemZ::PHI), OldVal)
2567     .addReg(OrigOldVal).addMBB(StartMBB)
2568     .addReg(RetryOldVal).addMBB(SetMBB);
2569   BuildMI(MBB, DL, TII->get(SystemZ::PHI), CmpVal)
2570     .addReg(OrigCmpVal).addMBB(StartMBB)
2571     .addReg(RetryCmpVal).addMBB(SetMBB);
2572   BuildMI(MBB, DL, TII->get(SystemZ::PHI), SwapVal)
2573     .addReg(OrigSwapVal).addMBB(StartMBB)
2574     .addReg(RetrySwapVal).addMBB(SetMBB);
2575   BuildMI(MBB, DL, TII->get(SystemZ::RLL), Dest)
2576     .addReg(OldVal).addReg(BitShift).addImm(BitSize);
2577   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetryCmpVal)
2578     .addReg(CmpVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
2579   BuildMI(MBB, DL, TII->get(SystemZ::CR))
2580     .addReg(Dest).addReg(RetryCmpVal);
2581   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2582     .addImm(SystemZ::CCMASK_ICMP)
2583     .addImm(SystemZ::CCMASK_CMP_NE).addMBB(DoneMBB);
2584   MBB->addSuccessor(DoneMBB);
2585   MBB->addSuccessor(SetMBB);
2586
2587   //  SetMBB:
2588   //   %RetrySwapVal = RISBG32 %SwapVal, %Dest, 32, 63-BitSize, 0
2589   //                      ^^ Replace the upper 32-BitSize bits of the new
2590   //                         value with those that we loaded.
2591   //   %StoreVal    = RLL %RetrySwapVal, -BitSize(%NegBitShift)
2592   //                      ^^ Rotate the new field to its proper position.
2593   //   %RetryOldVal = CS %Dest, %StoreVal, Disp(%Base)
2594   //   JNE LoopMBB
2595   //   # fall through to ExitMMB
2596   MBB = SetMBB;
2597   BuildMI(MBB, DL, TII->get(SystemZ::RISBG32), RetrySwapVal)
2598     .addReg(SwapVal).addReg(Dest).addImm(32).addImm(63 - BitSize).addImm(0);
2599   BuildMI(MBB, DL, TII->get(SystemZ::RLL), StoreVal)
2600     .addReg(RetrySwapVal).addReg(NegBitShift).addImm(-BitSize);
2601   BuildMI(MBB, DL, TII->get(CSOpcode), RetryOldVal)
2602     .addReg(OldVal).addReg(StoreVal).addOperand(Base).addImm(Disp);
2603   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2604     .addImm(SystemZ::CCMASK_CS).addImm(SystemZ::CCMASK_CS_NE).addMBB(LoopMBB);
2605   MBB->addSuccessor(LoopMBB);
2606   MBB->addSuccessor(DoneMBB);
2607
2608   MI->eraseFromParent();
2609   return DoneMBB;
2610 }
2611
2612 // Emit an extension from a GR32 or GR64 to a GR128.  ClearEven is true
2613 // if the high register of the GR128 value must be cleared or false if
2614 // it's "don't care".  SubReg is subreg_odd32 when extending a GR32
2615 // and subreg_odd when extending a GR64.
2616 MachineBasicBlock *
2617 SystemZTargetLowering::emitExt128(MachineInstr *MI,
2618                                   MachineBasicBlock *MBB,
2619                                   bool ClearEven, unsigned SubReg) const {
2620   const SystemZInstrInfo *TII = TM.getInstrInfo();
2621   MachineFunction &MF = *MBB->getParent();
2622   MachineRegisterInfo &MRI = MF.getRegInfo();
2623   DebugLoc DL = MI->getDebugLoc();
2624
2625   unsigned Dest  = MI->getOperand(0).getReg();
2626   unsigned Src   = MI->getOperand(1).getReg();
2627   unsigned In128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
2628
2629   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::IMPLICIT_DEF), In128);
2630   if (ClearEven) {
2631     unsigned NewIn128 = MRI.createVirtualRegister(&SystemZ::GR128BitRegClass);
2632     unsigned Zero64   = MRI.createVirtualRegister(&SystemZ::GR64BitRegClass);
2633
2634     BuildMI(*MBB, MI, DL, TII->get(SystemZ::LLILL), Zero64)
2635       .addImm(0);
2636     BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewIn128)
2637       .addReg(In128).addReg(Zero64).addImm(SystemZ::subreg_high);
2638     In128 = NewIn128;
2639   }
2640   BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dest)
2641     .addReg(In128).addReg(Src).addImm(SubReg);
2642
2643   MI->eraseFromParent();
2644   return MBB;
2645 }
2646
2647 MachineBasicBlock *
2648 SystemZTargetLowering::emitMemMemWrapper(MachineInstr *MI,
2649                                          MachineBasicBlock *MBB,
2650                                          unsigned Opcode) const {
2651   const SystemZInstrInfo *TII = TM.getInstrInfo();
2652   MachineFunction &MF = *MBB->getParent();
2653   MachineRegisterInfo &MRI = MF.getRegInfo();
2654   DebugLoc DL = MI->getDebugLoc();
2655
2656   MachineOperand DestBase = earlyUseOperand(MI->getOperand(0));
2657   uint64_t       DestDisp = MI->getOperand(1).getImm();
2658   MachineOperand SrcBase  = earlyUseOperand(MI->getOperand(2));
2659   uint64_t       SrcDisp  = MI->getOperand(3).getImm();
2660   uint64_t       Length   = MI->getOperand(4).getImm();
2661
2662   // When generating more than one CLC, all but the last will need to
2663   // branch to the end when a difference is found.
2664   MachineBasicBlock *EndMBB = (Length > 256 && Opcode == SystemZ::CLC ?
2665                                splitBlockAfter(MI, MBB) : 0);
2666
2667   // Check for the loop form, in which operand 5 is the trip count.
2668   if (MI->getNumExplicitOperands() > 5) {
2669     bool HaveSingleBase = DestBase.isIdenticalTo(SrcBase);
2670
2671     uint64_t StartCountReg = MI->getOperand(5).getReg();
2672     uint64_t StartSrcReg   = forceReg(MI, SrcBase, TII);
2673     uint64_t StartDestReg  = (HaveSingleBase ? StartSrcReg :
2674                               forceReg(MI, DestBase, TII));
2675
2676     const TargetRegisterClass *RC = &SystemZ::ADDR64BitRegClass;
2677     uint64_t ThisSrcReg  = MRI.createVirtualRegister(RC);
2678     uint64_t ThisDestReg = (HaveSingleBase ? ThisSrcReg :
2679                             MRI.createVirtualRegister(RC));
2680     uint64_t NextSrcReg  = MRI.createVirtualRegister(RC);
2681     uint64_t NextDestReg = (HaveSingleBase ? NextSrcReg :
2682                             MRI.createVirtualRegister(RC));
2683
2684     RC = &SystemZ::GR64BitRegClass;
2685     uint64_t ThisCountReg = MRI.createVirtualRegister(RC);
2686     uint64_t NextCountReg = MRI.createVirtualRegister(RC);
2687
2688     MachineBasicBlock *StartMBB = MBB;
2689     MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
2690     MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
2691     MachineBasicBlock *NextMBB = (EndMBB ? emitBlockAfter(LoopMBB) : LoopMBB);
2692
2693     //  StartMBB:
2694     //   # fall through to LoopMMB
2695     MBB->addSuccessor(LoopMBB);
2696
2697     //  LoopMBB:
2698     //   %ThisDestReg = phi [ %StartDestReg, StartMBB ],
2699     //                      [ %NextDestReg, NextMBB ]
2700     //   %ThisSrcReg = phi [ %StartSrcReg, StartMBB ],
2701     //                     [ %NextSrcReg, NextMBB ]
2702     //   %ThisCountReg = phi [ %StartCountReg, StartMBB ],
2703     //                       [ %NextCountReg, NextMBB ]
2704     //   ( PFD 2, 768+DestDisp(%ThisDestReg) )
2705     //   Opcode DestDisp(256,%ThisDestReg), SrcDisp(%ThisSrcReg)
2706     //   ( JLH EndMBB )
2707     //
2708     // The prefetch is used only for MVC.  The JLH is used only for CLC.
2709     MBB = LoopMBB;
2710
2711     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisDestReg)
2712       .addReg(StartDestReg).addMBB(StartMBB)
2713       .addReg(NextDestReg).addMBB(NextMBB);
2714     if (!HaveSingleBase)
2715       BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisSrcReg)
2716         .addReg(StartSrcReg).addMBB(StartMBB)
2717         .addReg(NextSrcReg).addMBB(NextMBB);
2718     BuildMI(MBB, DL, TII->get(SystemZ::PHI), ThisCountReg)
2719       .addReg(StartCountReg).addMBB(StartMBB)
2720       .addReg(NextCountReg).addMBB(NextMBB);
2721     if (Opcode == SystemZ::MVC)
2722       BuildMI(MBB, DL, TII->get(SystemZ::PFD))
2723         .addImm(SystemZ::PFD_WRITE)
2724         .addReg(ThisDestReg).addImm(DestDisp + 768).addReg(0);
2725     BuildMI(MBB, DL, TII->get(Opcode))
2726       .addReg(ThisDestReg).addImm(DestDisp).addImm(256)
2727       .addReg(ThisSrcReg).addImm(SrcDisp);
2728     if (EndMBB) {
2729       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2730         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
2731         .addMBB(EndMBB);
2732       MBB->addSuccessor(EndMBB);
2733       MBB->addSuccessor(NextMBB);
2734     }
2735
2736     // NextMBB:
2737     //   %NextDestReg = LA 256(%ThisDestReg)
2738     //   %NextSrcReg = LA 256(%ThisSrcReg)
2739     //   %NextCountReg = AGHI %ThisCountReg, -1
2740     //   CGHI %NextCountReg, 0
2741     //   JLH LoopMBB
2742     //   # fall through to DoneMMB
2743     //
2744     // The AGHI, CGHI and JLH should be converted to BRCTG by later passes.
2745     MBB = NextMBB;
2746
2747     BuildMI(MBB, DL, TII->get(SystemZ::LA), NextDestReg)
2748       .addReg(ThisDestReg).addImm(256).addReg(0);
2749     if (!HaveSingleBase)
2750       BuildMI(MBB, DL, TII->get(SystemZ::LA), NextSrcReg)
2751         .addReg(ThisSrcReg).addImm(256).addReg(0);
2752     BuildMI(MBB, DL, TII->get(SystemZ::AGHI), NextCountReg)
2753       .addReg(ThisCountReg).addImm(-1);
2754     BuildMI(MBB, DL, TII->get(SystemZ::CGHI))
2755       .addReg(NextCountReg).addImm(0);
2756     BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2757       .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
2758       .addMBB(LoopMBB);
2759     MBB->addSuccessor(LoopMBB);
2760     MBB->addSuccessor(DoneMBB);
2761
2762     DestBase = MachineOperand::CreateReg(NextDestReg, false);
2763     SrcBase = MachineOperand::CreateReg(NextSrcReg, false);
2764     Length &= 255;
2765     MBB = DoneMBB;
2766   }
2767   // Handle any remaining bytes with straight-line code.
2768   while (Length > 0) {
2769     uint64_t ThisLength = std::min(Length, uint64_t(256));
2770     // The previous iteration might have created out-of-range displacements.
2771     // Apply them using LAY if so.
2772     if (!isUInt<12>(DestDisp)) {
2773       unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
2774       BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
2775         .addOperand(DestBase).addImm(DestDisp).addReg(0);
2776       DestBase = MachineOperand::CreateReg(Reg, false);
2777       DestDisp = 0;
2778     }
2779     if (!isUInt<12>(SrcDisp)) {
2780       unsigned Reg = MRI.createVirtualRegister(&SystemZ::ADDR64BitRegClass);
2781       BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(SystemZ::LAY), Reg)
2782         .addOperand(SrcBase).addImm(SrcDisp).addReg(0);
2783       SrcBase = MachineOperand::CreateReg(Reg, false);
2784       SrcDisp = 0;
2785     }
2786     BuildMI(*MBB, MI, DL, TII->get(Opcode))
2787       .addOperand(DestBase).addImm(DestDisp).addImm(ThisLength)
2788       .addOperand(SrcBase).addImm(SrcDisp);
2789     DestDisp += ThisLength;
2790     SrcDisp += ThisLength;
2791     Length -= ThisLength;
2792     // If there's another CLC to go, branch to the end if a difference
2793     // was found.
2794     if (EndMBB && Length > 0) {
2795       MachineBasicBlock *NextMBB = splitBlockBefore(MI, MBB);
2796       BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2797         .addImm(SystemZ::CCMASK_ICMP).addImm(SystemZ::CCMASK_CMP_NE)
2798         .addMBB(EndMBB);
2799       MBB->addSuccessor(EndMBB);
2800       MBB->addSuccessor(NextMBB);
2801       MBB = NextMBB;
2802     }
2803   }
2804   if (EndMBB) {
2805     MBB->addSuccessor(EndMBB);
2806     MBB = EndMBB;
2807     MBB->addLiveIn(SystemZ::CC);
2808   }
2809
2810   MI->eraseFromParent();
2811   return MBB;
2812 }
2813
2814 // Decompose string pseudo-instruction MI into a loop that continually performs
2815 // Opcode until CC != 3.
2816 MachineBasicBlock *
2817 SystemZTargetLowering::emitStringWrapper(MachineInstr *MI,
2818                                          MachineBasicBlock *MBB,
2819                                          unsigned Opcode) const {
2820   const SystemZInstrInfo *TII = TM.getInstrInfo();
2821   MachineFunction &MF = *MBB->getParent();
2822   MachineRegisterInfo &MRI = MF.getRegInfo();
2823   DebugLoc DL = MI->getDebugLoc();
2824
2825   uint64_t End1Reg   = MI->getOperand(0).getReg();
2826   uint64_t Start1Reg = MI->getOperand(1).getReg();
2827   uint64_t Start2Reg = MI->getOperand(2).getReg();
2828   uint64_t CharReg   = MI->getOperand(3).getReg();
2829
2830   const TargetRegisterClass *RC = &SystemZ::GR64BitRegClass;
2831   uint64_t This1Reg = MRI.createVirtualRegister(RC);
2832   uint64_t This2Reg = MRI.createVirtualRegister(RC);
2833   uint64_t End2Reg  = MRI.createVirtualRegister(RC);
2834
2835   MachineBasicBlock *StartMBB = MBB;
2836   MachineBasicBlock *DoneMBB = splitBlockBefore(MI, MBB);
2837   MachineBasicBlock *LoopMBB = emitBlockAfter(StartMBB);
2838
2839   //  StartMBB:
2840   //   # fall through to LoopMMB
2841   MBB->addSuccessor(LoopMBB);
2842
2843   //  LoopMBB:
2844   //   %This1Reg = phi [ %Start1Reg, StartMBB ], [ %End1Reg, LoopMBB ]
2845   //   %This2Reg = phi [ %Start2Reg, StartMBB ], [ %End2Reg, LoopMBB ]
2846   //   R0W = %CharReg
2847   //   %End1Reg, %End2Reg = CLST %This1Reg, %This2Reg -- uses R0W
2848   //   JO LoopMBB
2849   //   # fall through to DoneMMB
2850   //
2851   // The load of R0W can be hoisted by post-RA LICM.
2852   MBB = LoopMBB;
2853
2854   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This1Reg)
2855     .addReg(Start1Reg).addMBB(StartMBB)
2856     .addReg(End1Reg).addMBB(LoopMBB);
2857   BuildMI(MBB, DL, TII->get(SystemZ::PHI), This2Reg)
2858     .addReg(Start2Reg).addMBB(StartMBB)
2859     .addReg(End2Reg).addMBB(LoopMBB);
2860   BuildMI(MBB, DL, TII->get(TargetOpcode::COPY), SystemZ::R0W).addReg(CharReg);
2861   BuildMI(MBB, DL, TII->get(Opcode))
2862     .addReg(End1Reg, RegState::Define).addReg(End2Reg, RegState::Define)
2863     .addReg(This1Reg).addReg(This2Reg);
2864   BuildMI(MBB, DL, TII->get(SystemZ::BRC))
2865     .addImm(SystemZ::CCMASK_ANY).addImm(SystemZ::CCMASK_3).addMBB(LoopMBB);
2866   MBB->addSuccessor(LoopMBB);
2867   MBB->addSuccessor(DoneMBB);
2868
2869   DoneMBB->addLiveIn(SystemZ::CC);
2870
2871   MI->eraseFromParent();
2872   return DoneMBB;
2873 }
2874
2875 MachineBasicBlock *SystemZTargetLowering::
2876 EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *MBB) const {
2877   switch (MI->getOpcode()) {
2878   case SystemZ::Select32:
2879   case SystemZ::SelectF32:
2880   case SystemZ::Select64:
2881   case SystemZ::SelectF64:
2882   case SystemZ::SelectF128:
2883     return emitSelect(MI, MBB);
2884
2885   case SystemZ::CondStore8_32:
2886     return emitCondStore(MI, MBB, SystemZ::STC32, 0, false);
2887   case SystemZ::CondStore8_32Inv:
2888     return emitCondStore(MI, MBB, SystemZ::STC32, 0, true);
2889   case SystemZ::CondStore16_32:
2890     return emitCondStore(MI, MBB, SystemZ::STH32, 0, false);
2891   case SystemZ::CondStore16_32Inv:
2892     return emitCondStore(MI, MBB, SystemZ::STH32, 0, true);
2893   case SystemZ::CondStore32_32:
2894     return emitCondStore(MI, MBB, SystemZ::ST32, SystemZ::STOC32, false);
2895   case SystemZ::CondStore32_32Inv:
2896     return emitCondStore(MI, MBB, SystemZ::ST32, SystemZ::STOC32, true);
2897   case SystemZ::CondStore8:
2898     return emitCondStore(MI, MBB, SystemZ::STC, 0, false);
2899   case SystemZ::CondStore8Inv:
2900     return emitCondStore(MI, MBB, SystemZ::STC, 0, true);
2901   case SystemZ::CondStore16:
2902     return emitCondStore(MI, MBB, SystemZ::STH, 0, false);
2903   case SystemZ::CondStore16Inv:
2904     return emitCondStore(MI, MBB, SystemZ::STH, 0, true);
2905   case SystemZ::CondStore32:
2906     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, false);
2907   case SystemZ::CondStore32Inv:
2908     return emitCondStore(MI, MBB, SystemZ::ST, SystemZ::STOC, true);
2909   case SystemZ::CondStore64:
2910     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, false);
2911   case SystemZ::CondStore64Inv:
2912     return emitCondStore(MI, MBB, SystemZ::STG, SystemZ::STOCG, true);
2913   case SystemZ::CondStoreF32:
2914     return emitCondStore(MI, MBB, SystemZ::STE, 0, false);
2915   case SystemZ::CondStoreF32Inv:
2916     return emitCondStore(MI, MBB, SystemZ::STE, 0, true);
2917   case SystemZ::CondStoreF64:
2918     return emitCondStore(MI, MBB, SystemZ::STD, 0, false);
2919   case SystemZ::CondStoreF64Inv:
2920     return emitCondStore(MI, MBB, SystemZ::STD, 0, true);
2921
2922   case SystemZ::AEXT128_64:
2923     return emitExt128(MI, MBB, false, SystemZ::subreg_low);
2924   case SystemZ::ZEXT128_32:
2925     return emitExt128(MI, MBB, true, SystemZ::subreg_low32);
2926   case SystemZ::ZEXT128_64:
2927     return emitExt128(MI, MBB, true, SystemZ::subreg_low);
2928
2929   case SystemZ::ATOMIC_SWAPW:
2930     return emitAtomicLoadBinary(MI, MBB, 0, 0);
2931   case SystemZ::ATOMIC_SWAP_32:
2932     return emitAtomicLoadBinary(MI, MBB, 0, 32);
2933   case SystemZ::ATOMIC_SWAP_64:
2934     return emitAtomicLoadBinary(MI, MBB, 0, 64);
2935
2936   case SystemZ::ATOMIC_LOADW_AR:
2937     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 0);
2938   case SystemZ::ATOMIC_LOADW_AFI:
2939     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 0);
2940   case SystemZ::ATOMIC_LOAD_AR:
2941     return emitAtomicLoadBinary(MI, MBB, SystemZ::AR, 32);
2942   case SystemZ::ATOMIC_LOAD_AHI:
2943     return emitAtomicLoadBinary(MI, MBB, SystemZ::AHI, 32);
2944   case SystemZ::ATOMIC_LOAD_AFI:
2945     return emitAtomicLoadBinary(MI, MBB, SystemZ::AFI, 32);
2946   case SystemZ::ATOMIC_LOAD_AGR:
2947     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGR, 64);
2948   case SystemZ::ATOMIC_LOAD_AGHI:
2949     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGHI, 64);
2950   case SystemZ::ATOMIC_LOAD_AGFI:
2951     return emitAtomicLoadBinary(MI, MBB, SystemZ::AGFI, 64);
2952
2953   case SystemZ::ATOMIC_LOADW_SR:
2954     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 0);
2955   case SystemZ::ATOMIC_LOAD_SR:
2956     return emitAtomicLoadBinary(MI, MBB, SystemZ::SR, 32);
2957   case SystemZ::ATOMIC_LOAD_SGR:
2958     return emitAtomicLoadBinary(MI, MBB, SystemZ::SGR, 64);
2959
2960   case SystemZ::ATOMIC_LOADW_NR:
2961     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0);
2962   case SystemZ::ATOMIC_LOADW_NILH:
2963     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH32, 0);
2964   case SystemZ::ATOMIC_LOAD_NR:
2965     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32);
2966   case SystemZ::ATOMIC_LOAD_NILL32:
2967     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL32, 32);
2968   case SystemZ::ATOMIC_LOAD_NILH32:
2969     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH32, 32);
2970   case SystemZ::ATOMIC_LOAD_NILF32:
2971     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF32, 32);
2972   case SystemZ::ATOMIC_LOAD_NGR:
2973     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64);
2974   case SystemZ::ATOMIC_LOAD_NILL:
2975     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 64);
2976   case SystemZ::ATOMIC_LOAD_NILH:
2977     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 64);
2978   case SystemZ::ATOMIC_LOAD_NIHL:
2979     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL, 64);
2980   case SystemZ::ATOMIC_LOAD_NIHH:
2981     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH, 64);
2982   case SystemZ::ATOMIC_LOAD_NILF:
2983     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 64);
2984   case SystemZ::ATOMIC_LOAD_NIHF:
2985     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF, 64);
2986
2987   case SystemZ::ATOMIC_LOADW_OR:
2988     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 0);
2989   case SystemZ::ATOMIC_LOADW_OILH:
2990     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH32, 0);
2991   case SystemZ::ATOMIC_LOAD_OR:
2992     return emitAtomicLoadBinary(MI, MBB, SystemZ::OR, 32);
2993   case SystemZ::ATOMIC_LOAD_OILL32:
2994     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL32, 32);
2995   case SystemZ::ATOMIC_LOAD_OILH32:
2996     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH32, 32);
2997   case SystemZ::ATOMIC_LOAD_OILF32:
2998     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF32, 32);
2999   case SystemZ::ATOMIC_LOAD_OGR:
3000     return emitAtomicLoadBinary(MI, MBB, SystemZ::OGR, 64);
3001   case SystemZ::ATOMIC_LOAD_OILL:
3002     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILL, 64);
3003   case SystemZ::ATOMIC_LOAD_OILH:
3004     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILH, 64);
3005   case SystemZ::ATOMIC_LOAD_OIHL:
3006     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHL, 64);
3007   case SystemZ::ATOMIC_LOAD_OIHH:
3008     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHH, 64);
3009   case SystemZ::ATOMIC_LOAD_OILF:
3010     return emitAtomicLoadBinary(MI, MBB, SystemZ::OILF, 64);
3011   case SystemZ::ATOMIC_LOAD_OIHF:
3012     return emitAtomicLoadBinary(MI, MBB, SystemZ::OIHF, 64);
3013
3014   case SystemZ::ATOMIC_LOADW_XR:
3015     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 0);
3016   case SystemZ::ATOMIC_LOADW_XILF:
3017     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF32, 0);
3018   case SystemZ::ATOMIC_LOAD_XR:
3019     return emitAtomicLoadBinary(MI, MBB, SystemZ::XR, 32);
3020   case SystemZ::ATOMIC_LOAD_XILF32:
3021     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF32, 32);
3022   case SystemZ::ATOMIC_LOAD_XGR:
3023     return emitAtomicLoadBinary(MI, MBB, SystemZ::XGR, 64);
3024   case SystemZ::ATOMIC_LOAD_XILF:
3025     return emitAtomicLoadBinary(MI, MBB, SystemZ::XILF, 64);
3026   case SystemZ::ATOMIC_LOAD_XIHF:
3027     return emitAtomicLoadBinary(MI, MBB, SystemZ::XIHF, 64);
3028
3029   case SystemZ::ATOMIC_LOADW_NRi:
3030     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 0, true);
3031   case SystemZ::ATOMIC_LOADW_NILHi:
3032     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH32, 0, true);
3033   case SystemZ::ATOMIC_LOAD_NRi:
3034     return emitAtomicLoadBinary(MI, MBB, SystemZ::NR, 32, true);
3035   case SystemZ::ATOMIC_LOAD_NILL32i:
3036     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL32, 32, true);
3037   case SystemZ::ATOMIC_LOAD_NILH32i:
3038     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH32, 32, true);
3039   case SystemZ::ATOMIC_LOAD_NILF32i:
3040     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF32, 32, true);
3041   case SystemZ::ATOMIC_LOAD_NGRi:
3042     return emitAtomicLoadBinary(MI, MBB, SystemZ::NGR, 64, true);
3043   case SystemZ::ATOMIC_LOAD_NILLi:
3044     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILL, 64, true);
3045   case SystemZ::ATOMIC_LOAD_NILHi:
3046     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILH, 64, true);
3047   case SystemZ::ATOMIC_LOAD_NIHLi:
3048     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHL, 64, true);
3049   case SystemZ::ATOMIC_LOAD_NIHHi:
3050     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHH, 64, true);
3051   case SystemZ::ATOMIC_LOAD_NILFi:
3052     return emitAtomicLoadBinary(MI, MBB, SystemZ::NILF, 64, true);
3053   case SystemZ::ATOMIC_LOAD_NIHFi:
3054     return emitAtomicLoadBinary(MI, MBB, SystemZ::NIHF, 64, true);
3055
3056   case SystemZ::ATOMIC_LOADW_MIN:
3057     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
3058                                 SystemZ::CCMASK_CMP_LE, 0);
3059   case SystemZ::ATOMIC_LOAD_MIN_32:
3060     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
3061                                 SystemZ::CCMASK_CMP_LE, 32);
3062   case SystemZ::ATOMIC_LOAD_MIN_64:
3063     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
3064                                 SystemZ::CCMASK_CMP_LE, 64);
3065
3066   case SystemZ::ATOMIC_LOADW_MAX:
3067     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
3068                                 SystemZ::CCMASK_CMP_GE, 0);
3069   case SystemZ::ATOMIC_LOAD_MAX_32:
3070     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CR,
3071                                 SystemZ::CCMASK_CMP_GE, 32);
3072   case SystemZ::ATOMIC_LOAD_MAX_64:
3073     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CGR,
3074                                 SystemZ::CCMASK_CMP_GE, 64);
3075
3076   case SystemZ::ATOMIC_LOADW_UMIN:
3077     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
3078                                 SystemZ::CCMASK_CMP_LE, 0);
3079   case SystemZ::ATOMIC_LOAD_UMIN_32:
3080     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
3081                                 SystemZ::CCMASK_CMP_LE, 32);
3082   case SystemZ::ATOMIC_LOAD_UMIN_64:
3083     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
3084                                 SystemZ::CCMASK_CMP_LE, 64);
3085
3086   case SystemZ::ATOMIC_LOADW_UMAX:
3087     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
3088                                 SystemZ::CCMASK_CMP_GE, 0);
3089   case SystemZ::ATOMIC_LOAD_UMAX_32:
3090     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLR,
3091                                 SystemZ::CCMASK_CMP_GE, 32);
3092   case SystemZ::ATOMIC_LOAD_UMAX_64:
3093     return emitAtomicLoadMinMax(MI, MBB, SystemZ::CLGR,
3094                                 SystemZ::CCMASK_CMP_GE, 64);
3095
3096   case SystemZ::ATOMIC_CMP_SWAPW:
3097     return emitAtomicCmpSwapW(MI, MBB);
3098   case SystemZ::MVCSequence:
3099   case SystemZ::MVCLoop:
3100     return emitMemMemWrapper(MI, MBB, SystemZ::MVC);
3101   case SystemZ::NCSequence:
3102   case SystemZ::NCLoop:
3103     return emitMemMemWrapper(MI, MBB, SystemZ::NC);
3104   case SystemZ::OCSequence:
3105   case SystemZ::OCLoop:
3106     return emitMemMemWrapper(MI, MBB, SystemZ::OC);
3107   case SystemZ::XCSequence:
3108   case SystemZ::XCLoop:
3109     return emitMemMemWrapper(MI, MBB, SystemZ::XC);
3110   case SystemZ::CLCSequence:
3111   case SystemZ::CLCLoop:
3112     return emitMemMemWrapper(MI, MBB, SystemZ::CLC);
3113   case SystemZ::CLSTLoop:
3114     return emitStringWrapper(MI, MBB, SystemZ::CLST);
3115   case SystemZ::MVSTLoop:
3116     return emitStringWrapper(MI, MBB, SystemZ::MVST);
3117   case SystemZ::SRSTLoop:
3118     return emitStringWrapper(MI, MBB, SystemZ::SRST);
3119   default:
3120     llvm_unreachable("Unexpected instr type to insert");
3121   }
3122 }