LegalizeIntegerTypes.cpp revision c56d65f63cd632ef57d9f80b4539f15a2f937364
1//===----- LegalizeIntegerTypes.cpp - Legalization of integer types -------===//
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 integer type expansion and promotion for LegalizeTypes.
11// Promotion is the act of changing a computation in an illegal type into a
12// computation in a larger type.  For example, implementing i8 arithmetic in an
13// i32 register (often needed on powerpc).
14// Expansion is the act of changing a computation in an illegal type into a
15// computation in two identical registers of a smaller type.  For example,
16// implementing i64 arithmetic in two i32 registers (often needed on 32-bit
17// targets).
18//
19//===----------------------------------------------------------------------===//
20
21#include "LegalizeTypes.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/CodeGen/PseudoSourceValue.h"
24#include "llvm/Support/ErrorHandling.h"
25#include "llvm/Support/raw_ostream.h"
26using namespace llvm;
27
28//===----------------------------------------------------------------------===//
29//  Integer Result Promotion
30//===----------------------------------------------------------------------===//
31
32/// PromoteIntegerResult - This method is called when a result of a node is
33/// found to be in need of promotion to a larger type.  At this point, the node
34/// may also have invalid operands or may have other results that need
35/// expansion, we just know that (at least) one result needs promotion.
36void DAGTypeLegalizer::PromoteIntegerResult(SDNode *N, unsigned ResNo) {
37  DEBUG(dbgs() << "Promote integer result: "; N->dump(&DAG); dbgs() << "\n");
38  SDValue Res = SDValue();
39
40  // See if the target wants to custom expand this node.
41  if (CustomLowerNode(N, N->getValueType(ResNo), true))
42    return;
43
44  switch (N->getOpcode()) {
45  default:
46#ifndef NDEBUG
47    dbgs() << "PromoteIntegerResult #" << ResNo << ": ";
48    N->dump(&DAG); dbgs() << "\n";
49#endif
50    llvm_unreachable("Do not know how to promote this operator!");
51  case ISD::MERGE_VALUES:Res = PromoteIntRes_MERGE_VALUES(N); break;
52  case ISD::AssertSext:  Res = PromoteIntRes_AssertSext(N); break;
53  case ISD::AssertZext:  Res = PromoteIntRes_AssertZext(N); break;
54  case ISD::BITCAST:     Res = PromoteIntRes_BITCAST(N); break;
55  case ISD::BSWAP:       Res = PromoteIntRes_BSWAP(N); break;
56  case ISD::BUILD_PAIR:  Res = PromoteIntRes_BUILD_PAIR(N); break;
57  case ISD::Constant:    Res = PromoteIntRes_Constant(N); break;
58  case ISD::CONVERT_RNDSAT:
59                         Res = PromoteIntRes_CONVERT_RNDSAT(N); break;
60  case ISD::CTLZ:        Res = PromoteIntRes_CTLZ(N); break;
61  case ISD::CTPOP:       Res = PromoteIntRes_CTPOP(N); break;
62  case ISD::CTTZ:        Res = PromoteIntRes_CTTZ(N); break;
63  case ISD::EXTRACT_VECTOR_ELT:
64                         Res = PromoteIntRes_EXTRACT_VECTOR_ELT(N); break;
65  case ISD::LOAD:        Res = PromoteIntRes_LOAD(cast<LoadSDNode>(N));break;
66  case ISD::SELECT:      Res = PromoteIntRes_SELECT(N); break;
67  case ISD::VSELECT:     Res = PromoteIntRes_VSELECT(N); break;
68  case ISD::SELECT_CC:   Res = PromoteIntRes_SELECT_CC(N); break;
69  case ISD::SETCC:       Res = PromoteIntRes_SETCC(N); break;
70  case ISD::SHL:         Res = PromoteIntRes_SHL(N); break;
71  case ISD::SIGN_EXTEND_INREG:
72                         Res = PromoteIntRes_SIGN_EXTEND_INREG(N); break;
73  case ISD::SRA:         Res = PromoteIntRes_SRA(N); break;
74  case ISD::SRL:         Res = PromoteIntRes_SRL(N); break;
75  case ISD::TRUNCATE:    Res = PromoteIntRes_TRUNCATE(N); break;
76  case ISD::UNDEF:       Res = PromoteIntRes_UNDEF(N); break;
77  case ISD::VAARG:       Res = PromoteIntRes_VAARG(N); break;
78
79  case ISD::EXTRACT_SUBVECTOR:
80                         Res = PromoteIntRes_EXTRACT_SUBVECTOR(N); break;
81  case ISD::VECTOR_SHUFFLE:
82                         Res = PromoteIntRes_VECTOR_SHUFFLE(N); break;
83  case ISD::INSERT_VECTOR_ELT:
84                         Res = PromoteIntRes_INSERT_VECTOR_ELT(N); break;
85  case ISD::BUILD_VECTOR:
86                         Res = PromoteIntRes_BUILD_VECTOR(N); break;
87  case ISD::SCALAR_TO_VECTOR:
88                         Res = PromoteIntRes_SCALAR_TO_VECTOR(N); break;
89  case ISD::CONCAT_VECTORS:
90                         Res = PromoteIntRes_CONCAT_VECTORS(N); break;
91
92  case ISD::SIGN_EXTEND:
93  case ISD::ZERO_EXTEND:
94  case ISD::ANY_EXTEND:  Res = PromoteIntRes_INT_EXTEND(N); break;
95
96  case ISD::FP_TO_SINT:
97  case ISD::FP_TO_UINT:  Res = PromoteIntRes_FP_TO_XINT(N); break;
98
99  case ISD::FP32_TO_FP16:Res = PromoteIntRes_FP32_TO_FP16(N); break;
100
101  case ISD::AND:
102  case ISD::OR:
103  case ISD::XOR:
104  case ISD::ADD:
105  case ISD::SUB:
106  case ISD::MUL:         Res = PromoteIntRes_SimpleIntBinOp(N); break;
107
108  case ISD::SDIV:
109  case ISD::SREM:        Res = PromoteIntRes_SDIV(N); break;
110
111  case ISD::UDIV:
112  case ISD::UREM:        Res = PromoteIntRes_UDIV(N); break;
113
114  case ISD::SADDO:
115  case ISD::SSUBO:       Res = PromoteIntRes_SADDSUBO(N, ResNo); break;
116  case ISD::UADDO:
117  case ISD::USUBO:       Res = PromoteIntRes_UADDSUBO(N, ResNo); break;
118  case ISD::SMULO:
119  case ISD::UMULO:       Res = PromoteIntRes_XMULO(N, ResNo); break;
120
121  case ISD::ATOMIC_LOAD:
122    Res = PromoteIntRes_Atomic0(cast<AtomicSDNode>(N)); break;
123
124  case ISD::ATOMIC_LOAD_ADD:
125  case ISD::ATOMIC_LOAD_SUB:
126  case ISD::ATOMIC_LOAD_AND:
127  case ISD::ATOMIC_LOAD_OR:
128  case ISD::ATOMIC_LOAD_XOR:
129  case ISD::ATOMIC_LOAD_NAND:
130  case ISD::ATOMIC_LOAD_MIN:
131  case ISD::ATOMIC_LOAD_MAX:
132  case ISD::ATOMIC_LOAD_UMIN:
133  case ISD::ATOMIC_LOAD_UMAX:
134  case ISD::ATOMIC_SWAP:
135    Res = PromoteIntRes_Atomic1(cast<AtomicSDNode>(N)); break;
136
137  case ISD::ATOMIC_CMP_SWAP:
138    Res = PromoteIntRes_Atomic2(cast<AtomicSDNode>(N)); break;
139  }
140
141  // If the result is null then the sub-method took care of registering it.
142  if (Res.getNode())
143    SetPromotedInteger(SDValue(N, ResNo), Res);
144}
145
146SDValue DAGTypeLegalizer::PromoteIntRes_MERGE_VALUES(SDNode *N) {
147  SDValue Op = DecomposeMERGE_VALUES(N);
148  return GetPromotedInteger(Op);
149}
150
151SDValue DAGTypeLegalizer::PromoteIntRes_AssertSext(SDNode *N) {
152  // Sign-extend the new bits, and continue the assertion.
153  SDValue Op = SExtPromotedInteger(N->getOperand(0));
154  return DAG.getNode(ISD::AssertSext, N->getDebugLoc(),
155                     Op.getValueType(), Op, N->getOperand(1));
156}
157
158SDValue DAGTypeLegalizer::PromoteIntRes_AssertZext(SDNode *N) {
159  // Zero the new bits, and continue the assertion.
160  SDValue Op = ZExtPromotedInteger(N->getOperand(0));
161  return DAG.getNode(ISD::AssertZext, N->getDebugLoc(),
162                     Op.getValueType(), Op, N->getOperand(1));
163}
164
165SDValue DAGTypeLegalizer::PromoteIntRes_Atomic0(AtomicSDNode *N) {
166  EVT ResVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
167  SDValue Res = DAG.getAtomic(N->getOpcode(), N->getDebugLoc(),
168                              N->getMemoryVT(), ResVT,
169                              N->getChain(), N->getBasePtr(),
170                              N->getMemOperand(), N->getOrdering(),
171                              N->getSynchScope());
172  // Legalized the chain result - switch anything that used the old chain to
173  // use the new one.
174  ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
175  return Res;
176}
177
178SDValue DAGTypeLegalizer::PromoteIntRes_Atomic1(AtomicSDNode *N) {
179  SDValue Op2 = GetPromotedInteger(N->getOperand(2));
180  SDValue Res = DAG.getAtomic(N->getOpcode(), N->getDebugLoc(),
181                              N->getMemoryVT(),
182                              N->getChain(), N->getBasePtr(),
183                              Op2, N->getMemOperand(), N->getOrdering(),
184                              N->getSynchScope());
185  // Legalized the chain result - switch anything that used the old chain to
186  // use the new one.
187  ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
188  return Res;
189}
190
191SDValue DAGTypeLegalizer::PromoteIntRes_Atomic2(AtomicSDNode *N) {
192  SDValue Op2 = GetPromotedInteger(N->getOperand(2));
193  SDValue Op3 = GetPromotedInteger(N->getOperand(3));
194  SDValue Res = DAG.getAtomic(N->getOpcode(), N->getDebugLoc(),
195                              N->getMemoryVT(), N->getChain(), N->getBasePtr(),
196                              Op2, Op3, N->getMemOperand(), N->getOrdering(),
197                              N->getSynchScope());
198  // Legalized the chain result - switch anything that used the old chain to
199  // use the new one.
200  ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
201  return Res;
202}
203
204SDValue DAGTypeLegalizer::PromoteIntRes_BITCAST(SDNode *N) {
205  SDValue InOp = N->getOperand(0);
206  EVT InVT = InOp.getValueType();
207  EVT NInVT = TLI.getTypeToTransformTo(*DAG.getContext(), InVT);
208  EVT OutVT = N->getValueType(0);
209  EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
210  DebugLoc dl = N->getDebugLoc();
211
212  switch (getTypeAction(InVT)) {
213  default:
214    assert(false && "Unknown type action!");
215    break;
216  case TargetLowering::TypeLegal:
217    break;
218  case TargetLowering::TypePromoteInteger:
219    if (NOutVT.bitsEq(NInVT))
220      // The input promotes to the same size.  Convert the promoted value.
221      return DAG.getNode(ISD::BITCAST, dl, NOutVT, GetPromotedInteger(InOp));
222    break;
223  case TargetLowering::TypeSoftenFloat:
224    // Promote the integer operand by hand.
225    return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT, GetSoftenedFloat(InOp));
226  case TargetLowering::TypeExpandInteger:
227  case TargetLowering::TypeExpandFloat:
228    break;
229  case TargetLowering::TypeScalarizeVector:
230    // Convert the element to an integer and promote it by hand.
231    if (!NOutVT.isVector())
232      return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT,
233                         BitConvertToInteger(GetScalarizedVector(InOp)));
234    break;
235  case TargetLowering::TypeSplitVector: {
236    // For example, i32 = BITCAST v2i16 on alpha.  Convert the split
237    // pieces of the input into integers and reassemble in the final type.
238    SDValue Lo, Hi;
239    GetSplitVector(N->getOperand(0), Lo, Hi);
240    Lo = BitConvertToInteger(Lo);
241    Hi = BitConvertToInteger(Hi);
242
243    if (TLI.isBigEndian())
244      std::swap(Lo, Hi);
245
246    InOp = DAG.getNode(ISD::ANY_EXTEND, dl,
247                       EVT::getIntegerVT(*DAG.getContext(),
248                                         NOutVT.getSizeInBits()),
249                       JoinIntegers(Lo, Hi));
250    return DAG.getNode(ISD::BITCAST, dl, NOutVT, InOp);
251  }
252  case TargetLowering::TypeWidenVector:
253    if (OutVT.bitsEq(NInVT))
254      // The input is widened to the same size.  Convert to the widened value.
255      return DAG.getNode(ISD::BITCAST, dl, OutVT, GetWidenedVector(InOp));
256  }
257
258  return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT,
259                     CreateStackStoreLoad(InOp, OutVT));
260}
261
262SDValue DAGTypeLegalizer::PromoteIntRes_BSWAP(SDNode *N) {
263  SDValue Op = GetPromotedInteger(N->getOperand(0));
264  EVT OVT = N->getValueType(0);
265  EVT NVT = Op.getValueType();
266  DebugLoc dl = N->getDebugLoc();
267
268  unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
269  return DAG.getNode(ISD::SRL, dl, NVT, DAG.getNode(ISD::BSWAP, dl, NVT, Op),
270                     DAG.getConstant(DiffBits, TLI.getPointerTy()));
271}
272
273SDValue DAGTypeLegalizer::PromoteIntRes_BUILD_PAIR(SDNode *N) {
274  // The pair element type may be legal, or may not promote to the same type as
275  // the result, for example i14 = BUILD_PAIR (i7, i7).  Handle all cases.
276  return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(),
277                     TLI.getTypeToTransformTo(*DAG.getContext(),
278                     N->getValueType(0)), JoinIntegers(N->getOperand(0),
279                     N->getOperand(1)));
280}
281
282SDValue DAGTypeLegalizer::PromoteIntRes_Constant(SDNode *N) {
283  EVT VT = N->getValueType(0);
284  // FIXME there is no actual debug info here
285  DebugLoc dl = N->getDebugLoc();
286  // Zero extend things like i1, sign extend everything else.  It shouldn't
287  // matter in theory which one we pick, but this tends to give better code?
288  unsigned Opc = VT.isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
289  SDValue Result = DAG.getNode(Opc, dl,
290                               TLI.getTypeToTransformTo(*DAG.getContext(), VT),
291                               SDValue(N, 0));
292  assert(isa<ConstantSDNode>(Result) && "Didn't constant fold ext?");
293  return Result;
294}
295
296SDValue DAGTypeLegalizer::PromoteIntRes_CONVERT_RNDSAT(SDNode *N) {
297  ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode();
298  assert ((CvtCode == ISD::CVT_SS || CvtCode == ISD::CVT_SU ||
299           CvtCode == ISD::CVT_US || CvtCode == ISD::CVT_UU ||
300           CvtCode == ISD::CVT_SF || CvtCode == ISD::CVT_UF) &&
301          "can only promote integers");
302  EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
303  return DAG.getConvertRndSat(OutVT, N->getDebugLoc(), N->getOperand(0),
304                              N->getOperand(1), N->getOperand(2),
305                              N->getOperand(3), N->getOperand(4), CvtCode);
306}
307
308SDValue DAGTypeLegalizer::PromoteIntRes_CTLZ(SDNode *N) {
309  // Zero extend to the promoted type and do the count there.
310  SDValue Op = ZExtPromotedInteger(N->getOperand(0));
311  DebugLoc dl = N->getDebugLoc();
312  EVT OVT = N->getValueType(0);
313  EVT NVT = Op.getValueType();
314  Op = DAG.getNode(ISD::CTLZ, dl, NVT, Op);
315  // Subtract off the extra leading bits in the bigger type.
316  return DAG.getNode(ISD::SUB, dl, NVT, Op,
317                     DAG.getConstant(NVT.getSizeInBits() -
318                                     OVT.getSizeInBits(), NVT));
319}
320
321SDValue DAGTypeLegalizer::PromoteIntRes_CTPOP(SDNode *N) {
322  // Zero extend to the promoted type and do the count there.
323  SDValue Op = ZExtPromotedInteger(N->getOperand(0));
324  return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), Op.getValueType(), Op);
325}
326
327SDValue DAGTypeLegalizer::PromoteIntRes_CTTZ(SDNode *N) {
328  SDValue Op = GetPromotedInteger(N->getOperand(0));
329  EVT OVT = N->getValueType(0);
330  EVT NVT = Op.getValueType();
331  DebugLoc dl = N->getDebugLoc();
332  // The count is the same in the promoted type except if the original
333  // value was zero.  This can be handled by setting the bit just off
334  // the top of the original type.
335  APInt TopBit(NVT.getSizeInBits(), 0);
336  TopBit.setBit(OVT.getSizeInBits());
337  Op = DAG.getNode(ISD::OR, dl, NVT, Op, DAG.getConstant(TopBit, NVT));
338  return DAG.getNode(ISD::CTTZ, dl, NVT, Op);
339}
340
341SDValue DAGTypeLegalizer::PromoteIntRes_EXTRACT_VECTOR_ELT(SDNode *N) {
342  DebugLoc dl = N->getDebugLoc();
343  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
344  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, NVT, N->getOperand(0),
345                     N->getOperand(1));
346}
347
348SDValue DAGTypeLegalizer::PromoteIntRes_FP_TO_XINT(SDNode *N) {
349  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
350  unsigned NewOpc = N->getOpcode();
351  DebugLoc dl = N->getDebugLoc();
352
353  // If we're promoting a UINT to a larger size and the larger FP_TO_UINT is
354  // not Legal, check to see if we can use FP_TO_SINT instead.  (If both UINT
355  // and SINT conversions are Custom, there is no way to tell which is
356  // preferable. We choose SINT because that's the right thing on PPC.)
357  if (N->getOpcode() == ISD::FP_TO_UINT &&
358      !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
359      TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NVT))
360    NewOpc = ISD::FP_TO_SINT;
361
362  SDValue Res = DAG.getNode(NewOpc, dl, NVT, N->getOperand(0));
363
364  // Assert that the converted value fits in the original type.  If it doesn't
365  // (eg: because the value being converted is too big), then the result of the
366  // original operation was undefined anyway, so the assert is still correct.
367  return DAG.getNode(N->getOpcode() == ISD::FP_TO_UINT ?
368                     ISD::AssertZext : ISD::AssertSext, dl, NVT, Res,
369                     DAG.getValueType(N->getValueType(0).getScalarType()));
370}
371
372SDValue DAGTypeLegalizer::PromoteIntRes_FP32_TO_FP16(SDNode *N) {
373  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
374  DebugLoc dl = N->getDebugLoc();
375
376  SDValue Res = DAG.getNode(N->getOpcode(), dl, NVT, N->getOperand(0));
377
378  return DAG.getNode(ISD::AssertZext, dl,
379                     NVT, Res, DAG.getValueType(N->getValueType(0)));
380}
381
382SDValue DAGTypeLegalizer::PromoteIntRes_INT_EXTEND(SDNode *N) {
383  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
384  DebugLoc dl = N->getDebugLoc();
385
386  if (getTypeAction(N->getOperand(0).getValueType())
387      == TargetLowering::TypePromoteInteger) {
388    SDValue Res = GetPromotedInteger(N->getOperand(0));
389    assert(Res.getValueType().bitsLE(NVT) && "Extension doesn't make sense!");
390
391    // If the result and operand types are the same after promotion, simplify
392    // to an in-register extension.
393    if (NVT == Res.getValueType()) {
394      // The high bits are not guaranteed to be anything.  Insert an extend.
395      if (N->getOpcode() == ISD::SIGN_EXTEND)
396        return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Res,
397                           DAG.getValueType(N->getOperand(0).getValueType()));
398      if (N->getOpcode() == ISD::ZERO_EXTEND)
399        return DAG.getZeroExtendInReg(Res, dl,
400                      N->getOperand(0).getValueType().getScalarType());
401      assert(N->getOpcode() == ISD::ANY_EXTEND && "Unknown integer extension!");
402      return Res;
403    }
404  }
405
406  // Otherwise, just extend the original operand all the way to the larger type.
407  return DAG.getNode(N->getOpcode(), dl, NVT, N->getOperand(0));
408}
409
410SDValue DAGTypeLegalizer::PromoteIntRes_LOAD(LoadSDNode *N) {
411  assert(ISD::isUNINDEXEDLoad(N) && "Indexed load during type legalization!");
412  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
413  ISD::LoadExtType ExtType =
414    ISD::isNON_EXTLoad(N) ? ISD::EXTLOAD : N->getExtensionType();
415  DebugLoc dl = N->getDebugLoc();
416  SDValue Res = DAG.getExtLoad(ExtType, dl, NVT, N->getChain(), N->getBasePtr(),
417                               N->getPointerInfo(),
418                               N->getMemoryVT(), N->isVolatile(),
419                               N->isNonTemporal(), N->getAlignment());
420
421  // Legalized the chain result - switch anything that used the old chain to
422  // use the new one.
423  ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
424  return Res;
425}
426
427/// Promote the overflow flag of an overflowing arithmetic node.
428SDValue DAGTypeLegalizer::PromoteIntRes_Overflow(SDNode *N) {
429  // Simply change the return type of the boolean result.
430  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(1));
431  EVT ValueVTs[] = { N->getValueType(0), NVT };
432  SDValue Ops[] = { N->getOperand(0), N->getOperand(1) };
433  SDValue Res = DAG.getNode(N->getOpcode(), N->getDebugLoc(),
434                            DAG.getVTList(ValueVTs, 2), Ops, 2);
435
436  // Modified the sum result - switch anything that used the old sum to use
437  // the new one.
438  ReplaceValueWith(SDValue(N, 0), Res);
439
440  return SDValue(Res.getNode(), 1);
441}
442
443SDValue DAGTypeLegalizer::PromoteIntRes_SADDSUBO(SDNode *N, unsigned ResNo) {
444  if (ResNo == 1)
445    return PromoteIntRes_Overflow(N);
446
447  // The operation overflowed iff the result in the larger type is not the
448  // sign extension of its truncation to the original type.
449  SDValue LHS = SExtPromotedInteger(N->getOperand(0));
450  SDValue RHS = SExtPromotedInteger(N->getOperand(1));
451  EVT OVT = N->getOperand(0).getValueType();
452  EVT NVT = LHS.getValueType();
453  DebugLoc dl = N->getDebugLoc();
454
455  // Do the arithmetic in the larger type.
456  unsigned Opcode = N->getOpcode() == ISD::SADDO ? ISD::ADD : ISD::SUB;
457  SDValue Res = DAG.getNode(Opcode, dl, NVT, LHS, RHS);
458
459  // Calculate the overflow flag: sign extend the arithmetic result from
460  // the original type.
461  SDValue Ofl = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Res,
462                            DAG.getValueType(OVT));
463  // Overflowed if and only if this is not equal to Res.
464  Ofl = DAG.getSetCC(dl, N->getValueType(1), Ofl, Res, ISD::SETNE);
465
466  // Use the calculated overflow everywhere.
467  ReplaceValueWith(SDValue(N, 1), Ofl);
468
469  return Res;
470}
471
472SDValue DAGTypeLegalizer::PromoteIntRes_SDIV(SDNode *N) {
473  // Sign extend the input.
474  SDValue LHS = SExtPromotedInteger(N->getOperand(0));
475  SDValue RHS = SExtPromotedInteger(N->getOperand(1));
476  return DAG.getNode(N->getOpcode(), N->getDebugLoc(),
477                     LHS.getValueType(), LHS, RHS);
478}
479
480SDValue DAGTypeLegalizer::PromoteIntRes_SELECT(SDNode *N) {
481  SDValue LHS = GetPromotedInteger(N->getOperand(1));
482  SDValue RHS = GetPromotedInteger(N->getOperand(2));
483  return DAG.getNode(ISD::SELECT, N->getDebugLoc(),
484                     LHS.getValueType(), N->getOperand(0),LHS,RHS);
485}
486
487SDValue DAGTypeLegalizer::PromoteIntRes_VSELECT(SDNode *N) {
488  SDValue Mask = GetPromotedInteger(N->getOperand(0));
489  SDValue LHS = GetPromotedInteger(N->getOperand(1));
490  SDValue RHS = GetPromotedInteger(N->getOperand(2));
491  return DAG.getNode(ISD::VSELECT, N->getDebugLoc(),
492                     LHS.getValueType(), Mask, LHS, RHS);
493}
494
495SDValue DAGTypeLegalizer::PromoteIntRes_SELECT_CC(SDNode *N) {
496  SDValue LHS = GetPromotedInteger(N->getOperand(2));
497  SDValue RHS = GetPromotedInteger(N->getOperand(3));
498  return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(),
499                     LHS.getValueType(), N->getOperand(0),
500                     N->getOperand(1), LHS, RHS, N->getOperand(4));
501}
502
503SDValue DAGTypeLegalizer::PromoteIntRes_SETCC(SDNode *N) {
504  EVT SVT = TLI.getSetCCResultType(N->getOperand(0).getValueType());
505  // Vector setcc result types need to be leglized.
506  SVT = TLI.getTypeToTransformTo(*DAG.getContext(), SVT);
507
508  DebugLoc dl = N->getDebugLoc();
509  assert(SVT.isVector() == N->getOperand(0).getValueType().isVector() &&
510         "Vector compare must return a vector result!");
511
512  // Get the SETCC result using the canonical SETCC type.
513  SDValue SetCC = DAG.getNode(N->getOpcode(), dl, SVT, N->getOperand(0),
514                              N->getOperand(1), N->getOperand(2));
515
516  // Convert to the expected type.
517  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
518  assert(NVT.bitsLE(SVT) && "Integer type overpromoted?");
519  return DAG.getNode(ISD::TRUNCATE, dl, NVT, SetCC);
520}
521
522SDValue DAGTypeLegalizer::PromoteIntRes_SHL(SDNode *N) {
523  return DAG.getNode(ISD::SHL, N->getDebugLoc(),
524                TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0)),
525                     GetPromotedInteger(N->getOperand(0)), N->getOperand(1));
526}
527
528SDValue DAGTypeLegalizer::PromoteIntRes_SIGN_EXTEND_INREG(SDNode *N) {
529  SDValue Op = GetPromotedInteger(N->getOperand(0));
530  return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(),
531                     Op.getValueType(), Op, N->getOperand(1));
532}
533
534SDValue DAGTypeLegalizer::PromoteIntRes_SimpleIntBinOp(SDNode *N) {
535  // The input may have strange things in the top bits of the registers, but
536  // these operations don't care.  They may have weird bits going out, but
537  // that too is okay if they are integer operations.
538  SDValue LHS = GetPromotedInteger(N->getOperand(0));
539  SDValue RHS = GetPromotedInteger(N->getOperand(1));
540  return DAG.getNode(N->getOpcode(), N->getDebugLoc(),
541                    LHS.getValueType(), LHS, RHS);
542}
543
544SDValue DAGTypeLegalizer::PromoteIntRes_SRA(SDNode *N) {
545  // The input value must be properly sign extended.
546  SDValue Res = SExtPromotedInteger(N->getOperand(0));
547  return DAG.getNode(ISD::SRA, N->getDebugLoc(),
548                     Res.getValueType(), Res, N->getOperand(1));
549}
550
551SDValue DAGTypeLegalizer::PromoteIntRes_SRL(SDNode *N) {
552  // The input value must be properly zero extended.
553  EVT VT = N->getValueType(0);
554  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
555  SDValue Res = ZExtPromotedInteger(N->getOperand(0));
556  return DAG.getNode(ISD::SRL, N->getDebugLoc(), NVT, Res, N->getOperand(1));
557}
558
559SDValue DAGTypeLegalizer::PromoteIntRes_TRUNCATE(SDNode *N) {
560  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
561  SDValue Res;
562  SDValue InOp = N->getOperand(0);
563  DebugLoc dl = N->getDebugLoc();
564
565  switch (getTypeAction(InOp.getValueType())) {
566  default: llvm_unreachable("Unknown type action!");
567  case TargetLowering::TypeLegal:
568  case TargetLowering::TypeExpandInteger:
569    Res = InOp;
570    break;
571  case TargetLowering::TypePromoteInteger:
572    Res = GetPromotedInteger(InOp);
573    break;
574  case TargetLowering::TypeSplitVector:
575    EVT InVT = InOp.getValueType();
576    assert(InVT.isVector() && "Cannot split scalar types");
577    unsigned NumElts = InVT.getVectorNumElements();
578    assert(NumElts == NVT.getVectorNumElements() &&
579           "Dst and Src must have the same number of elements");
580    EVT EltVT = InVT.getScalarType();
581    assert(isPowerOf2_32(NumElts) &&
582           "Promoted vector type must be a power of two");
583
584    EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts/2);
585    EVT HalfNVT = EVT::getVectorVT(*DAG.getContext(), NVT.getScalarType(),
586                                   NumElts/2);
587
588    SDValue EOp1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, HalfVT, InOp,
589                               DAG.getIntPtrConstant(0));
590    SDValue EOp2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, HalfVT, InOp,
591                               DAG.getIntPtrConstant(NumElts/2));
592    EOp1 = DAG.getNode(ISD::TRUNCATE, dl, HalfNVT, EOp1);
593    EOp2 = DAG.getNode(ISD::TRUNCATE, dl, HalfNVT, EOp2);
594
595    return DAG.getNode(ISD::CONCAT_VECTORS, dl, NVT, EOp1, EOp2);
596  }
597
598  // Truncate to NVT instead of VT
599  return DAG.getNode(ISD::TRUNCATE, dl, NVT, Res);
600}
601
602SDValue DAGTypeLegalizer::PromoteIntRes_UADDSUBO(SDNode *N, unsigned ResNo) {
603  if (ResNo == 1)
604    return PromoteIntRes_Overflow(N);
605
606  // The operation overflowed iff the result in the larger type is not the
607  // zero extension of its truncation to the original type.
608  SDValue LHS = ZExtPromotedInteger(N->getOperand(0));
609  SDValue RHS = ZExtPromotedInteger(N->getOperand(1));
610  EVT OVT = N->getOperand(0).getValueType();
611  EVT NVT = LHS.getValueType();
612  DebugLoc dl = N->getDebugLoc();
613
614  // Do the arithmetic in the larger type.
615  unsigned Opcode = N->getOpcode() == ISD::UADDO ? ISD::ADD : ISD::SUB;
616  SDValue Res = DAG.getNode(Opcode, dl, NVT, LHS, RHS);
617
618  // Calculate the overflow flag: zero extend the arithmetic result from
619  // the original type.
620  SDValue Ofl = DAG.getZeroExtendInReg(Res, dl, OVT);
621  // Overflowed if and only if this is not equal to Res.
622  Ofl = DAG.getSetCC(dl, N->getValueType(1), Ofl, Res, ISD::SETNE);
623
624  // Use the calculated overflow everywhere.
625  ReplaceValueWith(SDValue(N, 1), Ofl);
626
627  return Res;
628}
629
630SDValue DAGTypeLegalizer::PromoteIntRes_XMULO(SDNode *N, unsigned ResNo) {
631  // Promote the overflow bit trivially.
632  if (ResNo == 1)
633    return PromoteIntRes_Overflow(N);
634
635  SDValue LHS = N->getOperand(0), RHS = N->getOperand(1);
636  DebugLoc DL = N->getDebugLoc();
637  EVT SmallVT = LHS.getValueType();
638
639  // To determine if the result overflowed in a larger type, we extend the
640  // input to the larger type, do the multiply, then check the high bits of
641  // the result to see if the overflow happened.
642  if (N->getOpcode() == ISD::SMULO) {
643    LHS = SExtPromotedInteger(LHS);
644    RHS = SExtPromotedInteger(RHS);
645  } else {
646    LHS = ZExtPromotedInteger(LHS);
647    RHS = ZExtPromotedInteger(RHS);
648  }
649  SDValue Mul = DAG.getNode(ISD::MUL, DL, LHS.getValueType(), LHS, RHS);
650
651  // Overflow occurred iff the high part of the result does not
652  // zero/sign-extend the low part.
653  SDValue Overflow;
654  if (N->getOpcode() == ISD::UMULO) {
655    // Unsigned overflow occurred iff the high part is non-zero.
656    SDValue Hi = DAG.getNode(ISD::SRL, DL, Mul.getValueType(), Mul,
657                             DAG.getIntPtrConstant(SmallVT.getSizeInBits()));
658    Overflow = DAG.getSetCC(DL, N->getValueType(1), Hi,
659                            DAG.getConstant(0, Hi.getValueType()), ISD::SETNE);
660  } else {
661    // Signed overflow occurred iff the high part does not sign extend the low.
662    SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Mul.getValueType(),
663                               Mul, DAG.getValueType(SmallVT));
664    Overflow = DAG.getSetCC(DL, N->getValueType(1), SExt, Mul, ISD::SETNE);
665  }
666
667  // Use the calculated overflow everywhere.
668  ReplaceValueWith(SDValue(N, 1), Overflow);
669  return Mul;
670}
671
672SDValue DAGTypeLegalizer::PromoteIntRes_UDIV(SDNode *N) {
673  // Zero extend the input.
674  SDValue LHS = ZExtPromotedInteger(N->getOperand(0));
675  SDValue RHS = ZExtPromotedInteger(N->getOperand(1));
676  return DAG.getNode(N->getOpcode(), N->getDebugLoc(),
677                     LHS.getValueType(), LHS, RHS);
678}
679
680SDValue DAGTypeLegalizer::PromoteIntRes_UNDEF(SDNode *N) {
681  return DAG.getUNDEF(TLI.getTypeToTransformTo(*DAG.getContext(),
682                                               N->getValueType(0)));
683}
684
685SDValue DAGTypeLegalizer::PromoteIntRes_VAARG(SDNode *N) {
686  SDValue Chain = N->getOperand(0); // Get the chain.
687  SDValue Ptr = N->getOperand(1); // Get the pointer.
688  EVT VT = N->getValueType(0);
689  DebugLoc dl = N->getDebugLoc();
690
691  EVT RegVT = TLI.getRegisterType(*DAG.getContext(), VT);
692  unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), VT);
693  // The argument is passed as NumRegs registers of type RegVT.
694
695  SmallVector<SDValue, 8> Parts(NumRegs);
696  for (unsigned i = 0; i < NumRegs; ++i) {
697    Parts[i] = DAG.getVAArg(RegVT, dl, Chain, Ptr, N->getOperand(2),
698                            N->getConstantOperandVal(3));
699    Chain = Parts[i].getValue(1);
700  }
701
702  // Handle endianness of the load.
703  if (TLI.isBigEndian())
704    std::reverse(Parts.begin(), Parts.end());
705
706  // Assemble the parts in the promoted type.
707  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
708  SDValue Res = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Parts[0]);
709  for (unsigned i = 1; i < NumRegs; ++i) {
710    SDValue Part = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Parts[i]);
711    // Shift it to the right position and "or" it in.
712    Part = DAG.getNode(ISD::SHL, dl, NVT, Part,
713                       DAG.getConstant(i * RegVT.getSizeInBits(),
714                                       TLI.getPointerTy()));
715    Res = DAG.getNode(ISD::OR, dl, NVT, Res, Part);
716  }
717
718  // Modified the chain result - switch anything that used the old chain to
719  // use the new one.
720  ReplaceValueWith(SDValue(N, 1), Chain);
721
722  return Res;
723}
724
725//===----------------------------------------------------------------------===//
726//  Integer Operand Promotion
727//===----------------------------------------------------------------------===//
728
729/// PromoteIntegerOperand - This method is called when the specified operand of
730/// the specified node is found to need promotion.  At this point, all of the
731/// result types of the node are known to be legal, but other operands of the
732/// node may need promotion or expansion as well as the specified one.
733bool DAGTypeLegalizer::PromoteIntegerOperand(SDNode *N, unsigned OpNo) {
734  DEBUG(dbgs() << "Promote integer operand: "; N->dump(&DAG); dbgs() << "\n");
735  SDValue Res = SDValue();
736
737  if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
738    return false;
739
740  switch (N->getOpcode()) {
741    default:
742  #ifndef NDEBUG
743    dbgs() << "PromoteIntegerOperand Op #" << OpNo << ": ";
744    N->dump(&DAG); dbgs() << "\n";
745  #endif
746    llvm_unreachable("Do not know how to promote this operator's operand!");
747
748  case ISD::ANY_EXTEND:   Res = PromoteIntOp_ANY_EXTEND(N); break;
749  case ISD::ATOMIC_STORE:
750    Res = PromoteIntOp_ATOMIC_STORE(cast<AtomicSDNode>(N));
751    break;
752  case ISD::BITCAST:      Res = PromoteIntOp_BITCAST(N); break;
753  case ISD::BR_CC:        Res = PromoteIntOp_BR_CC(N, OpNo); break;
754  case ISD::BRCOND:       Res = PromoteIntOp_BRCOND(N, OpNo); break;
755  case ISD::BUILD_PAIR:   Res = PromoteIntOp_BUILD_PAIR(N); break;
756  case ISD::BUILD_VECTOR: Res = PromoteIntOp_BUILD_VECTOR(N); break;
757  case ISD::CONCAT_VECTORS: Res = PromoteIntOp_CONCAT_VECTORS(N); break;
758  case ISD::EXTRACT_VECTOR_ELT: Res = PromoteIntOp_EXTRACT_VECTOR_ELT(N); break;
759  case ISD::CONVERT_RNDSAT:
760                          Res = PromoteIntOp_CONVERT_RNDSAT(N); break;
761  case ISD::INSERT_VECTOR_ELT:
762                          Res = PromoteIntOp_INSERT_VECTOR_ELT(N, OpNo);break;
763  case ISD::MEMBARRIER:   Res = PromoteIntOp_MEMBARRIER(N); break;
764  case ISD::SCALAR_TO_VECTOR:
765                          Res = PromoteIntOp_SCALAR_TO_VECTOR(N); break;
766  case ISD::VSELECT:
767  case ISD::SELECT:       Res = PromoteIntOp_SELECT(N, OpNo); break;
768  case ISD::SELECT_CC:    Res = PromoteIntOp_SELECT_CC(N, OpNo); break;
769  case ISD::SETCC:        Res = PromoteIntOp_SETCC(N, OpNo); break;
770  case ISD::SIGN_EXTEND:  Res = PromoteIntOp_SIGN_EXTEND(N); break;
771  case ISD::SINT_TO_FP:   Res = PromoteIntOp_SINT_TO_FP(N); break;
772  case ISD::STORE:        Res = PromoteIntOp_STORE(cast<StoreSDNode>(N),
773                                                   OpNo); break;
774  case ISD::TRUNCATE:     Res = PromoteIntOp_TRUNCATE(N); break;
775  case ISD::FP16_TO_FP32:
776  case ISD::UINT_TO_FP:   Res = PromoteIntOp_UINT_TO_FP(N); break;
777  case ISD::ZERO_EXTEND:  Res = PromoteIntOp_ZERO_EXTEND(N); break;
778
779  case ISD::SHL:
780  case ISD::SRA:
781  case ISD::SRL:
782  case ISD::ROTL:
783  case ISD::ROTR: Res = PromoteIntOp_Shift(N); break;
784  }
785
786  // If the result is null, the sub-method took care of registering results etc.
787  if (!Res.getNode()) return false;
788
789  // If the result is N, the sub-method updated N in place.  Tell the legalizer
790  // core about this.
791  if (Res.getNode() == N)
792    return true;
793
794  assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
795         "Invalid operand expansion");
796
797  ReplaceValueWith(SDValue(N, 0), Res);
798  return false;
799}
800
801/// PromoteSetCCOperands - Promote the operands of a comparison.  This code is
802/// shared among BR_CC, SELECT_CC, and SETCC handlers.
803void DAGTypeLegalizer::PromoteSetCCOperands(SDValue &NewLHS,SDValue &NewRHS,
804                                            ISD::CondCode CCCode) {
805  // We have to insert explicit sign or zero extends.  Note that we could
806  // insert sign extends for ALL conditions, but zero extend is cheaper on
807  // many machines (an AND instead of two shifts), so prefer it.
808  switch (CCCode) {
809  default: llvm_unreachable("Unknown integer comparison!");
810  case ISD::SETEQ:
811  case ISD::SETNE:
812  case ISD::SETUGE:
813  case ISD::SETUGT:
814  case ISD::SETULE:
815  case ISD::SETULT:
816    // ALL of these operations will work if we either sign or zero extend
817    // the operands (including the unsigned comparisons!).  Zero extend is
818    // usually a simpler/cheaper operation, so prefer it.
819    NewLHS = ZExtPromotedInteger(NewLHS);
820    NewRHS = ZExtPromotedInteger(NewRHS);
821    break;
822  case ISD::SETGE:
823  case ISD::SETGT:
824  case ISD::SETLT:
825  case ISD::SETLE:
826    NewLHS = SExtPromotedInteger(NewLHS);
827    NewRHS = SExtPromotedInteger(NewRHS);
828    break;
829  }
830}
831
832SDValue DAGTypeLegalizer::PromoteIntOp_ANY_EXTEND(SDNode *N) {
833  SDValue Op = GetPromotedInteger(N->getOperand(0));
834  return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), N->getValueType(0), Op);
835}
836
837SDValue DAGTypeLegalizer::PromoteIntOp_ATOMIC_STORE(AtomicSDNode *N) {
838  SDValue Op2 = GetPromotedInteger(N->getOperand(2));
839  return DAG.getAtomic(N->getOpcode(), N->getDebugLoc(), N->getMemoryVT(),
840                       N->getChain(), N->getBasePtr(), Op2, N->getMemOperand(),
841                       N->getOrdering(), N->getSynchScope());
842}
843
844SDValue DAGTypeLegalizer::PromoteIntOp_BITCAST(SDNode *N) {
845  // This should only occur in unusual situations like bitcasting to an
846  // x86_fp80, so just turn it into a store+load
847  return CreateStackStoreLoad(N->getOperand(0), N->getValueType(0));
848}
849
850SDValue DAGTypeLegalizer::PromoteIntOp_BR_CC(SDNode *N, unsigned OpNo) {
851  assert(OpNo == 2 && "Don't know how to promote this operand!");
852
853  SDValue LHS = N->getOperand(2);
854  SDValue RHS = N->getOperand(3);
855  PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(1))->get());
856
857  // The chain (Op#0), CC (#1) and basic block destination (Op#4) are always
858  // legal types.
859  return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
860                                N->getOperand(1), LHS, RHS, N->getOperand(4)),
861                 0);
862}
863
864SDValue DAGTypeLegalizer::PromoteIntOp_BRCOND(SDNode *N, unsigned OpNo) {
865  assert(OpNo == 1 && "only know how to promote condition");
866
867  // Promote all the way up to the canonical SetCC type.
868  EVT SVT = TLI.getSetCCResultType(MVT::Other);
869  SDValue Cond = PromoteTargetBoolean(N->getOperand(1), SVT);
870
871  // The chain (Op#0) and basic block destination (Op#2) are always legal types.
872  return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0), Cond,
873                                        N->getOperand(2)), 0);
874}
875
876SDValue DAGTypeLegalizer::PromoteIntOp_BUILD_PAIR(SDNode *N) {
877  // Since the result type is legal, the operands must promote to it.
878  EVT OVT = N->getOperand(0).getValueType();
879  SDValue Lo = ZExtPromotedInteger(N->getOperand(0));
880  SDValue Hi = GetPromotedInteger(N->getOperand(1));
881  assert(Lo.getValueType() == N->getValueType(0) && "Operand over promoted?");
882  DebugLoc dl = N->getDebugLoc();
883
884  Hi = DAG.getNode(ISD::SHL, dl, N->getValueType(0), Hi,
885                   DAG.getConstant(OVT.getSizeInBits(), TLI.getPointerTy()));
886  return DAG.getNode(ISD::OR, dl, N->getValueType(0), Lo, Hi);
887}
888
889SDValue DAGTypeLegalizer::PromoteIntOp_BUILD_VECTOR(SDNode *N) {
890  // The vector type is legal but the element type is not.  This implies
891  // that the vector is a power-of-two in length and that the element
892  // type does not have a strange size (eg: it is not i1).
893  EVT VecVT = N->getValueType(0);
894  unsigned NumElts = VecVT.getVectorNumElements();
895  assert(!(NumElts & 1) && "Legal vector of one illegal element?");
896
897  // Promote the inserted value.  The type does not need to match the
898  // vector element type.  Check that any extra bits introduced will be
899  // truncated away.
900  assert(N->getOperand(0).getValueType().getSizeInBits() >=
901         N->getValueType(0).getVectorElementType().getSizeInBits() &&
902         "Type of inserted value narrower than vector element type!");
903
904  SmallVector<SDValue, 16> NewOps;
905  for (unsigned i = 0; i < NumElts; ++i)
906    NewOps.push_back(GetPromotedInteger(N->getOperand(i)));
907
908  return SDValue(DAG.UpdateNodeOperands(N, &NewOps[0], NumElts), 0);
909}
910
911SDValue DAGTypeLegalizer::PromoteIntOp_CONVERT_RNDSAT(SDNode *N) {
912  ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode();
913  assert ((CvtCode == ISD::CVT_SS || CvtCode == ISD::CVT_SU ||
914           CvtCode == ISD::CVT_US || CvtCode == ISD::CVT_UU ||
915           CvtCode == ISD::CVT_FS || CvtCode == ISD::CVT_FU) &&
916           "can only promote integer arguments");
917  SDValue InOp = GetPromotedInteger(N->getOperand(0));
918  return DAG.getConvertRndSat(N->getValueType(0), N->getDebugLoc(), InOp,
919                              N->getOperand(1), N->getOperand(2),
920                              N->getOperand(3), N->getOperand(4), CvtCode);
921}
922
923SDValue DAGTypeLegalizer::PromoteIntOp_INSERT_VECTOR_ELT(SDNode *N,
924                                                         unsigned OpNo) {
925  if (OpNo == 1) {
926    // Promote the inserted value.  This is valid because the type does not
927    // have to match the vector element type.
928
929    // Check that any extra bits introduced will be truncated away.
930    assert(N->getOperand(1).getValueType().getSizeInBits() >=
931           N->getValueType(0).getVectorElementType().getSizeInBits() &&
932           "Type of inserted value narrower than vector element type!");
933    return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
934                                  GetPromotedInteger(N->getOperand(1)),
935                                  N->getOperand(2)),
936                   0);
937  }
938
939  assert(OpNo == 2 && "Different operand and result vector types?");
940
941  // Promote the index.
942  SDValue Idx = ZExtPromotedInteger(N->getOperand(2));
943  return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
944                                N->getOperand(1), Idx), 0);
945}
946
947SDValue DAGTypeLegalizer::PromoteIntOp_MEMBARRIER(SDNode *N) {
948  SDValue NewOps[6];
949  DebugLoc dl = N->getDebugLoc();
950  NewOps[0] = N->getOperand(0);
951  for (unsigned i = 1; i < array_lengthof(NewOps); ++i) {
952    SDValue Flag = GetPromotedInteger(N->getOperand(i));
953    NewOps[i] = DAG.getZeroExtendInReg(Flag, dl, MVT::i1);
954  }
955  return SDValue(DAG.UpdateNodeOperands(N, NewOps, array_lengthof(NewOps)), 0);
956}
957
958SDValue DAGTypeLegalizer::PromoteIntOp_SCALAR_TO_VECTOR(SDNode *N) {
959  // Integer SCALAR_TO_VECTOR operands are implicitly truncated, so just promote
960  // the operand in place.
961  return SDValue(DAG.UpdateNodeOperands(N,
962                                GetPromotedInteger(N->getOperand(0))), 0);
963}
964
965SDValue DAGTypeLegalizer::PromoteIntOp_SELECT(SDNode *N, unsigned OpNo) {
966  assert(OpNo == 0 && "Only know how to promote the condition!");
967  SDValue Cond = N->getOperand(0);
968  EVT OpTy = N->getOperand(1).getValueType();
969
970  // Promote all the way up to the canonical SetCC type.
971  EVT SVT = TLI.getSetCCResultType(N->getOpcode() == ISD::SELECT ?
972                                   OpTy.getScalarType() : OpTy);
973  Cond = PromoteTargetBoolean(Cond, SVT);
974
975  return SDValue(DAG.UpdateNodeOperands(N, Cond, N->getOperand(1),
976                                        N->getOperand(2)), 0);
977}
978
979SDValue DAGTypeLegalizer::PromoteIntOp_SELECT_CC(SDNode *N, unsigned OpNo) {
980  assert(OpNo == 0 && "Don't know how to promote this operand!");
981
982  SDValue LHS = N->getOperand(0);
983  SDValue RHS = N->getOperand(1);
984  PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(4))->get());
985
986  // The CC (#4) and the possible return values (#2 and #3) have legal types.
987  return SDValue(DAG.UpdateNodeOperands(N, LHS, RHS, N->getOperand(2),
988                                N->getOperand(3), N->getOperand(4)), 0);
989}
990
991SDValue DAGTypeLegalizer::PromoteIntOp_SETCC(SDNode *N, unsigned OpNo) {
992  assert(OpNo == 0 && "Don't know how to promote this operand!");
993
994  SDValue LHS = N->getOperand(0);
995  SDValue RHS = N->getOperand(1);
996  PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(2))->get());
997
998  // The CC (#2) is always legal.
999  return SDValue(DAG.UpdateNodeOperands(N, LHS, RHS, N->getOperand(2)), 0);
1000}
1001
1002SDValue DAGTypeLegalizer::PromoteIntOp_Shift(SDNode *N) {
1003  return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
1004                                ZExtPromotedInteger(N->getOperand(1))), 0);
1005}
1006
1007SDValue DAGTypeLegalizer::PromoteIntOp_SIGN_EXTEND(SDNode *N) {
1008  SDValue Op = GetPromotedInteger(N->getOperand(0));
1009  DebugLoc dl = N->getDebugLoc();
1010  Op = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Op);
1011  return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Op.getValueType(),
1012                     Op, DAG.getValueType(N->getOperand(0).getValueType()));
1013}
1014
1015SDValue DAGTypeLegalizer::PromoteIntOp_SINT_TO_FP(SDNode *N) {
1016  return SDValue(DAG.UpdateNodeOperands(N,
1017                                SExtPromotedInteger(N->getOperand(0))), 0);
1018}
1019
1020SDValue DAGTypeLegalizer::PromoteIntOp_STORE(StoreSDNode *N, unsigned OpNo){
1021  assert(ISD::isUNINDEXEDStore(N) && "Indexed store during type legalization!");
1022  SDValue Ch = N->getChain(), Ptr = N->getBasePtr();
1023  unsigned Alignment = N->getAlignment();
1024  bool isVolatile = N->isVolatile();
1025  bool isNonTemporal = N->isNonTemporal();
1026  DebugLoc dl = N->getDebugLoc();
1027
1028  SDValue Val = GetPromotedInteger(N->getValue());  // Get promoted value.
1029
1030  // Truncate the value and store the result.
1031  return DAG.getTruncStore(Ch, dl, Val, Ptr, N->getPointerInfo(),
1032                           N->getMemoryVT(),
1033                           isVolatile, isNonTemporal, Alignment);
1034}
1035
1036SDValue DAGTypeLegalizer::PromoteIntOp_TRUNCATE(SDNode *N) {
1037  SDValue Op = GetPromotedInteger(N->getOperand(0));
1038  return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), N->getValueType(0), Op);
1039}
1040
1041SDValue DAGTypeLegalizer::PromoteIntOp_UINT_TO_FP(SDNode *N) {
1042  return SDValue(DAG.UpdateNodeOperands(N,
1043                                ZExtPromotedInteger(N->getOperand(0))), 0);
1044}
1045
1046SDValue DAGTypeLegalizer::PromoteIntOp_ZERO_EXTEND(SDNode *N) {
1047  DebugLoc dl = N->getDebugLoc();
1048  SDValue Op = GetPromotedInteger(N->getOperand(0));
1049  Op = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Op);
1050  return DAG.getZeroExtendInReg(Op, dl,
1051                                N->getOperand(0).getValueType().getScalarType());
1052}
1053
1054
1055//===----------------------------------------------------------------------===//
1056//  Integer Result Expansion
1057//===----------------------------------------------------------------------===//
1058
1059/// ExpandIntegerResult - This method is called when the specified result of the
1060/// specified node is found to need expansion.  At this point, the node may also
1061/// have invalid operands or may have other results that need promotion, we just
1062/// know that (at least) one result needs expansion.
1063void DAGTypeLegalizer::ExpandIntegerResult(SDNode *N, unsigned ResNo) {
1064  DEBUG(dbgs() << "Expand integer result: "; N->dump(&DAG); dbgs() << "\n");
1065  SDValue Lo, Hi;
1066  Lo = Hi = SDValue();
1067
1068  // See if the target wants to custom expand this node.
1069  if (CustomLowerNode(N, N->getValueType(ResNo), true))
1070    return;
1071
1072  switch (N->getOpcode()) {
1073  default:
1074#ifndef NDEBUG
1075    dbgs() << "ExpandIntegerResult #" << ResNo << ": ";
1076    N->dump(&DAG); dbgs() << "\n";
1077#endif
1078    llvm_unreachable("Do not know how to expand the result of this operator!");
1079
1080  case ISD::MERGE_VALUES: SplitRes_MERGE_VALUES(N, Lo, Hi); break;
1081  case ISD::SELECT:       SplitRes_SELECT(N, Lo, Hi); break;
1082  case ISD::SELECT_CC:    SplitRes_SELECT_CC(N, Lo, Hi); break;
1083  case ISD::UNDEF:        SplitRes_UNDEF(N, Lo, Hi); break;
1084
1085  case ISD::BITCAST:            ExpandRes_BITCAST(N, Lo, Hi); break;
1086  case ISD::BUILD_PAIR:         ExpandRes_BUILD_PAIR(N, Lo, Hi); break;
1087  case ISD::EXTRACT_ELEMENT:    ExpandRes_EXTRACT_ELEMENT(N, Lo, Hi); break;
1088  case ISD::EXTRACT_VECTOR_ELT: ExpandRes_EXTRACT_VECTOR_ELT(N, Lo, Hi); break;
1089  case ISD::VAARG:              ExpandRes_VAARG(N, Lo, Hi); break;
1090
1091  case ISD::ANY_EXTEND:  ExpandIntRes_ANY_EXTEND(N, Lo, Hi); break;
1092  case ISD::AssertSext:  ExpandIntRes_AssertSext(N, Lo, Hi); break;
1093  case ISD::AssertZext:  ExpandIntRes_AssertZext(N, Lo, Hi); break;
1094  case ISD::BSWAP:       ExpandIntRes_BSWAP(N, Lo, Hi); break;
1095  case ISD::Constant:    ExpandIntRes_Constant(N, Lo, Hi); break;
1096  case ISD::CTLZ:        ExpandIntRes_CTLZ(N, Lo, Hi); break;
1097  case ISD::CTPOP:       ExpandIntRes_CTPOP(N, Lo, Hi); break;
1098  case ISD::CTTZ:        ExpandIntRes_CTTZ(N, Lo, Hi); break;
1099  case ISD::FP_TO_SINT:  ExpandIntRes_FP_TO_SINT(N, Lo, Hi); break;
1100  case ISD::FP_TO_UINT:  ExpandIntRes_FP_TO_UINT(N, Lo, Hi); break;
1101  case ISD::LOAD:        ExpandIntRes_LOAD(cast<LoadSDNode>(N), Lo, Hi); break;
1102  case ISD::MUL:         ExpandIntRes_MUL(N, Lo, Hi); break;
1103  case ISD::SDIV:        ExpandIntRes_SDIV(N, Lo, Hi); break;
1104  case ISD::SIGN_EXTEND: ExpandIntRes_SIGN_EXTEND(N, Lo, Hi); break;
1105  case ISD::SIGN_EXTEND_INREG: ExpandIntRes_SIGN_EXTEND_INREG(N, Lo, Hi); break;
1106  case ISD::SREM:        ExpandIntRes_SREM(N, Lo, Hi); break;
1107  case ISD::TRUNCATE:    ExpandIntRes_TRUNCATE(N, Lo, Hi); break;
1108  case ISD::UDIV:        ExpandIntRes_UDIV(N, Lo, Hi); break;
1109  case ISD::UREM:        ExpandIntRes_UREM(N, Lo, Hi); break;
1110  case ISD::ZERO_EXTEND: ExpandIntRes_ZERO_EXTEND(N, Lo, Hi); break;
1111  case ISD::ATOMIC_LOAD: ExpandIntRes_ATOMIC_LOAD(N, Lo, Hi); break;
1112
1113  case ISD::ATOMIC_LOAD_ADD:
1114  case ISD::ATOMIC_LOAD_SUB:
1115  case ISD::ATOMIC_LOAD_AND:
1116  case ISD::ATOMIC_LOAD_OR:
1117  case ISD::ATOMIC_LOAD_XOR:
1118  case ISD::ATOMIC_LOAD_NAND:
1119  case ISD::ATOMIC_LOAD_MIN:
1120  case ISD::ATOMIC_LOAD_MAX:
1121  case ISD::ATOMIC_LOAD_UMIN:
1122  case ISD::ATOMIC_LOAD_UMAX:
1123  case ISD::ATOMIC_SWAP: {
1124    std::pair<SDValue, SDValue> Tmp = ExpandAtomic(N);
1125    SplitInteger(Tmp.first, Lo, Hi);
1126    ReplaceValueWith(SDValue(N, 1), Tmp.second);
1127    break;
1128  }
1129
1130  case ISD::AND:
1131  case ISD::OR:
1132  case ISD::XOR: ExpandIntRes_Logical(N, Lo, Hi); break;
1133
1134  case ISD::ADD:
1135  case ISD::SUB: ExpandIntRes_ADDSUB(N, Lo, Hi); break;
1136
1137  case ISD::ADDC:
1138  case ISD::SUBC: ExpandIntRes_ADDSUBC(N, Lo, Hi); break;
1139
1140  case ISD::ADDE:
1141  case ISD::SUBE: ExpandIntRes_ADDSUBE(N, Lo, Hi); break;
1142
1143  case ISD::SHL:
1144  case ISD::SRA:
1145  case ISD::SRL: ExpandIntRes_Shift(N, Lo, Hi); break;
1146
1147  case ISD::SADDO:
1148  case ISD::SSUBO: ExpandIntRes_SADDSUBO(N, Lo, Hi); break;
1149  case ISD::UADDO:
1150  case ISD::USUBO: ExpandIntRes_UADDSUBO(N, Lo, Hi); break;
1151  case ISD::UMULO:
1152  case ISD::SMULO: ExpandIntRes_XMULO(N, Lo, Hi); break;
1153  }
1154
1155  // If Lo/Hi is null, the sub-method took care of registering results etc.
1156  if (Lo.getNode())
1157    SetExpandedInteger(SDValue(N, ResNo), Lo, Hi);
1158}
1159
1160/// Lower an atomic node to the appropriate builtin call.
1161std::pair <SDValue, SDValue> DAGTypeLegalizer::ExpandAtomic(SDNode *Node) {
1162  unsigned Opc = Node->getOpcode();
1163  MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
1164  RTLIB::Libcall LC;
1165
1166  switch (Opc) {
1167  default:
1168    llvm_unreachable("Unhandled atomic intrinsic Expand!");
1169    break;
1170  case ISD::ATOMIC_SWAP:
1171    switch (VT.SimpleTy) {
1172    default: llvm_unreachable("Unexpected value type for atomic!");
1173    case MVT::i8:  LC = RTLIB::SYNC_LOCK_TEST_AND_SET_1; break;
1174    case MVT::i16: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_2; break;
1175    case MVT::i32: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_4; break;
1176    case MVT::i64: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_8; break;
1177    }
1178    break;
1179  case ISD::ATOMIC_CMP_SWAP:
1180    switch (VT.SimpleTy) {
1181    default: llvm_unreachable("Unexpected value type for atomic!");
1182    case MVT::i8:  LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_1; break;
1183    case MVT::i16: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_2; break;
1184    case MVT::i32: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_4; break;
1185    case MVT::i64: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_8; break;
1186    }
1187    break;
1188  case ISD::ATOMIC_LOAD_ADD:
1189    switch (VT.SimpleTy) {
1190    default: llvm_unreachable("Unexpected value type for atomic!");
1191    case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_ADD_1; break;
1192    case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_ADD_2; break;
1193    case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_ADD_4; break;
1194    case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_ADD_8; break;
1195    }
1196    break;
1197  case ISD::ATOMIC_LOAD_SUB:
1198    switch (VT.SimpleTy) {
1199    default: llvm_unreachable("Unexpected value type for atomic!");
1200    case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_SUB_1; break;
1201    case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_SUB_2; break;
1202    case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_SUB_4; break;
1203    case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_SUB_8; break;
1204    }
1205    break;
1206  case ISD::ATOMIC_LOAD_AND:
1207    switch (VT.SimpleTy) {
1208    default: llvm_unreachable("Unexpected value type for atomic!");
1209    case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_AND_1; break;
1210    case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_AND_2; break;
1211    case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_AND_4; break;
1212    case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_AND_8; break;
1213    }
1214    break;
1215  case ISD::ATOMIC_LOAD_OR:
1216    switch (VT.SimpleTy) {
1217    default: llvm_unreachable("Unexpected value type for atomic!");
1218    case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_OR_1; break;
1219    case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_OR_2; break;
1220    case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_OR_4; break;
1221    case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_OR_8; break;
1222    }
1223    break;
1224  case ISD::ATOMIC_LOAD_XOR:
1225    switch (VT.SimpleTy) {
1226    default: llvm_unreachable("Unexpected value type for atomic!");
1227    case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_XOR_1; break;
1228    case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_XOR_2; break;
1229    case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_XOR_4; break;
1230    case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_XOR_8; break;
1231    }
1232    break;
1233  case ISD::ATOMIC_LOAD_NAND:
1234    switch (VT.SimpleTy) {
1235    default: llvm_unreachable("Unexpected value type for atomic!");
1236    case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_NAND_1; break;
1237    case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_NAND_2; break;
1238    case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_NAND_4; break;
1239    case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_NAND_8; break;
1240    }
1241    break;
1242  }
1243
1244  return ExpandChainLibCall(LC, Node, false);
1245}
1246
1247/// ExpandShiftByConstant - N is a shift by a value that needs to be expanded,
1248/// and the shift amount is a constant 'Amt'.  Expand the operation.
1249void DAGTypeLegalizer::ExpandShiftByConstant(SDNode *N, unsigned Amt,
1250                                             SDValue &Lo, SDValue &Hi) {
1251  DebugLoc DL = N->getDebugLoc();
1252  // Expand the incoming operand to be shifted, so that we have its parts
1253  SDValue InL, InH;
1254  GetExpandedInteger(N->getOperand(0), InL, InH);
1255
1256  EVT NVT = InL.getValueType();
1257  unsigned VTBits = N->getValueType(0).getSizeInBits();
1258  unsigned NVTBits = NVT.getSizeInBits();
1259  EVT ShTy = N->getOperand(1).getValueType();
1260
1261  if (N->getOpcode() == ISD::SHL) {
1262    if (Amt > VTBits) {
1263      Lo = Hi = DAG.getConstant(0, NVT);
1264    } else if (Amt > NVTBits) {
1265      Lo = DAG.getConstant(0, NVT);
1266      Hi = DAG.getNode(ISD::SHL, DL,
1267                       NVT, InL, DAG.getConstant(Amt-NVTBits, ShTy));
1268    } else if (Amt == NVTBits) {
1269      Lo = DAG.getConstant(0, NVT);
1270      Hi = InL;
1271    } else if (Amt == 1 &&
1272               TLI.isOperationLegalOrCustom(ISD::ADDC,
1273                              TLI.getTypeToExpandTo(*DAG.getContext(), NVT))) {
1274      // Emit this X << 1 as X+X.
1275      SDVTList VTList = DAG.getVTList(NVT, MVT::Glue);
1276      SDValue LoOps[2] = { InL, InL };
1277      Lo = DAG.getNode(ISD::ADDC, DL, VTList, LoOps, 2);
1278      SDValue HiOps[3] = { InH, InH, Lo.getValue(1) };
1279      Hi = DAG.getNode(ISD::ADDE, DL, VTList, HiOps, 3);
1280    } else {
1281      Lo = DAG.getNode(ISD::SHL, DL, NVT, InL, DAG.getConstant(Amt, ShTy));
1282      Hi = DAG.getNode(ISD::OR, DL, NVT,
1283                       DAG.getNode(ISD::SHL, DL, NVT, InH,
1284                                   DAG.getConstant(Amt, ShTy)),
1285                       DAG.getNode(ISD::SRL, DL, NVT, InL,
1286                                   DAG.getConstant(NVTBits-Amt, ShTy)));
1287    }
1288    return;
1289  }
1290
1291  if (N->getOpcode() == ISD::SRL) {
1292    if (Amt > VTBits) {
1293      Lo = DAG.getConstant(0, NVT);
1294      Hi = DAG.getConstant(0, NVT);
1295    } else if (Amt > NVTBits) {
1296      Lo = DAG.getNode(ISD::SRL, DL,
1297                       NVT, InH, DAG.getConstant(Amt-NVTBits,ShTy));
1298      Hi = DAG.getConstant(0, NVT);
1299    } else if (Amt == NVTBits) {
1300      Lo = InH;
1301      Hi = DAG.getConstant(0, NVT);
1302    } else {
1303      Lo = DAG.getNode(ISD::OR, DL, NVT,
1304                       DAG.getNode(ISD::SRL, DL, NVT, InL,
1305                                   DAG.getConstant(Amt, ShTy)),
1306                       DAG.getNode(ISD::SHL, DL, NVT, InH,
1307                                   DAG.getConstant(NVTBits-Amt, ShTy)));
1308      Hi = DAG.getNode(ISD::SRL, DL, NVT, InH, DAG.getConstant(Amt, ShTy));
1309    }
1310    return;
1311  }
1312
1313  assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
1314  if (Amt > VTBits) {
1315    Hi = Lo = DAG.getNode(ISD::SRA, DL, NVT, InH,
1316                          DAG.getConstant(NVTBits-1, ShTy));
1317  } else if (Amt > NVTBits) {
1318    Lo = DAG.getNode(ISD::SRA, DL, NVT, InH,
1319                     DAG.getConstant(Amt-NVTBits, ShTy));
1320    Hi = DAG.getNode(ISD::SRA, DL, NVT, InH,
1321                     DAG.getConstant(NVTBits-1, ShTy));
1322  } else if (Amt == NVTBits) {
1323    Lo = InH;
1324    Hi = DAG.getNode(ISD::SRA, DL, NVT, InH,
1325                     DAG.getConstant(NVTBits-1, ShTy));
1326  } else {
1327    Lo = DAG.getNode(ISD::OR, DL, NVT,
1328                     DAG.getNode(ISD::SRL, DL, NVT, InL,
1329                                 DAG.getConstant(Amt, ShTy)),
1330                     DAG.getNode(ISD::SHL, DL, NVT, InH,
1331                                 DAG.getConstant(NVTBits-Amt, ShTy)));
1332    Hi = DAG.getNode(ISD::SRA, DL, NVT, InH, DAG.getConstant(Amt, ShTy));
1333  }
1334}
1335
1336/// ExpandShiftWithKnownAmountBit - Try to determine whether we can simplify
1337/// this shift based on knowledge of the high bit of the shift amount.  If we
1338/// can tell this, we know that it is >= 32 or < 32, without knowing the actual
1339/// shift amount.
1340bool DAGTypeLegalizer::
1341ExpandShiftWithKnownAmountBit(SDNode *N, SDValue &Lo, SDValue &Hi) {
1342  SDValue Amt = N->getOperand(1);
1343  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1344  EVT ShTy = Amt.getValueType();
1345  unsigned ShBits = ShTy.getScalarType().getSizeInBits();
1346  unsigned NVTBits = NVT.getScalarType().getSizeInBits();
1347  assert(isPowerOf2_32(NVTBits) &&
1348         "Expanded integer type size not a power of two!");
1349  DebugLoc dl = N->getDebugLoc();
1350
1351  APInt HighBitMask = APInt::getHighBitsSet(ShBits, ShBits - Log2_32(NVTBits));
1352  APInt KnownZero, KnownOne;
1353  DAG.ComputeMaskedBits(N->getOperand(1), HighBitMask, KnownZero, KnownOne);
1354
1355  // If we don't know anything about the high bits, exit.
1356  if (((KnownZero|KnownOne) & HighBitMask) == 0)
1357    return false;
1358
1359  // Get the incoming operand to be shifted.
1360  SDValue InL, InH;
1361  GetExpandedInteger(N->getOperand(0), InL, InH);
1362
1363  // If we know that any of the high bits of the shift amount are one, then we
1364  // can do this as a couple of simple shifts.
1365  if (KnownOne.intersects(HighBitMask)) {
1366    // Mask out the high bit, which we know is set.
1367    Amt = DAG.getNode(ISD::AND, dl, ShTy, Amt,
1368                      DAG.getConstant(~HighBitMask, ShTy));
1369
1370    switch (N->getOpcode()) {
1371    default: llvm_unreachable("Unknown shift");
1372    case ISD::SHL:
1373      Lo = DAG.getConstant(0, NVT);              // Low part is zero.
1374      Hi = DAG.getNode(ISD::SHL, dl, NVT, InL, Amt); // High part from Lo part.
1375      return true;
1376    case ISD::SRL:
1377      Hi = DAG.getConstant(0, NVT);              // Hi part is zero.
1378      Lo = DAG.getNode(ISD::SRL, dl, NVT, InH, Amt); // Lo part from Hi part.
1379      return true;
1380    case ISD::SRA:
1381      Hi = DAG.getNode(ISD::SRA, dl, NVT, InH,       // Sign extend high part.
1382                       DAG.getConstant(NVTBits-1, ShTy));
1383      Lo = DAG.getNode(ISD::SRA, dl, NVT, InH, Amt); // Lo part from Hi part.
1384      return true;
1385    }
1386  }
1387
1388#if 0
1389  // FIXME: This code is broken for shifts with a zero amount!
1390  // If we know that all of the high bits of the shift amount are zero, then we
1391  // can do this as a couple of simple shifts.
1392  if ((KnownZero & HighBitMask) == HighBitMask) {
1393    // Compute 32-amt.
1394    SDValue Amt2 = DAG.getNode(ISD::SUB, ShTy,
1395                                 DAG.getConstant(NVTBits, ShTy),
1396                                 Amt);
1397    unsigned Op1, Op2;
1398    switch (N->getOpcode()) {
1399    default: llvm_unreachable("Unknown shift");
1400    case ISD::SHL:  Op1 = ISD::SHL; Op2 = ISD::SRL; break;
1401    case ISD::SRL:
1402    case ISD::SRA:  Op1 = ISD::SRL; Op2 = ISD::SHL; break;
1403    }
1404
1405    Lo = DAG.getNode(N->getOpcode(), NVT, InL, Amt);
1406    Hi = DAG.getNode(ISD::OR, NVT,
1407                     DAG.getNode(Op1, NVT, InH, Amt),
1408                     DAG.getNode(Op2, NVT, InL, Amt2));
1409    return true;
1410  }
1411#endif
1412
1413  return false;
1414}
1415
1416/// ExpandShiftWithUnknownAmountBit - Fully general expansion of integer shift
1417/// of any size.
1418bool DAGTypeLegalizer::
1419ExpandShiftWithUnknownAmountBit(SDNode *N, SDValue &Lo, SDValue &Hi) {
1420  SDValue Amt = N->getOperand(1);
1421  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1422  EVT ShTy = Amt.getValueType();
1423  unsigned NVTBits = NVT.getSizeInBits();
1424  assert(isPowerOf2_32(NVTBits) &&
1425         "Expanded integer type size not a power of two!");
1426  DebugLoc dl = N->getDebugLoc();
1427
1428  // Get the incoming operand to be shifted.
1429  SDValue InL, InH;
1430  GetExpandedInteger(N->getOperand(0), InL, InH);
1431
1432  SDValue NVBitsNode = DAG.getConstant(NVTBits, ShTy);
1433  SDValue AmtExcess = DAG.getNode(ISD::SUB, dl, ShTy, Amt, NVBitsNode);
1434  SDValue AmtLack = DAG.getNode(ISD::SUB, dl, ShTy, NVBitsNode, Amt);
1435  SDValue isShort = DAG.getSetCC(dl, TLI.getSetCCResultType(ShTy),
1436                                 Amt, NVBitsNode, ISD::SETULT);
1437
1438  SDValue LoS, HiS, LoL, HiL;
1439  switch (N->getOpcode()) {
1440  default: llvm_unreachable("Unknown shift");
1441  case ISD::SHL:
1442    // Short: ShAmt < NVTBits
1443    LoS = DAG.getNode(ISD::SHL, dl, NVT, InL, Amt);
1444    HiS = DAG.getNode(ISD::OR, dl, NVT,
1445                      DAG.getNode(ISD::SHL, dl, NVT, InH, Amt),
1446    // FIXME: If Amt is zero, the following shift generates an undefined result
1447    // on some architectures.
1448                      DAG.getNode(ISD::SRL, dl, NVT, InL, AmtLack));
1449
1450    // Long: ShAmt >= NVTBits
1451    LoL = DAG.getConstant(0, NVT);                        // Lo part is zero.
1452    HiL = DAG.getNode(ISD::SHL, dl, NVT, InL, AmtExcess); // Hi from Lo part.
1453
1454    Lo = DAG.getNode(ISD::SELECT, dl, NVT, isShort, LoS, LoL);
1455    Hi = DAG.getNode(ISD::SELECT, dl, NVT, isShort, HiS, HiL);
1456    return true;
1457  case ISD::SRL:
1458    // Short: ShAmt < NVTBits
1459    HiS = DAG.getNode(ISD::SRL, dl, NVT, InH, Amt);
1460    LoS = DAG.getNode(ISD::OR, dl, NVT,
1461                      DAG.getNode(ISD::SRL, dl, NVT, InL, Amt),
1462    // FIXME: If Amt is zero, the following shift generates an undefined result
1463    // on some architectures.
1464                      DAG.getNode(ISD::SHL, dl, NVT, InH, AmtLack));
1465
1466    // Long: ShAmt >= NVTBits
1467    HiL = DAG.getConstant(0, NVT);                        // Hi part is zero.
1468    LoL = DAG.getNode(ISD::SRL, dl, NVT, InH, AmtExcess); // Lo from Hi part.
1469
1470    Lo = DAG.getNode(ISD::SELECT, dl, NVT, isShort, LoS, LoL);
1471    Hi = DAG.getNode(ISD::SELECT, dl, NVT, isShort, HiS, HiL);
1472    return true;
1473  case ISD::SRA:
1474    // Short: ShAmt < NVTBits
1475    HiS = DAG.getNode(ISD::SRA, dl, NVT, InH, Amt);
1476    LoS = DAG.getNode(ISD::OR, dl, NVT,
1477                      DAG.getNode(ISD::SRL, dl, NVT, InL, Amt),
1478    // FIXME: If Amt is zero, the following shift generates an undefined result
1479    // on some architectures.
1480                      DAG.getNode(ISD::SHL, dl, NVT, InH, AmtLack));
1481
1482    // Long: ShAmt >= NVTBits
1483    HiL = DAG.getNode(ISD::SRA, dl, NVT, InH,             // Sign of Hi part.
1484                      DAG.getConstant(NVTBits-1, ShTy));
1485    LoL = DAG.getNode(ISD::SRA, dl, NVT, InH, AmtExcess); // Lo from Hi part.
1486
1487    Lo = DAG.getNode(ISD::SELECT, dl, NVT, isShort, LoS, LoL);
1488    Hi = DAG.getNode(ISD::SELECT, dl, NVT, isShort, HiS, HiL);
1489    return true;
1490  }
1491
1492  return false;
1493}
1494
1495void DAGTypeLegalizer::ExpandIntRes_ADDSUB(SDNode *N,
1496                                           SDValue &Lo, SDValue &Hi) {
1497  DebugLoc dl = N->getDebugLoc();
1498  // Expand the subcomponents.
1499  SDValue LHSL, LHSH, RHSL, RHSH;
1500  GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1501  GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1502
1503  EVT NVT = LHSL.getValueType();
1504  SDValue LoOps[2] = { LHSL, RHSL };
1505  SDValue HiOps[3] = { LHSH, RHSH };
1506
1507  // Do not generate ADDC/ADDE or SUBC/SUBE if the target does not support
1508  // them.  TODO: Teach operation legalization how to expand unsupported
1509  // ADDC/ADDE/SUBC/SUBE.  The problem is that these operations generate
1510  // a carry of type MVT::Glue, but there doesn't seem to be any way to
1511  // generate a value of this type in the expanded code sequence.
1512  bool hasCarry =
1513    TLI.isOperationLegalOrCustom(N->getOpcode() == ISD::ADD ?
1514                                   ISD::ADDC : ISD::SUBC,
1515                                 TLI.getTypeToExpandTo(*DAG.getContext(), NVT));
1516
1517  if (hasCarry) {
1518    SDVTList VTList = DAG.getVTList(NVT, MVT::Glue);
1519    if (N->getOpcode() == ISD::ADD) {
1520      Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps, 2);
1521      HiOps[2] = Lo.getValue(1);
1522      Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps, 3);
1523    } else {
1524      Lo = DAG.getNode(ISD::SUBC, dl, VTList, LoOps, 2);
1525      HiOps[2] = Lo.getValue(1);
1526      Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps, 3);
1527    }
1528    return;
1529  }
1530
1531  if (N->getOpcode() == ISD::ADD) {
1532    Lo = DAG.getNode(ISD::ADD, dl, NVT, LoOps, 2);
1533    Hi = DAG.getNode(ISD::ADD, dl, NVT, HiOps, 2);
1534    SDValue Cmp1 = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), Lo, LoOps[0],
1535                                ISD::SETULT);
1536    SDValue Carry1 = DAG.getNode(ISD::SELECT, dl, NVT, Cmp1,
1537                                 DAG.getConstant(1, NVT),
1538                                 DAG.getConstant(0, NVT));
1539    SDValue Cmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), Lo, LoOps[1],
1540                                ISD::SETULT);
1541    SDValue Carry2 = DAG.getNode(ISD::SELECT, dl, NVT, Cmp2,
1542                                 DAG.getConstant(1, NVT), Carry1);
1543    Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, Carry2);
1544  } else {
1545    Lo = DAG.getNode(ISD::SUB, dl, NVT, LoOps, 2);
1546    Hi = DAG.getNode(ISD::SUB, dl, NVT, HiOps, 2);
1547    SDValue Cmp =
1548      DAG.getSetCC(dl, TLI.getSetCCResultType(LoOps[0].getValueType()),
1549                   LoOps[0], LoOps[1], ISD::SETULT);
1550    SDValue Borrow = DAG.getNode(ISD::SELECT, dl, NVT, Cmp,
1551                                 DAG.getConstant(1, NVT),
1552                                 DAG.getConstant(0, NVT));
1553    Hi = DAG.getNode(ISD::SUB, dl, NVT, Hi, Borrow);
1554  }
1555}
1556
1557void DAGTypeLegalizer::ExpandIntRes_ADDSUBC(SDNode *N,
1558                                            SDValue &Lo, SDValue &Hi) {
1559  // Expand the subcomponents.
1560  SDValue LHSL, LHSH, RHSL, RHSH;
1561  DebugLoc dl = N->getDebugLoc();
1562  GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1563  GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1564  SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Glue);
1565  SDValue LoOps[2] = { LHSL, RHSL };
1566  SDValue HiOps[3] = { LHSH, RHSH };
1567
1568  if (N->getOpcode() == ISD::ADDC) {
1569    Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps, 2);
1570    HiOps[2] = Lo.getValue(1);
1571    Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps, 3);
1572  } else {
1573    Lo = DAG.getNode(ISD::SUBC, dl, VTList, LoOps, 2);
1574    HiOps[2] = Lo.getValue(1);
1575    Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps, 3);
1576  }
1577
1578  // Legalized the flag result - switch anything that used the old flag to
1579  // use the new one.
1580  ReplaceValueWith(SDValue(N, 1), Hi.getValue(1));
1581}
1582
1583void DAGTypeLegalizer::ExpandIntRes_ADDSUBE(SDNode *N,
1584                                            SDValue &Lo, SDValue &Hi) {
1585  // Expand the subcomponents.
1586  SDValue LHSL, LHSH, RHSL, RHSH;
1587  DebugLoc dl = N->getDebugLoc();
1588  GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1589  GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1590  SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Glue);
1591  SDValue LoOps[3] = { LHSL, RHSL, N->getOperand(2) };
1592  SDValue HiOps[3] = { LHSH, RHSH };
1593
1594  Lo = DAG.getNode(N->getOpcode(), dl, VTList, LoOps, 3);
1595  HiOps[2] = Lo.getValue(1);
1596  Hi = DAG.getNode(N->getOpcode(), dl, VTList, HiOps, 3);
1597
1598  // Legalized the flag result - switch anything that used the old flag to
1599  // use the new one.
1600  ReplaceValueWith(SDValue(N, 1), Hi.getValue(1));
1601}
1602
1603void DAGTypeLegalizer::ExpandIntRes_MERGE_VALUES(SDNode *N,
1604                                                 SDValue &Lo, SDValue &Hi) {
1605  SDValue Res = DecomposeMERGE_VALUES(N);
1606  SplitInteger(Res, Lo, Hi);
1607}
1608
1609void DAGTypeLegalizer::ExpandIntRes_ANY_EXTEND(SDNode *N,
1610                                               SDValue &Lo, SDValue &Hi) {
1611  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1612  DebugLoc dl = N->getDebugLoc();
1613  SDValue Op = N->getOperand(0);
1614  if (Op.getValueType().bitsLE(NVT)) {
1615    // The low part is any extension of the input (which degenerates to a copy).
1616    Lo = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Op);
1617    Hi = DAG.getUNDEF(NVT);   // The high part is undefined.
1618  } else {
1619    // For example, extension of an i48 to an i64.  The operand type necessarily
1620    // promotes to the result type, so will end up being expanded too.
1621    assert(getTypeAction(Op.getValueType()) ==
1622           TargetLowering::TypePromoteInteger &&
1623           "Only know how to promote this result!");
1624    SDValue Res = GetPromotedInteger(Op);
1625    assert(Res.getValueType() == N->getValueType(0) &&
1626           "Operand over promoted?");
1627    // Split the promoted operand.  This will simplify when it is expanded.
1628    SplitInteger(Res, Lo, Hi);
1629  }
1630}
1631
1632void DAGTypeLegalizer::ExpandIntRes_AssertSext(SDNode *N,
1633                                               SDValue &Lo, SDValue &Hi) {
1634  DebugLoc dl = N->getDebugLoc();
1635  GetExpandedInteger(N->getOperand(0), Lo, Hi);
1636  EVT NVT = Lo.getValueType();
1637  EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1638  unsigned NVTBits = NVT.getSizeInBits();
1639  unsigned EVTBits = EVT.getSizeInBits();
1640
1641  if (NVTBits < EVTBits) {
1642    Hi = DAG.getNode(ISD::AssertSext, dl, NVT, Hi,
1643                     DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
1644                                                        EVTBits - NVTBits)));
1645  } else {
1646    Lo = DAG.getNode(ISD::AssertSext, dl, NVT, Lo, DAG.getValueType(EVT));
1647    // The high part replicates the sign bit of Lo, make it explicit.
1648    Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
1649                     DAG.getConstant(NVTBits-1, TLI.getPointerTy()));
1650  }
1651}
1652
1653void DAGTypeLegalizer::ExpandIntRes_AssertZext(SDNode *N,
1654                                               SDValue &Lo, SDValue &Hi) {
1655  DebugLoc dl = N->getDebugLoc();
1656  GetExpandedInteger(N->getOperand(0), Lo, Hi);
1657  EVT NVT = Lo.getValueType();
1658  EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1659  unsigned NVTBits = NVT.getSizeInBits();
1660  unsigned EVTBits = EVT.getSizeInBits();
1661
1662  if (NVTBits < EVTBits) {
1663    Hi = DAG.getNode(ISD::AssertZext, dl, NVT, Hi,
1664                     DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
1665                                                        EVTBits - NVTBits)));
1666  } else {
1667    Lo = DAG.getNode(ISD::AssertZext, dl, NVT, Lo, DAG.getValueType(EVT));
1668    // The high part must be zero, make it explicit.
1669    Hi = DAG.getConstant(0, NVT);
1670  }
1671}
1672
1673void DAGTypeLegalizer::ExpandIntRes_BSWAP(SDNode *N,
1674                                          SDValue &Lo, SDValue &Hi) {
1675  DebugLoc dl = N->getDebugLoc();
1676  GetExpandedInteger(N->getOperand(0), Hi, Lo);  // Note swapped operands.
1677  Lo = DAG.getNode(ISD::BSWAP, dl, Lo.getValueType(), Lo);
1678  Hi = DAG.getNode(ISD::BSWAP, dl, Hi.getValueType(), Hi);
1679}
1680
1681void DAGTypeLegalizer::ExpandIntRes_Constant(SDNode *N,
1682                                             SDValue &Lo, SDValue &Hi) {
1683  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1684  unsigned NBitWidth = NVT.getSizeInBits();
1685  const APInt &Cst = cast<ConstantSDNode>(N)->getAPIntValue();
1686  Lo = DAG.getConstant(Cst.trunc(NBitWidth), NVT);
1687  Hi = DAG.getConstant(Cst.lshr(NBitWidth).trunc(NBitWidth), NVT);
1688}
1689
1690void DAGTypeLegalizer::ExpandIntRes_CTLZ(SDNode *N,
1691                                         SDValue &Lo, SDValue &Hi) {
1692  DebugLoc dl = N->getDebugLoc();
1693  // ctlz (HiLo) -> Hi != 0 ? ctlz(Hi) : (ctlz(Lo)+32)
1694  GetExpandedInteger(N->getOperand(0), Lo, Hi);
1695  EVT NVT = Lo.getValueType();
1696
1697  SDValue HiNotZero = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), Hi,
1698                                   DAG.getConstant(0, NVT), ISD::SETNE);
1699
1700  SDValue LoLZ = DAG.getNode(ISD::CTLZ, dl, NVT, Lo);
1701  SDValue HiLZ = DAG.getNode(ISD::CTLZ, dl, NVT, Hi);
1702
1703  Lo = DAG.getNode(ISD::SELECT, dl, NVT, HiNotZero, HiLZ,
1704                   DAG.getNode(ISD::ADD, dl, NVT, LoLZ,
1705                               DAG.getConstant(NVT.getSizeInBits(), NVT)));
1706  Hi = DAG.getConstant(0, NVT);
1707}
1708
1709void DAGTypeLegalizer::ExpandIntRes_CTPOP(SDNode *N,
1710                                          SDValue &Lo, SDValue &Hi) {
1711  DebugLoc dl = N->getDebugLoc();
1712  // ctpop(HiLo) -> ctpop(Hi)+ctpop(Lo)
1713  GetExpandedInteger(N->getOperand(0), Lo, Hi);
1714  EVT NVT = Lo.getValueType();
1715  Lo = DAG.getNode(ISD::ADD, dl, NVT, DAG.getNode(ISD::CTPOP, dl, NVT, Lo),
1716                   DAG.getNode(ISD::CTPOP, dl, NVT, Hi));
1717  Hi = DAG.getConstant(0, NVT);
1718}
1719
1720void DAGTypeLegalizer::ExpandIntRes_CTTZ(SDNode *N,
1721                                         SDValue &Lo, SDValue &Hi) {
1722  DebugLoc dl = N->getDebugLoc();
1723  // cttz (HiLo) -> Lo != 0 ? cttz(Lo) : (cttz(Hi)+32)
1724  GetExpandedInteger(N->getOperand(0), Lo, Hi);
1725  EVT NVT = Lo.getValueType();
1726
1727  SDValue LoNotZero = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), Lo,
1728                                   DAG.getConstant(0, NVT), ISD::SETNE);
1729
1730  SDValue LoLZ = DAG.getNode(ISD::CTTZ, dl, NVT, Lo);
1731  SDValue HiLZ = DAG.getNode(ISD::CTTZ, dl, NVT, Hi);
1732
1733  Lo = DAG.getNode(ISD::SELECT, dl, NVT, LoNotZero, LoLZ,
1734                   DAG.getNode(ISD::ADD, dl, NVT, HiLZ,
1735                               DAG.getConstant(NVT.getSizeInBits(), NVT)));
1736  Hi = DAG.getConstant(0, NVT);
1737}
1738
1739void DAGTypeLegalizer::ExpandIntRes_FP_TO_SINT(SDNode *N, SDValue &Lo,
1740                                               SDValue &Hi) {
1741  DebugLoc dl = N->getDebugLoc();
1742  EVT VT = N->getValueType(0);
1743  SDValue Op = N->getOperand(0);
1744  RTLIB::Libcall LC = RTLIB::getFPTOSINT(Op.getValueType(), VT);
1745  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-sint conversion!");
1746  SplitInteger(MakeLibCall(LC, VT, &Op, 1, true/*irrelevant*/, dl), Lo, Hi);
1747}
1748
1749void DAGTypeLegalizer::ExpandIntRes_FP_TO_UINT(SDNode *N, SDValue &Lo,
1750                                               SDValue &Hi) {
1751  DebugLoc dl = N->getDebugLoc();
1752  EVT VT = N->getValueType(0);
1753  SDValue Op = N->getOperand(0);
1754  RTLIB::Libcall LC = RTLIB::getFPTOUINT(Op.getValueType(), VT);
1755  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-uint conversion!");
1756  SplitInteger(MakeLibCall(LC, VT, &Op, 1, false/*irrelevant*/, dl), Lo, Hi);
1757}
1758
1759void DAGTypeLegalizer::ExpandIntRes_LOAD(LoadSDNode *N,
1760                                         SDValue &Lo, SDValue &Hi) {
1761  if (ISD::isNormalLoad(N)) {
1762    ExpandRes_NormalLoad(N, Lo, Hi);
1763    return;
1764  }
1765
1766  assert(ISD::isUNINDEXEDLoad(N) && "Indexed load during type legalization!");
1767
1768  EVT VT = N->getValueType(0);
1769  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
1770  SDValue Ch  = N->getChain();
1771  SDValue Ptr = N->getBasePtr();
1772  ISD::LoadExtType ExtType = N->getExtensionType();
1773  unsigned Alignment = N->getAlignment();
1774  bool isVolatile = N->isVolatile();
1775  bool isNonTemporal = N->isNonTemporal();
1776  DebugLoc dl = N->getDebugLoc();
1777
1778  assert(NVT.isByteSized() && "Expanded type not byte sized!");
1779
1780  if (N->getMemoryVT().bitsLE(NVT)) {
1781    EVT MemVT = N->getMemoryVT();
1782
1783    Lo = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr, N->getPointerInfo(),
1784                        MemVT, isVolatile, isNonTemporal, Alignment);
1785
1786    // Remember the chain.
1787    Ch = Lo.getValue(1);
1788
1789    if (ExtType == ISD::SEXTLOAD) {
1790      // The high part is obtained by SRA'ing all but one of the bits of the
1791      // lo part.
1792      unsigned LoSize = Lo.getValueType().getSizeInBits();
1793      Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
1794                       DAG.getConstant(LoSize-1, TLI.getPointerTy()));
1795    } else if (ExtType == ISD::ZEXTLOAD) {
1796      // The high part is just a zero.
1797      Hi = DAG.getConstant(0, NVT);
1798    } else {
1799      assert(ExtType == ISD::EXTLOAD && "Unknown extload!");
1800      // The high part is undefined.
1801      Hi = DAG.getUNDEF(NVT);
1802    }
1803  } else if (TLI.isLittleEndian()) {
1804    // Little-endian - low bits are at low addresses.
1805    Lo = DAG.getLoad(NVT, dl, Ch, Ptr, N->getPointerInfo(),
1806                     isVolatile, isNonTemporal, Alignment);
1807
1808    unsigned ExcessBits =
1809      N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
1810    EVT NEVT = EVT::getIntegerVT(*DAG.getContext(), ExcessBits);
1811
1812    // Increment the pointer to the other half.
1813    unsigned IncrementSize = NVT.getSizeInBits()/8;
1814    Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
1815                      DAG.getIntPtrConstant(IncrementSize));
1816    Hi = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr,
1817                        N->getPointerInfo().getWithOffset(IncrementSize), NEVT,
1818                        isVolatile, isNonTemporal,
1819                        MinAlign(Alignment, IncrementSize));
1820
1821    // Build a factor node to remember that this load is independent of the
1822    // other one.
1823    Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1824                     Hi.getValue(1));
1825  } else {
1826    // Big-endian - high bits are at low addresses.  Favor aligned loads at
1827    // the cost of some bit-fiddling.
1828    EVT MemVT = N->getMemoryVT();
1829    unsigned EBytes = MemVT.getStoreSize();
1830    unsigned IncrementSize = NVT.getSizeInBits()/8;
1831    unsigned ExcessBits = (EBytes - IncrementSize)*8;
1832
1833    // Load both the high bits and maybe some of the low bits.
1834    Hi = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr, N->getPointerInfo(),
1835                        EVT::getIntegerVT(*DAG.getContext(),
1836                                          MemVT.getSizeInBits() - ExcessBits),
1837                        isVolatile, isNonTemporal, Alignment);
1838
1839    // Increment the pointer to the other half.
1840    Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
1841                      DAG.getIntPtrConstant(IncrementSize));
1842    // Load the rest of the low bits.
1843    Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, NVT, Ch, Ptr,
1844                        N->getPointerInfo().getWithOffset(IncrementSize),
1845                        EVT::getIntegerVT(*DAG.getContext(), ExcessBits),
1846                        isVolatile, isNonTemporal,
1847                        MinAlign(Alignment, IncrementSize));
1848
1849    // Build a factor node to remember that this load is independent of the
1850    // other one.
1851    Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1852                     Hi.getValue(1));
1853
1854    if (ExcessBits < NVT.getSizeInBits()) {
1855      // Transfer low bits from the bottom of Hi to the top of Lo.
1856      Lo = DAG.getNode(ISD::OR, dl, NVT, Lo,
1857                       DAG.getNode(ISD::SHL, dl, NVT, Hi,
1858                                   DAG.getConstant(ExcessBits,
1859                                                   TLI.getPointerTy())));
1860      // Move high bits to the right position in Hi.
1861      Hi = DAG.getNode(ExtType == ISD::SEXTLOAD ? ISD::SRA : ISD::SRL, dl,
1862                       NVT, Hi,
1863                       DAG.getConstant(NVT.getSizeInBits() - ExcessBits,
1864                                       TLI.getPointerTy()));
1865    }
1866  }
1867
1868  // Legalized the chain result - switch anything that used the old chain to
1869  // use the new one.
1870  ReplaceValueWith(SDValue(N, 1), Ch);
1871}
1872
1873void DAGTypeLegalizer::ExpandIntRes_Logical(SDNode *N,
1874                                            SDValue &Lo, SDValue &Hi) {
1875  DebugLoc dl = N->getDebugLoc();
1876  SDValue LL, LH, RL, RH;
1877  GetExpandedInteger(N->getOperand(0), LL, LH);
1878  GetExpandedInteger(N->getOperand(1), RL, RH);
1879  Lo = DAG.getNode(N->getOpcode(), dl, LL.getValueType(), LL, RL);
1880  Hi = DAG.getNode(N->getOpcode(), dl, LL.getValueType(), LH, RH);
1881}
1882
1883void DAGTypeLegalizer::ExpandIntRes_MUL(SDNode *N,
1884                                        SDValue &Lo, SDValue &Hi) {
1885  EVT VT = N->getValueType(0);
1886  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
1887  DebugLoc dl = N->getDebugLoc();
1888
1889  bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, NVT);
1890  bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, NVT);
1891  bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, NVT);
1892  bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, NVT);
1893  if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
1894    SDValue LL, LH, RL, RH;
1895    GetExpandedInteger(N->getOperand(0), LL, LH);
1896    GetExpandedInteger(N->getOperand(1), RL, RH);
1897    unsigned OuterBitSize = VT.getSizeInBits();
1898    unsigned InnerBitSize = NVT.getSizeInBits();
1899    unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0));
1900    unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1));
1901
1902    APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
1903    if (DAG.MaskedValueIsZero(N->getOperand(0), HighMask) &&
1904        DAG.MaskedValueIsZero(N->getOperand(1), HighMask)) {
1905      // The inputs are both zero-extended.
1906      if (HasUMUL_LOHI) {
1907        // We can emit a umul_lohi.
1908        Lo = DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(NVT, NVT), LL, RL);
1909        Hi = SDValue(Lo.getNode(), 1);
1910        return;
1911      }
1912      if (HasMULHU) {
1913        // We can emit a mulhu+mul.
1914        Lo = DAG.getNode(ISD::MUL, dl, NVT, LL, RL);
1915        Hi = DAG.getNode(ISD::MULHU, dl, NVT, LL, RL);
1916        return;
1917      }
1918    }
1919    if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
1920      // The input values are both sign-extended.
1921      if (HasSMUL_LOHI) {
1922        // We can emit a smul_lohi.
1923        Lo = DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(NVT, NVT), LL, RL);
1924        Hi = SDValue(Lo.getNode(), 1);
1925        return;
1926      }
1927      if (HasMULHS) {
1928        // We can emit a mulhs+mul.
1929        Lo = DAG.getNode(ISD::MUL, dl, NVT, LL, RL);
1930        Hi = DAG.getNode(ISD::MULHS, dl, NVT, LL, RL);
1931        return;
1932      }
1933    }
1934    if (HasUMUL_LOHI) {
1935      // Lo,Hi = umul LHS, RHS.
1936      SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI, dl,
1937                                       DAG.getVTList(NVT, NVT), LL, RL);
1938      Lo = UMulLOHI;
1939      Hi = UMulLOHI.getValue(1);
1940      RH = DAG.getNode(ISD::MUL, dl, NVT, LL, RH);
1941      LH = DAG.getNode(ISD::MUL, dl, NVT, LH, RL);
1942      Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, RH);
1943      Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, LH);
1944      return;
1945    }
1946    if (HasMULHU) {
1947      Lo = DAG.getNode(ISD::MUL, dl, NVT, LL, RL);
1948      Hi = DAG.getNode(ISD::MULHU, dl, NVT, LL, RL);
1949      RH = DAG.getNode(ISD::MUL, dl, NVT, LL, RH);
1950      LH = DAG.getNode(ISD::MUL, dl, NVT, LH, RL);
1951      Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, RH);
1952      Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, LH);
1953      return;
1954    }
1955  }
1956
1957  // If nothing else, we can make a libcall.
1958  RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1959  if (VT == MVT::i16)
1960    LC = RTLIB::MUL_I16;
1961  else if (VT == MVT::i32)
1962    LC = RTLIB::MUL_I32;
1963  else if (VT == MVT::i64)
1964    LC = RTLIB::MUL_I64;
1965  else if (VT == MVT::i128)
1966    LC = RTLIB::MUL_I128;
1967  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported MUL!");
1968
1969  SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1970  SplitInteger(MakeLibCall(LC, VT, Ops, 2, true/*irrelevant*/, dl), Lo, Hi);
1971}
1972
1973void DAGTypeLegalizer::ExpandIntRes_SADDSUBO(SDNode *Node,
1974                                             SDValue &Lo, SDValue &Hi) {
1975  SDValue LHS = Node->getOperand(0);
1976  SDValue RHS = Node->getOperand(1);
1977  DebugLoc dl = Node->getDebugLoc();
1978
1979  // Expand the result by simply replacing it with the equivalent
1980  // non-overflow-checking operation.
1981  SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
1982                            ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
1983                            LHS, RHS);
1984  SplitInteger(Sum, Lo, Hi);
1985
1986  // Compute the overflow.
1987  //
1988  //   LHSSign -> LHS >= 0
1989  //   RHSSign -> RHS >= 0
1990  //   SumSign -> Sum >= 0
1991  //
1992  //   Add:
1993  //   Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
1994  //   Sub:
1995  //   Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
1996  //
1997  EVT OType = Node->getValueType(1);
1998  SDValue Zero = DAG.getConstant(0, LHS.getValueType());
1999
2000  SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
2001  SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
2002  SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
2003                                    Node->getOpcode() == ISD::SADDO ?
2004                                    ISD::SETEQ : ISD::SETNE);
2005
2006  SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
2007  SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
2008
2009  SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
2010
2011  // Use the calculated overflow everywhere.
2012  ReplaceValueWith(SDValue(Node, 1), Cmp);
2013}
2014
2015void DAGTypeLegalizer::ExpandIntRes_SDIV(SDNode *N,
2016                                         SDValue &Lo, SDValue &Hi) {
2017  EVT VT = N->getValueType(0);
2018  DebugLoc dl = N->getDebugLoc();
2019
2020  RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2021  if (VT == MVT::i16)
2022    LC = RTLIB::SDIV_I16;
2023  else if (VT == MVT::i32)
2024    LC = RTLIB::SDIV_I32;
2025  else if (VT == MVT::i64)
2026    LC = RTLIB::SDIV_I64;
2027  else if (VT == MVT::i128)
2028    LC = RTLIB::SDIV_I128;
2029  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
2030
2031  SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2032  SplitInteger(MakeLibCall(LC, VT, Ops, 2, true, dl), Lo, Hi);
2033}
2034
2035void DAGTypeLegalizer::ExpandIntRes_Shift(SDNode *N,
2036                                          SDValue &Lo, SDValue &Hi) {
2037  EVT VT = N->getValueType(0);
2038  DebugLoc dl = N->getDebugLoc();
2039
2040  // If we can emit an efficient shift operation, do so now.  Check to see if
2041  // the RHS is a constant.
2042  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2043    return ExpandShiftByConstant(N, CN->getZExtValue(), Lo, Hi);
2044
2045  // If we can determine that the high bit of the shift is zero or one, even if
2046  // the low bits are variable, emit this shift in an optimized form.
2047  if (ExpandShiftWithKnownAmountBit(N, Lo, Hi))
2048    return;
2049
2050  // If this target supports shift_PARTS, use it.  First, map to the _PARTS opc.
2051  unsigned PartsOpc;
2052  if (N->getOpcode() == ISD::SHL) {
2053    PartsOpc = ISD::SHL_PARTS;
2054  } else if (N->getOpcode() == ISD::SRL) {
2055    PartsOpc = ISD::SRL_PARTS;
2056  } else {
2057    assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
2058    PartsOpc = ISD::SRA_PARTS;
2059  }
2060
2061  // Next check to see if the target supports this SHL_PARTS operation or if it
2062  // will custom expand it.
2063  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2064  TargetLowering::LegalizeAction Action = TLI.getOperationAction(PartsOpc, NVT);
2065  if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
2066      Action == TargetLowering::Custom) {
2067    // Expand the subcomponents.
2068    SDValue LHSL, LHSH;
2069    GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
2070
2071    SDValue Ops[] = { LHSL, LHSH, N->getOperand(1) };
2072    EVT VT = LHSL.getValueType();
2073    Lo = DAG.getNode(PartsOpc, dl, DAG.getVTList(VT, VT), Ops, 3);
2074    Hi = Lo.getValue(1);
2075    return;
2076  }
2077
2078  // Otherwise, emit a libcall.
2079  RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2080  bool isSigned;
2081  if (N->getOpcode() == ISD::SHL) {
2082    isSigned = false; /*sign irrelevant*/
2083    if (VT == MVT::i16)
2084      LC = RTLIB::SHL_I16;
2085    else if (VT == MVT::i32)
2086      LC = RTLIB::SHL_I32;
2087    else if (VT == MVT::i64)
2088      LC = RTLIB::SHL_I64;
2089    else if (VT == MVT::i128)
2090      LC = RTLIB::SHL_I128;
2091  } else if (N->getOpcode() == ISD::SRL) {
2092    isSigned = false;
2093    if (VT == MVT::i16)
2094      LC = RTLIB::SRL_I16;
2095    else if (VT == MVT::i32)
2096      LC = RTLIB::SRL_I32;
2097    else if (VT == MVT::i64)
2098      LC = RTLIB::SRL_I64;
2099    else if (VT == MVT::i128)
2100      LC = RTLIB::SRL_I128;
2101  } else {
2102    assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
2103    isSigned = true;
2104    if (VT == MVT::i16)
2105      LC = RTLIB::SRA_I16;
2106    else if (VT == MVT::i32)
2107      LC = RTLIB::SRA_I32;
2108    else if (VT == MVT::i64)
2109      LC = RTLIB::SRA_I64;
2110    else if (VT == MVT::i128)
2111      LC = RTLIB::SRA_I128;
2112  }
2113
2114  if (LC != RTLIB::UNKNOWN_LIBCALL && TLI.getLibcallName(LC)) {
2115    SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2116    SplitInteger(MakeLibCall(LC, VT, Ops, 2, isSigned, dl), Lo, Hi);
2117    return;
2118  }
2119
2120  if (!ExpandShiftWithUnknownAmountBit(N, Lo, Hi))
2121    llvm_unreachable("Unsupported shift!");
2122}
2123
2124void DAGTypeLegalizer::ExpandIntRes_SIGN_EXTEND(SDNode *N,
2125                                                SDValue &Lo, SDValue &Hi) {
2126  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2127  DebugLoc dl = N->getDebugLoc();
2128  SDValue Op = N->getOperand(0);
2129  if (Op.getValueType().bitsLE(NVT)) {
2130    // The low part is sign extension of the input (degenerates to a copy).
2131    Lo = DAG.getNode(ISD::SIGN_EXTEND, dl, NVT, N->getOperand(0));
2132    // The high part is obtained by SRA'ing all but one of the bits of low part.
2133    unsigned LoSize = NVT.getSizeInBits();
2134    Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
2135                     DAG.getConstant(LoSize-1, TLI.getPointerTy()));
2136  } else {
2137    // For example, extension of an i48 to an i64.  The operand type necessarily
2138    // promotes to the result type, so will end up being expanded too.
2139    assert(getTypeAction(Op.getValueType()) ==
2140           TargetLowering::TypePromoteInteger &&
2141           "Only know how to promote this result!");
2142    SDValue Res = GetPromotedInteger(Op);
2143    assert(Res.getValueType() == N->getValueType(0) &&
2144           "Operand over promoted?");
2145    // Split the promoted operand.  This will simplify when it is expanded.
2146    SplitInteger(Res, Lo, Hi);
2147    unsigned ExcessBits =
2148      Op.getValueType().getSizeInBits() - NVT.getSizeInBits();
2149    Hi = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Hi.getValueType(), Hi,
2150                     DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
2151                                                        ExcessBits)));
2152  }
2153}
2154
2155void DAGTypeLegalizer::
2156ExpandIntRes_SIGN_EXTEND_INREG(SDNode *N, SDValue &Lo, SDValue &Hi) {
2157  DebugLoc dl = N->getDebugLoc();
2158  GetExpandedInteger(N->getOperand(0), Lo, Hi);
2159  EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
2160
2161  if (EVT.bitsLE(Lo.getValueType())) {
2162    // sext_inreg the low part if needed.
2163    Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Lo.getValueType(), Lo,
2164                     N->getOperand(1));
2165
2166    // The high part gets the sign extension from the lo-part.  This handles
2167    // things like sextinreg V:i64 from i8.
2168    Hi = DAG.getNode(ISD::SRA, dl, Hi.getValueType(), Lo,
2169                     DAG.getConstant(Hi.getValueType().getSizeInBits()-1,
2170                                     TLI.getPointerTy()));
2171  } else {
2172    // For example, extension of an i48 to an i64.  Leave the low part alone,
2173    // sext_inreg the high part.
2174    unsigned ExcessBits =
2175      EVT.getSizeInBits() - Lo.getValueType().getSizeInBits();
2176    Hi = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Hi.getValueType(), Hi,
2177                     DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
2178                                                        ExcessBits)));
2179  }
2180}
2181
2182void DAGTypeLegalizer::ExpandIntRes_SREM(SDNode *N,
2183                                         SDValue &Lo, SDValue &Hi) {
2184  EVT VT = N->getValueType(0);
2185  DebugLoc dl = N->getDebugLoc();
2186
2187  RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2188  if (VT == MVT::i16)
2189    LC = RTLIB::SREM_I16;
2190  else if (VT == MVT::i32)
2191    LC = RTLIB::SREM_I32;
2192  else if (VT == MVT::i64)
2193    LC = RTLIB::SREM_I64;
2194  else if (VT == MVT::i128)
2195    LC = RTLIB::SREM_I128;
2196  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
2197
2198  SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2199  SplitInteger(MakeLibCall(LC, VT, Ops, 2, true, dl), Lo, Hi);
2200}
2201
2202void DAGTypeLegalizer::ExpandIntRes_TRUNCATE(SDNode *N,
2203                                             SDValue &Lo, SDValue &Hi) {
2204  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2205  DebugLoc dl = N->getDebugLoc();
2206  Lo = DAG.getNode(ISD::TRUNCATE, dl, NVT, N->getOperand(0));
2207  Hi = DAG.getNode(ISD::SRL, dl,
2208                   N->getOperand(0).getValueType(), N->getOperand(0),
2209                   DAG.getConstant(NVT.getSizeInBits(), TLI.getPointerTy()));
2210  Hi = DAG.getNode(ISD::TRUNCATE, dl, NVT, Hi);
2211}
2212
2213void DAGTypeLegalizer::ExpandIntRes_UADDSUBO(SDNode *N,
2214                                             SDValue &Lo, SDValue &Hi) {
2215  SDValue LHS = N->getOperand(0);
2216  SDValue RHS = N->getOperand(1);
2217  DebugLoc dl = N->getDebugLoc();
2218
2219  // Expand the result by simply replacing it with the equivalent
2220  // non-overflow-checking operation.
2221  SDValue Sum = DAG.getNode(N->getOpcode() == ISD::UADDO ?
2222                            ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
2223                            LHS, RHS);
2224  SplitInteger(Sum, Lo, Hi);
2225
2226  // Calculate the overflow: addition overflows iff a + b < a, and subtraction
2227  // overflows iff a - b > a.
2228  SDValue Ofl = DAG.getSetCC(dl, N->getValueType(1), Sum, LHS,
2229                             N->getOpcode () == ISD::UADDO ?
2230                             ISD::SETULT : ISD::SETUGT);
2231
2232  // Use the calculated overflow everywhere.
2233  ReplaceValueWith(SDValue(N, 1), Ofl);
2234}
2235
2236void DAGTypeLegalizer::ExpandIntRes_XMULO(SDNode *N,
2237                                          SDValue &Lo, SDValue &Hi) {
2238  EVT VT = N->getValueType(0);
2239  Type *RetTy = VT.getTypeForEVT(*DAG.getContext());
2240  EVT PtrVT = TLI.getPointerTy();
2241  Type *PtrTy = PtrVT.getTypeForEVT(*DAG.getContext());
2242  DebugLoc dl = N->getDebugLoc();
2243
2244  // A divide for UMULO should be faster than a function call.
2245  if (N->getOpcode() == ISD::UMULO) {
2246    SDValue LHS = N->getOperand(0), RHS = N->getOperand(1);
2247    DebugLoc DL = N->getDebugLoc();
2248
2249    SDValue MUL = DAG.getNode(ISD::MUL, DL, LHS.getValueType(), LHS, RHS);
2250    SplitInteger(MUL, Lo, Hi);
2251
2252    // A divide for UMULO will be faster than a function call. Select to
2253    // make sure we aren't using 0.
2254    SDValue isZero = DAG.getSetCC(dl, TLI.getSetCCResultType(VT),
2255				  RHS, DAG.getConstant(0, VT), ISD::SETNE);
2256    SDValue NotZero = DAG.getNode(ISD::SELECT, dl, VT, isZero,
2257				  DAG.getConstant(1, VT), RHS);
2258    SDValue DIV = DAG.getNode(ISD::UDIV, DL, LHS.getValueType(), MUL, NotZero);
2259    SDValue Overflow;
2260    Overflow = DAG.getSetCC(DL, N->getValueType(1), DIV, LHS, ISD::SETNE);
2261    ReplaceValueWith(SDValue(N, 1), Overflow);
2262    return;
2263  }
2264
2265  // Replace this with a libcall that will check overflow.
2266  RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2267  if (VT == MVT::i32)
2268    LC = RTLIB::MULO_I32;
2269  else if (VT == MVT::i64)
2270    LC = RTLIB::MULO_I64;
2271  else if (VT == MVT::i128)
2272    LC = RTLIB::MULO_I128;
2273  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported XMULO!");
2274
2275  SDValue Temp = DAG.CreateStackTemporary(PtrVT);
2276  // Temporary for the overflow value, default it to zero.
2277  SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl,
2278			       DAG.getConstant(0, PtrVT), Temp,
2279			       MachinePointerInfo(), false, false, 0);
2280
2281  TargetLowering::ArgListTy Args;
2282  TargetLowering::ArgListEntry Entry;
2283  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2284    EVT ArgVT = N->getOperand(i).getValueType();
2285    Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2286    Entry.Node = N->getOperand(i);
2287    Entry.Ty = ArgTy;
2288    Entry.isSExt = true;
2289    Entry.isZExt = false;
2290    Args.push_back(Entry);
2291  }
2292
2293  // Also pass the address of the overflow check.
2294  Entry.Node = Temp;
2295  Entry.Ty = PtrTy->getPointerTo();
2296  Entry.isSExt = true;
2297  Entry.isZExt = false;
2298  Args.push_back(Entry);
2299
2300  SDValue Func = DAG.getExternalSymbol(TLI.getLibcallName(LC), PtrVT);
2301  std::pair<SDValue, SDValue> CallInfo =
2302    TLI.LowerCallTo(Chain, RetTy, true, false, false, false,
2303		    0, TLI.getLibcallCallingConv(LC), false,
2304		    true, Func, Args, DAG, dl);
2305
2306  SplitInteger(CallInfo.first, Lo, Hi);
2307  SDValue Temp2 = DAG.getLoad(PtrVT, dl, CallInfo.second, Temp,
2308			      MachinePointerInfo(), false, false, 0);
2309  SDValue Ofl = DAG.getSetCC(dl, N->getValueType(1), Temp2,
2310                             DAG.getConstant(0, PtrVT),
2311                             ISD::SETNE);
2312  // Use the overflow from the libcall everywhere.
2313  ReplaceValueWith(SDValue(N, 1), Ofl);
2314}
2315
2316void DAGTypeLegalizer::ExpandIntRes_UDIV(SDNode *N,
2317                                         SDValue &Lo, SDValue &Hi) {
2318  EVT VT = N->getValueType(0);
2319  DebugLoc dl = N->getDebugLoc();
2320
2321  RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2322  if (VT == MVT::i16)
2323    LC = RTLIB::UDIV_I16;
2324  else if (VT == MVT::i32)
2325    LC = RTLIB::UDIV_I32;
2326  else if (VT == MVT::i64)
2327    LC = RTLIB::UDIV_I64;
2328  else if (VT == MVT::i128)
2329    LC = RTLIB::UDIV_I128;
2330  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UDIV!");
2331
2332  SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2333  SplitInteger(MakeLibCall(LC, VT, Ops, 2, false, dl), Lo, Hi);
2334}
2335
2336void DAGTypeLegalizer::ExpandIntRes_UREM(SDNode *N,
2337                                         SDValue &Lo, SDValue &Hi) {
2338  EVT VT = N->getValueType(0);
2339  DebugLoc dl = N->getDebugLoc();
2340
2341  RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2342  if (VT == MVT::i16)
2343    LC = RTLIB::UREM_I16;
2344  else if (VT == MVT::i32)
2345    LC = RTLIB::UREM_I32;
2346  else if (VT == MVT::i64)
2347    LC = RTLIB::UREM_I64;
2348  else if (VT == MVT::i128)
2349    LC = RTLIB::UREM_I128;
2350  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UREM!");
2351
2352  SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2353  SplitInteger(MakeLibCall(LC, VT, Ops, 2, false, dl), Lo, Hi);
2354}
2355
2356void DAGTypeLegalizer::ExpandIntRes_ZERO_EXTEND(SDNode *N,
2357                                                SDValue &Lo, SDValue &Hi) {
2358  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2359  DebugLoc dl = N->getDebugLoc();
2360  SDValue Op = N->getOperand(0);
2361  if (Op.getValueType().bitsLE(NVT)) {
2362    // The low part is zero extension of the input (degenerates to a copy).
2363    Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N->getOperand(0));
2364    Hi = DAG.getConstant(0, NVT);   // The high part is just a zero.
2365  } else {
2366    // For example, extension of an i48 to an i64.  The operand type necessarily
2367    // promotes to the result type, so will end up being expanded too.
2368    assert(getTypeAction(Op.getValueType()) ==
2369           TargetLowering::TypePromoteInteger &&
2370           "Only know how to promote this result!");
2371    SDValue Res = GetPromotedInteger(Op);
2372    assert(Res.getValueType() == N->getValueType(0) &&
2373           "Operand over promoted?");
2374    // Split the promoted operand.  This will simplify when it is expanded.
2375    SplitInteger(Res, Lo, Hi);
2376    unsigned ExcessBits =
2377      Op.getValueType().getSizeInBits() - NVT.getSizeInBits();
2378    Hi = DAG.getZeroExtendInReg(Hi, dl,
2379                                EVT::getIntegerVT(*DAG.getContext(),
2380                                                  ExcessBits));
2381  }
2382}
2383
2384void DAGTypeLegalizer::ExpandIntRes_ATOMIC_LOAD(SDNode *N,
2385                                                SDValue &Lo, SDValue &Hi) {
2386  DebugLoc dl = N->getDebugLoc();
2387  EVT VT = cast<AtomicSDNode>(N)->getMemoryVT();
2388  SDValue Zero = DAG.getConstant(0, VT);
2389  SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
2390                               N->getOperand(0),
2391                               N->getOperand(1), Zero, Zero,
2392                               cast<AtomicSDNode>(N)->getMemOperand(),
2393                               cast<AtomicSDNode>(N)->getOrdering(),
2394                               cast<AtomicSDNode>(N)->getSynchScope());
2395  ReplaceValueWith(SDValue(N, 0), Swap.getValue(0));
2396  ReplaceValueWith(SDValue(N, 1), Swap.getValue(1));
2397}
2398
2399//===----------------------------------------------------------------------===//
2400//  Integer Operand Expansion
2401//===----------------------------------------------------------------------===//
2402
2403/// ExpandIntegerOperand - This method is called when the specified operand of
2404/// the specified node is found to need expansion.  At this point, all of the
2405/// result types of the node are known to be legal, but other operands of the
2406/// node may need promotion or expansion as well as the specified one.
2407bool DAGTypeLegalizer::ExpandIntegerOperand(SDNode *N, unsigned OpNo) {
2408  DEBUG(dbgs() << "Expand integer operand: "; N->dump(&DAG); dbgs() << "\n");
2409  SDValue Res = SDValue();
2410
2411  if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
2412    return false;
2413
2414  switch (N->getOpcode()) {
2415  default:
2416  #ifndef NDEBUG
2417    dbgs() << "ExpandIntegerOperand Op #" << OpNo << ": ";
2418    N->dump(&DAG); dbgs() << "\n";
2419  #endif
2420    llvm_unreachable("Do not know how to expand this operator's operand!");
2421
2422  case ISD::BITCAST:           Res = ExpandOp_BITCAST(N); break;
2423  case ISD::BR_CC:             Res = ExpandIntOp_BR_CC(N); break;
2424  case ISD::BUILD_VECTOR:      Res = ExpandOp_BUILD_VECTOR(N); break;
2425  case ISD::EXTRACT_ELEMENT:   Res = ExpandOp_EXTRACT_ELEMENT(N); break;
2426  case ISD::INSERT_VECTOR_ELT: Res = ExpandOp_INSERT_VECTOR_ELT(N); break;
2427  case ISD::SCALAR_TO_VECTOR:  Res = ExpandOp_SCALAR_TO_VECTOR(N); break;
2428  case ISD::SELECT_CC:         Res = ExpandIntOp_SELECT_CC(N); break;
2429  case ISD::SETCC:             Res = ExpandIntOp_SETCC(N); break;
2430  case ISD::SINT_TO_FP:        Res = ExpandIntOp_SINT_TO_FP(N); break;
2431  case ISD::STORE:   Res = ExpandIntOp_STORE(cast<StoreSDNode>(N), OpNo); break;
2432  case ISD::TRUNCATE:          Res = ExpandIntOp_TRUNCATE(N); break;
2433  case ISD::UINT_TO_FP:        Res = ExpandIntOp_UINT_TO_FP(N); break;
2434
2435  case ISD::SHL:
2436  case ISD::SRA:
2437  case ISD::SRL:
2438  case ISD::ROTL:
2439  case ISD::ROTR:              Res = ExpandIntOp_Shift(N); break;
2440  case ISD::RETURNADDR:
2441  case ISD::FRAMEADDR:         Res = ExpandIntOp_RETURNADDR(N); break;
2442
2443  case ISD::ATOMIC_STORE:      Res = ExpandIntOp_ATOMIC_STORE(N); break;
2444  }
2445
2446  // If the result is null, the sub-method took care of registering results etc.
2447  if (!Res.getNode()) return false;
2448
2449  // If the result is N, the sub-method updated N in place.  Tell the legalizer
2450  // core about this.
2451  if (Res.getNode() == N)
2452    return true;
2453
2454  assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
2455         "Invalid operand expansion");
2456
2457  ReplaceValueWith(SDValue(N, 0), Res);
2458  return false;
2459}
2460
2461/// IntegerExpandSetCCOperands - Expand the operands of a comparison.  This code
2462/// is shared among BR_CC, SELECT_CC, and SETCC handlers.
2463void DAGTypeLegalizer::IntegerExpandSetCCOperands(SDValue &NewLHS,
2464                                                  SDValue &NewRHS,
2465                                                  ISD::CondCode &CCCode,
2466                                                  DebugLoc dl) {
2467  SDValue LHSLo, LHSHi, RHSLo, RHSHi;
2468  GetExpandedInteger(NewLHS, LHSLo, LHSHi);
2469  GetExpandedInteger(NewRHS, RHSLo, RHSHi);
2470
2471  if (CCCode == ISD::SETEQ || CCCode == ISD::SETNE) {
2472    if (RHSLo == RHSHi) {
2473      if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo)) {
2474        if (RHSCST->isAllOnesValue()) {
2475          // Equality comparison to -1.
2476          NewLHS = DAG.getNode(ISD::AND, dl,
2477                               LHSLo.getValueType(), LHSLo, LHSHi);
2478          NewRHS = RHSLo;
2479          return;
2480        }
2481      }
2482    }
2483
2484    NewLHS = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSLo, RHSLo);
2485    NewRHS = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSHi, RHSHi);
2486    NewLHS = DAG.getNode(ISD::OR, dl, NewLHS.getValueType(), NewLHS, NewRHS);
2487    NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2488    return;
2489  }
2490
2491  // If this is a comparison of the sign bit, just look at the top part.
2492  // X > -1,  x < 0
2493  if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(NewRHS))
2494    if ((CCCode == ISD::SETLT && CST->isNullValue()) ||     // X < 0
2495        (CCCode == ISD::SETGT && CST->isAllOnesValue())) {  // X > -1
2496      NewLHS = LHSHi;
2497      NewRHS = RHSHi;
2498      return;
2499    }
2500
2501  // FIXME: This generated code sucks.
2502  ISD::CondCode LowCC;
2503  switch (CCCode) {
2504  default: llvm_unreachable("Unknown integer setcc!");
2505  case ISD::SETLT:
2506  case ISD::SETULT: LowCC = ISD::SETULT; break;
2507  case ISD::SETGT:
2508  case ISD::SETUGT: LowCC = ISD::SETUGT; break;
2509  case ISD::SETLE:
2510  case ISD::SETULE: LowCC = ISD::SETULE; break;
2511  case ISD::SETGE:
2512  case ISD::SETUGE: LowCC = ISD::SETUGE; break;
2513  }
2514
2515  // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
2516  // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
2517  // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
2518
2519  // NOTE: on targets without efficient SELECT of bools, we can always use
2520  // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
2521  TargetLowering::DAGCombinerInfo DagCombineInfo(DAG, false, true, true, NULL);
2522  SDValue Tmp1, Tmp2;
2523  Tmp1 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSLo.getValueType()),
2524                           LHSLo, RHSLo, LowCC, false, DagCombineInfo, dl);
2525  if (!Tmp1.getNode())
2526    Tmp1 = DAG.getSetCC(dl, TLI.getSetCCResultType(LHSLo.getValueType()),
2527                        LHSLo, RHSLo, LowCC);
2528  Tmp2 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi.getValueType()),
2529                           LHSHi, RHSHi, CCCode, false, DagCombineInfo, dl);
2530  if (!Tmp2.getNode())
2531    Tmp2 = DAG.getNode(ISD::SETCC, dl,
2532                       TLI.getSetCCResultType(LHSHi.getValueType()),
2533                       LHSHi, RHSHi, DAG.getCondCode(CCCode));
2534
2535  ConstantSDNode *Tmp1C = dyn_cast<ConstantSDNode>(Tmp1.getNode());
2536  ConstantSDNode *Tmp2C = dyn_cast<ConstantSDNode>(Tmp2.getNode());
2537  if ((Tmp1C && Tmp1C->isNullValue()) ||
2538      (Tmp2C && Tmp2C->isNullValue() &&
2539       (CCCode == ISD::SETLE || CCCode == ISD::SETGE ||
2540        CCCode == ISD::SETUGE || CCCode == ISD::SETULE)) ||
2541      (Tmp2C && Tmp2C->getAPIntValue() == 1 &&
2542       (CCCode == ISD::SETLT || CCCode == ISD::SETGT ||
2543        CCCode == ISD::SETUGT || CCCode == ISD::SETULT))) {
2544    // low part is known false, returns high part.
2545    // For LE / GE, if high part is known false, ignore the low part.
2546    // For LT / GT, if high part is known true, ignore the low part.
2547    NewLHS = Tmp2;
2548    NewRHS = SDValue();
2549    return;
2550  }
2551
2552  NewLHS = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi.getValueType()),
2553                             LHSHi, RHSHi, ISD::SETEQ, false,
2554                             DagCombineInfo, dl);
2555  if (!NewLHS.getNode())
2556    NewLHS = DAG.getSetCC(dl, TLI.getSetCCResultType(LHSHi.getValueType()),
2557                          LHSHi, RHSHi, ISD::SETEQ);
2558  NewLHS = DAG.getNode(ISD::SELECT, dl, Tmp1.getValueType(),
2559                       NewLHS, Tmp1, Tmp2);
2560  NewRHS = SDValue();
2561}
2562
2563SDValue DAGTypeLegalizer::ExpandIntOp_BR_CC(SDNode *N) {
2564  SDValue NewLHS = N->getOperand(2), NewRHS = N->getOperand(3);
2565  ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(1))->get();
2566  IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, N->getDebugLoc());
2567
2568  // If ExpandSetCCOperands returned a scalar, we need to compare the result
2569  // against zero to select between true and false values.
2570  if (NewRHS.getNode() == 0) {
2571    NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2572    CCCode = ISD::SETNE;
2573  }
2574
2575  // Update N to have the operands specified.
2576  return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
2577                                DAG.getCondCode(CCCode), NewLHS, NewRHS,
2578                                N->getOperand(4)), 0);
2579}
2580
2581SDValue DAGTypeLegalizer::ExpandIntOp_SELECT_CC(SDNode *N) {
2582  SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
2583  ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(4))->get();
2584  IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, N->getDebugLoc());
2585
2586  // If ExpandSetCCOperands returned a scalar, we need to compare the result
2587  // against zero to select between true and false values.
2588  if (NewRHS.getNode() == 0) {
2589    NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2590    CCCode = ISD::SETNE;
2591  }
2592
2593  // Update N to have the operands specified.
2594  return SDValue(DAG.UpdateNodeOperands(N, NewLHS, NewRHS,
2595                                N->getOperand(2), N->getOperand(3),
2596                                DAG.getCondCode(CCCode)), 0);
2597}
2598
2599SDValue DAGTypeLegalizer::ExpandIntOp_SETCC(SDNode *N) {
2600  SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
2601  ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(2))->get();
2602  IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, N->getDebugLoc());
2603
2604  // If ExpandSetCCOperands returned a scalar, use it.
2605  if (NewRHS.getNode() == 0) {
2606    assert(NewLHS.getValueType() == N->getValueType(0) &&
2607           "Unexpected setcc expansion!");
2608    return NewLHS;
2609  }
2610
2611  // Otherwise, update N to have the operands specified.
2612  return SDValue(DAG.UpdateNodeOperands(N, NewLHS, NewRHS,
2613                                DAG.getCondCode(CCCode)), 0);
2614}
2615
2616SDValue DAGTypeLegalizer::ExpandIntOp_Shift(SDNode *N) {
2617  // The value being shifted is legal, but the shift amount is too big.
2618  // It follows that either the result of the shift is undefined, or the
2619  // upper half of the shift amount is zero.  Just use the lower half.
2620  SDValue Lo, Hi;
2621  GetExpandedInteger(N->getOperand(1), Lo, Hi);
2622  return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0), Lo), 0);
2623}
2624
2625SDValue DAGTypeLegalizer::ExpandIntOp_RETURNADDR(SDNode *N) {
2626  // The argument of RETURNADDR / FRAMEADDR builtin is 32 bit contant.  This
2627  // surely makes pretty nice problems on 8/16 bit targets. Just truncate this
2628  // constant to valid type.
2629  SDValue Lo, Hi;
2630  GetExpandedInteger(N->getOperand(0), Lo, Hi);
2631  return SDValue(DAG.UpdateNodeOperands(N, Lo), 0);
2632}
2633
2634SDValue DAGTypeLegalizer::ExpandIntOp_SINT_TO_FP(SDNode *N) {
2635  SDValue Op = N->getOperand(0);
2636  EVT DstVT = N->getValueType(0);
2637  RTLIB::Libcall LC = RTLIB::getSINTTOFP(Op.getValueType(), DstVT);
2638  assert(LC != RTLIB::UNKNOWN_LIBCALL &&
2639         "Don't know how to expand this SINT_TO_FP!");
2640  return MakeLibCall(LC, DstVT, &Op, 1, true, N->getDebugLoc());
2641}
2642
2643SDValue DAGTypeLegalizer::ExpandIntOp_STORE(StoreSDNode *N, unsigned OpNo) {
2644  if (ISD::isNormalStore(N))
2645    return ExpandOp_NormalStore(N, OpNo);
2646
2647  assert(ISD::isUNINDEXEDStore(N) && "Indexed store during type legalization!");
2648  assert(OpNo == 1 && "Can only expand the stored value so far");
2649
2650  EVT VT = N->getOperand(1).getValueType();
2651  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2652  SDValue Ch  = N->getChain();
2653  SDValue Ptr = N->getBasePtr();
2654  unsigned Alignment = N->getAlignment();
2655  bool isVolatile = N->isVolatile();
2656  bool isNonTemporal = N->isNonTemporal();
2657  DebugLoc dl = N->getDebugLoc();
2658  SDValue Lo, Hi;
2659
2660  assert(NVT.isByteSized() && "Expanded type not byte sized!");
2661
2662  if (N->getMemoryVT().bitsLE(NVT)) {
2663    GetExpandedInteger(N->getValue(), Lo, Hi);
2664    return DAG.getTruncStore(Ch, dl, Lo, Ptr, N->getPointerInfo(),
2665                             N->getMemoryVT(), isVolatile, isNonTemporal,
2666                             Alignment);
2667  }
2668
2669  if (TLI.isLittleEndian()) {
2670    // Little-endian - low bits are at low addresses.
2671    GetExpandedInteger(N->getValue(), Lo, Hi);
2672
2673    Lo = DAG.getStore(Ch, dl, Lo, Ptr, N->getPointerInfo(),
2674                      isVolatile, isNonTemporal, Alignment);
2675
2676    unsigned ExcessBits =
2677      N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
2678    EVT NEVT = EVT::getIntegerVT(*DAG.getContext(), ExcessBits);
2679
2680    // Increment the pointer to the other half.
2681    unsigned IncrementSize = NVT.getSizeInBits()/8;
2682    Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
2683                      DAG.getIntPtrConstant(IncrementSize));
2684    Hi = DAG.getTruncStore(Ch, dl, Hi, Ptr,
2685                           N->getPointerInfo().getWithOffset(IncrementSize),
2686                           NEVT, isVolatile, isNonTemporal,
2687                           MinAlign(Alignment, IncrementSize));
2688    return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
2689  }
2690
2691  // Big-endian - high bits are at low addresses.  Favor aligned stores at
2692  // the cost of some bit-fiddling.
2693  GetExpandedInteger(N->getValue(), Lo, Hi);
2694
2695  EVT ExtVT = N->getMemoryVT();
2696  unsigned EBytes = ExtVT.getStoreSize();
2697  unsigned IncrementSize = NVT.getSizeInBits()/8;
2698  unsigned ExcessBits = (EBytes - IncrementSize)*8;
2699  EVT HiVT = EVT::getIntegerVT(*DAG.getContext(),
2700                               ExtVT.getSizeInBits() - ExcessBits);
2701
2702  if (ExcessBits < NVT.getSizeInBits()) {
2703    // Transfer high bits from the top of Lo to the bottom of Hi.
2704    Hi = DAG.getNode(ISD::SHL, dl, NVT, Hi,
2705                     DAG.getConstant(NVT.getSizeInBits() - ExcessBits,
2706                                     TLI.getPointerTy()));
2707    Hi = DAG.getNode(ISD::OR, dl, NVT, Hi,
2708                     DAG.getNode(ISD::SRL, dl, NVT, Lo,
2709                                 DAG.getConstant(ExcessBits,
2710                                                 TLI.getPointerTy())));
2711  }
2712
2713  // Store both the high bits and maybe some of the low bits.
2714  Hi = DAG.getTruncStore(Ch, dl, Hi, Ptr, N->getPointerInfo(),
2715                         HiVT, isVolatile, isNonTemporal, Alignment);
2716
2717  // Increment the pointer to the other half.
2718  Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
2719                    DAG.getIntPtrConstant(IncrementSize));
2720  // Store the lowest ExcessBits bits in the second half.
2721  Lo = DAG.getTruncStore(Ch, dl, Lo, Ptr,
2722                         N->getPointerInfo().getWithOffset(IncrementSize),
2723                         EVT::getIntegerVT(*DAG.getContext(), ExcessBits),
2724                         isVolatile, isNonTemporal,
2725                         MinAlign(Alignment, IncrementSize));
2726  return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
2727}
2728
2729SDValue DAGTypeLegalizer::ExpandIntOp_TRUNCATE(SDNode *N) {
2730  SDValue InL, InH;
2731  GetExpandedInteger(N->getOperand(0), InL, InH);
2732  // Just truncate the low part of the source.
2733  return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), N->getValueType(0), InL);
2734}
2735
2736static const fltSemantics *EVTToAPFloatSemantics(EVT VT) {
2737  switch (VT.getSimpleVT().SimpleTy) {
2738  default: llvm_unreachable("Unknown FP format");
2739  case MVT::f32:     return &APFloat::IEEEsingle;
2740  case MVT::f64:     return &APFloat::IEEEdouble;
2741  case MVT::f80:     return &APFloat::x87DoubleExtended;
2742  case MVT::f128:    return &APFloat::IEEEquad;
2743  case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
2744  }
2745}
2746
2747SDValue DAGTypeLegalizer::ExpandIntOp_UINT_TO_FP(SDNode *N) {
2748  SDValue Op = N->getOperand(0);
2749  EVT SrcVT = Op.getValueType();
2750  EVT DstVT = N->getValueType(0);
2751  DebugLoc dl = N->getDebugLoc();
2752
2753  // The following optimization is valid only if every value in SrcVT (when
2754  // treated as signed) is representable in DstVT.  Check that the mantissa
2755  // size of DstVT is >= than the number of bits in SrcVT -1.
2756  const fltSemantics *sem = EVTToAPFloatSemantics(DstVT);
2757  if (APFloat::semanticsPrecision(*sem) >= SrcVT.getSizeInBits()-1 &&
2758      TLI.getOperationAction(ISD::SINT_TO_FP, SrcVT) == TargetLowering::Custom){
2759    // Do a signed conversion then adjust the result.
2760    SDValue SignedConv = DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Op);
2761    SignedConv = TLI.LowerOperation(SignedConv, DAG);
2762
2763    // The result of the signed conversion needs adjusting if the 'sign bit' of
2764    // the incoming integer was set.  To handle this, we dynamically test to see
2765    // if it is set, and, if so, add a fudge factor.
2766
2767    const uint64_t F32TwoE32  = 0x4F800000ULL;
2768    const uint64_t F32TwoE64  = 0x5F800000ULL;
2769    const uint64_t F32TwoE128 = 0x7F800000ULL;
2770
2771    APInt FF(32, 0);
2772    if (SrcVT == MVT::i32)
2773      FF = APInt(32, F32TwoE32);
2774    else if (SrcVT == MVT::i64)
2775      FF = APInt(32, F32TwoE64);
2776    else if (SrcVT == MVT::i128)
2777      FF = APInt(32, F32TwoE128);
2778    else
2779      assert(false && "Unsupported UINT_TO_FP!");
2780
2781    // Check whether the sign bit is set.
2782    SDValue Lo, Hi;
2783    GetExpandedInteger(Op, Lo, Hi);
2784    SDValue SignSet = DAG.getSetCC(dl,
2785                                   TLI.getSetCCResultType(Hi.getValueType()),
2786                                   Hi, DAG.getConstant(0, Hi.getValueType()),
2787                                   ISD::SETLT);
2788
2789    // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
2790    SDValue FudgePtr = DAG.getConstantPool(
2791                               ConstantInt::get(*DAG.getContext(), FF.zext(64)),
2792                                           TLI.getPointerTy());
2793
2794    // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
2795    SDValue Zero = DAG.getIntPtrConstant(0);
2796    SDValue Four = DAG.getIntPtrConstant(4);
2797    if (TLI.isBigEndian()) std::swap(Zero, Four);
2798    SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
2799                                 Zero, Four);
2800    unsigned Alignment = cast<ConstantPoolSDNode>(FudgePtr)->getAlignment();
2801    FudgePtr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), FudgePtr, Offset);
2802    Alignment = std::min(Alignment, 4u);
2803
2804    // Load the value out, extending it from f32 to the destination float type.
2805    // FIXME: Avoid the extend by constructing the right constant pool?
2806    SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, DstVT, DAG.getEntryNode(),
2807                                   FudgePtr,
2808                                   MachinePointerInfo::getConstantPool(),
2809                                   MVT::f32,
2810                                   false, false, Alignment);
2811    return DAG.getNode(ISD::FADD, dl, DstVT, SignedConv, Fudge);
2812  }
2813
2814  // Otherwise, use a libcall.
2815  RTLIB::Libcall LC = RTLIB::getUINTTOFP(SrcVT, DstVT);
2816  assert(LC != RTLIB::UNKNOWN_LIBCALL &&
2817         "Don't know how to expand this UINT_TO_FP!");
2818  return MakeLibCall(LC, DstVT, &Op, 1, true, dl);
2819}
2820
2821SDValue DAGTypeLegalizer::ExpandIntOp_ATOMIC_STORE(SDNode *N) {
2822  DebugLoc dl = N->getDebugLoc();
2823  SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
2824                               cast<AtomicSDNode>(N)->getMemoryVT(),
2825                               N->getOperand(0),
2826                               N->getOperand(1), N->getOperand(2),
2827                               cast<AtomicSDNode>(N)->getMemOperand(),
2828                               cast<AtomicSDNode>(N)->getOrdering(),
2829                               cast<AtomicSDNode>(N)->getSynchScope());
2830  return Swap.getValue(1);
2831}
2832
2833
2834SDValue DAGTypeLegalizer::PromoteIntRes_EXTRACT_SUBVECTOR(SDNode *N) {
2835  SDValue InOp0 = N->getOperand(0);
2836  EVT InVT = InOp0.getValueType();
2837
2838  EVT OutVT = N->getValueType(0);
2839  EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2840  assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2841  unsigned OutNumElems = OutVT.getVectorNumElements();
2842  EVT NOutVTElem = NOutVT.getVectorElementType();
2843
2844  DebugLoc dl = N->getDebugLoc();
2845  SDValue BaseIdx = N->getOperand(1);
2846
2847  SmallVector<SDValue, 8> Ops;
2848  Ops.reserve(OutNumElems);
2849  for (unsigned i = 0; i != OutNumElems; ++i) {
2850
2851    // Extract the element from the original vector.
2852    SDValue Index = DAG.getNode(ISD::ADD, dl, BaseIdx.getValueType(),
2853      BaseIdx, DAG.getIntPtrConstant(i));
2854    SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
2855      InVT.getVectorElementType(), N->getOperand(0), Index);
2856
2857    SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, Ext);
2858    // Insert the converted element to the new vector.
2859    Ops.push_back(Op);
2860  }
2861
2862  return DAG.getNode(ISD::BUILD_VECTOR, dl, NOutVT, &Ops[0], Ops.size());
2863}
2864
2865
2866SDValue DAGTypeLegalizer::PromoteIntRes_VECTOR_SHUFFLE(SDNode *N) {
2867  ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
2868  EVT VT = N->getValueType(0);
2869  DebugLoc dl = N->getDebugLoc();
2870
2871  unsigned NumElts = VT.getVectorNumElements();
2872  SmallVector<int, 8> NewMask;
2873  for (unsigned i = 0; i != NumElts; ++i) {
2874    NewMask.push_back(SV->getMaskElt(i));
2875  }
2876
2877  SDValue V0 = GetPromotedInteger(N->getOperand(0));
2878  SDValue V1 = GetPromotedInteger(N->getOperand(1));
2879  EVT OutVT = V0.getValueType();
2880
2881  return DAG.getVectorShuffle(OutVT, dl, V0, V1, &NewMask[0]);
2882}
2883
2884
2885SDValue DAGTypeLegalizer::PromoteIntRes_BUILD_VECTOR(SDNode *N) {
2886  EVT OutVT = N->getValueType(0);
2887  EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2888  assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2889  unsigned NumElems = N->getNumOperands();
2890  EVT NOutVTElem = NOutVT.getVectorElementType();
2891
2892  DebugLoc dl = N->getDebugLoc();
2893
2894  SmallVector<SDValue, 8> Ops;
2895  Ops.reserve(NumElems);
2896  for (unsigned i = 0; i != NumElems; ++i) {
2897    SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, N->getOperand(i));
2898    Ops.push_back(Op);
2899  }
2900
2901  return DAG.getNode(ISD::BUILD_VECTOR, dl, NOutVT, &Ops[0], Ops.size());
2902}
2903
2904SDValue DAGTypeLegalizer::PromoteIntRes_SCALAR_TO_VECTOR(SDNode *N) {
2905
2906  DebugLoc dl = N->getDebugLoc();
2907
2908  assert(!N->getOperand(0).getValueType().isVector() &&
2909         "Input must be a scalar");
2910
2911  EVT OutVT = N->getValueType(0);
2912  EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2913  assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2914  EVT NOutVTElem = NOutVT.getVectorElementType();
2915
2916  SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, N->getOperand(0));
2917
2918  return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NOutVT, Op);
2919}
2920
2921SDValue DAGTypeLegalizer::PromoteIntRes_CONCAT_VECTORS(SDNode *N) {
2922  DebugLoc dl = N->getDebugLoc();
2923
2924  SDValue Op0 = N->getOperand(1);
2925  SDValue Op1 = N->getOperand(1);
2926  assert(Op0.getValueType() == Op1.getValueType() &&
2927         "Invalid input vector types");
2928
2929  EVT OutVT = N->getValueType(0);
2930  EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2931  assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2932
2933  EVT OutElemTy = NOutVT.getVectorElementType();
2934
2935  unsigned NumElem0 = Op0.getValueType().getVectorNumElements();
2936  unsigned NumElem1 = Op1.getValueType().getVectorNumElements();
2937  unsigned NumOutElem = NOutVT.getVectorNumElements();
2938  assert(NumElem0 + NumElem1 == NumOutElem &&
2939         "Invalid number of incoming elements");
2940
2941  // Take the elements from the first vector.
2942  SmallVector<SDValue, 8> Ops(NumOutElem);
2943  for (unsigned i = 0; i < NumElem0; ++i) {
2944    SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
2945                              Op0.getValueType().getScalarType(), Op0,
2946                              DAG.getIntPtrConstant(i));
2947    Ops[i] = DAG.getNode(ISD::ANY_EXTEND, dl, OutElemTy, Ext);
2948  }
2949
2950  // Take the elements from the second vector
2951  for (unsigned i = 0; i < NumElem1; ++i) {
2952    SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
2953                              Op1.getValueType().getScalarType(), Op1,
2954                              DAG.getIntPtrConstant(i));
2955    Ops[i + NumElem0] = DAG.getNode(ISD::ANY_EXTEND, dl, OutElemTy, Ext);
2956  }
2957
2958  return DAG.getNode(ISD::BUILD_VECTOR, dl, NOutVT, &Ops[0], Ops.size());
2959}
2960
2961SDValue DAGTypeLegalizer::PromoteIntRes_INSERT_VECTOR_ELT(SDNode *N) {
2962  EVT OutVT = N->getValueType(0);
2963  EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2964  assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2965
2966  EVT NOutVTElem = NOutVT.getVectorElementType();
2967
2968  DebugLoc dl = N->getDebugLoc();
2969  SDValue V0 = GetPromotedInteger(N->getOperand(0));
2970
2971  SDValue ConvElem = DAG.getNode(ISD::ANY_EXTEND, dl,
2972    NOutVTElem, N->getOperand(1));
2973  return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, NOutVT,
2974    V0, ConvElem, N->getOperand(2));
2975}
2976
2977SDValue DAGTypeLegalizer::PromoteIntOp_EXTRACT_VECTOR_ELT(SDNode *N) {
2978  DebugLoc dl = N->getDebugLoc();
2979  SDValue V0 = GetPromotedInteger(N->getOperand(0));
2980  SDValue V1 = N->getOperand(1);
2981  SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
2982    V0->getValueType(0).getScalarType(), V0, V1);
2983
2984  return DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), Ext);
2985
2986}
2987
2988SDValue DAGTypeLegalizer::PromoteIntOp_CONCAT_VECTORS(SDNode *N) {
2989  DebugLoc dl = N->getDebugLoc();
2990  unsigned NumElems = N->getNumOperands();
2991
2992  EVT RetSclrTy = N->getValueType(0).getVectorElementType();
2993
2994  SmallVector<SDValue, 8> NewOps;
2995  NewOps.reserve(NumElems);
2996
2997  // For each incoming vector
2998  for (unsigned VecIdx = 0; VecIdx != NumElems; ++VecIdx) {
2999    SDValue Incoming = GetPromotedInteger(N->getOperand(VecIdx));
3000    EVT SclrTy = Incoming->getValueType(0).getVectorElementType();
3001    unsigned NumElem = Incoming->getValueType(0).getVectorNumElements();
3002
3003    for (unsigned i=0; i<NumElem; ++i) {
3004      // Extract element from incoming vector
3005      SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SclrTy,
3006      Incoming, DAG.getIntPtrConstant(i));
3007      SDValue Tr = DAG.getNode(ISD::TRUNCATE, dl, RetSclrTy, Ex);
3008      NewOps.push_back(Tr);
3009    }
3010  }
3011
3012  return DAG.getNode(ISD::BUILD_VECTOR, dl,  N->getValueType(0),
3013    &NewOps[0], NewOps.size());
3014  }
3015