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