LegalizeIntegerTypes.cpp revision 21c2972f7d24680f6475877a3398b7f8cf515b33
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"
22using namespace llvm;
23
24//===----------------------------------------------------------------------===//
25//  Integer Result Promotion
26//===----------------------------------------------------------------------===//
27
28/// PromoteIntegerResult - This method is called when a result of a node is
29/// found to be in need of promotion to a larger type.  At this point, the node
30/// may also have invalid operands or may have other results that need
31/// expansion, we just know that (at least) one result needs promotion.
32void DAGTypeLegalizer::PromoteIntegerResult(SDNode *N, unsigned ResNo) {
33  DEBUG(cerr << "Promote integer result: "; N->dump(&DAG); cerr << "\n");
34  SDValue Result = SDValue();
35
36  // See if the target wants to custom expand this node.
37  if (TLI.getOperationAction(N->getOpcode(), N->getValueType(ResNo)) ==
38      TargetLowering::Custom) {
39    // If the target wants to, allow it to lower this itself.
40    if (SDNode *P = TLI.ReplaceNodeResults(N, DAG)) {
41      // Everything that once used N now uses P.  We are guaranteed that the
42      // result value types of N and the result value types of P match.
43      ReplaceNodeWith(N, P);
44      return;
45    }
46  }
47
48  switch (N->getOpcode()) {
49  default:
50#ifndef NDEBUG
51    cerr << "PromoteIntegerResult #" << ResNo << ": ";
52    N->dump(&DAG); cerr << "\n";
53#endif
54    assert(0 && "Do not know how to promote this operator!");
55    abort();
56  case ISD::AssertSext:  Result = PromoteIntRes_AssertSext(N); break;
57  case ISD::AssertZext:  Result = PromoteIntRes_AssertZext(N); break;
58  case ISD::BIT_CONVERT: Result = PromoteIntRes_BIT_CONVERT(N); break;
59  case ISD::BSWAP:       Result = PromoteIntRes_BSWAP(N); break;
60  case ISD::BUILD_PAIR:  Result = PromoteIntRes_BUILD_PAIR(N); break;
61  case ISD::Constant:    Result = PromoteIntRes_Constant(N); break;
62  case ISD::CTLZ:        Result = PromoteIntRes_CTLZ(N); break;
63  case ISD::CTPOP:       Result = PromoteIntRes_CTPOP(N); break;
64  case ISD::CTTZ:        Result = PromoteIntRes_CTTZ(N); break;
65  case ISD::EXTRACT_VECTOR_ELT:
66                         Result = PromoteIntRes_EXTRACT_VECTOR_ELT(N); break;
67  case ISD::LOAD:        Result = PromoteIntRes_LOAD(cast<LoadSDNode>(N));break;
68  case ISD::SELECT:      Result = PromoteIntRes_SELECT(N); break;
69  case ISD::SELECT_CC:   Result = PromoteIntRes_SELECT_CC(N); break;
70  case ISD::SETCC:       Result = PromoteIntRes_SETCC(N); break;
71  case ISD::SHL:         Result = PromoteIntRes_SHL(N); break;
72  case ISD::SIGN_EXTEND_INREG:
73                         Result = PromoteIntRes_SIGN_EXTEND_INREG(N); break;
74  case ISD::SRA:         Result = PromoteIntRes_SRA(N); break;
75  case ISD::SRL:         Result = PromoteIntRes_SRL(N); break;
76  case ISD::TRUNCATE:    Result = PromoteIntRes_TRUNCATE(N); break;
77  case ISD::UNDEF:       Result = PromoteIntRes_UNDEF(N); break;
78  case ISD::VAARG:       Result = PromoteIntRes_VAARG(N); break;
79
80  case ISD::SIGN_EXTEND:
81  case ISD::ZERO_EXTEND:
82  case ISD::ANY_EXTEND:  Result = PromoteIntRes_INT_EXTEND(N); break;
83
84  case ISD::FP_TO_SINT:
85  case ISD::FP_TO_UINT: Result = PromoteIntRes_FP_TO_XINT(N); break;
86
87  case ISD::AND:
88  case ISD::OR:
89  case ISD::XOR:
90  case ISD::ADD:
91  case ISD::SUB:
92  case ISD::MUL: Result = PromoteIntRes_SimpleIntBinOp(N); break;
93
94  case ISD::SDIV:
95  case ISD::SREM: Result = PromoteIntRes_SDIV(N); break;
96
97  case ISD::UDIV:
98  case ISD::UREM: Result = PromoteIntRes_UDIV(N); break;
99
100  case ISD::ATOMIC_LOAD_ADD_8:
101  case ISD::ATOMIC_LOAD_SUB_8:
102  case ISD::ATOMIC_LOAD_AND_8:
103  case ISD::ATOMIC_LOAD_OR_8:
104  case ISD::ATOMIC_LOAD_XOR_8:
105  case ISD::ATOMIC_LOAD_NAND_8:
106  case ISD::ATOMIC_LOAD_MIN_8:
107  case ISD::ATOMIC_LOAD_MAX_8:
108  case ISD::ATOMIC_LOAD_UMIN_8:
109  case ISD::ATOMIC_LOAD_UMAX_8:
110  case ISD::ATOMIC_SWAP_8:
111  case ISD::ATOMIC_LOAD_ADD_16:
112  case ISD::ATOMIC_LOAD_SUB_16:
113  case ISD::ATOMIC_LOAD_AND_16:
114  case ISD::ATOMIC_LOAD_OR_16:
115  case ISD::ATOMIC_LOAD_XOR_16:
116  case ISD::ATOMIC_LOAD_NAND_16:
117  case ISD::ATOMIC_LOAD_MIN_16:
118  case ISD::ATOMIC_LOAD_MAX_16:
119  case ISD::ATOMIC_LOAD_UMIN_16:
120  case ISD::ATOMIC_LOAD_UMAX_16:
121  case ISD::ATOMIC_SWAP_16:
122  case ISD::ATOMIC_LOAD_ADD_32:
123  case ISD::ATOMIC_LOAD_SUB_32:
124  case ISD::ATOMIC_LOAD_AND_32:
125  case ISD::ATOMIC_LOAD_OR_32:
126  case ISD::ATOMIC_LOAD_XOR_32:
127  case ISD::ATOMIC_LOAD_NAND_32:
128  case ISD::ATOMIC_LOAD_MIN_32:
129  case ISD::ATOMIC_LOAD_MAX_32:
130  case ISD::ATOMIC_LOAD_UMIN_32:
131  case ISD::ATOMIC_LOAD_UMAX_32:
132  case ISD::ATOMIC_SWAP_32:
133  case ISD::ATOMIC_LOAD_ADD_64:
134  case ISD::ATOMIC_LOAD_SUB_64:
135  case ISD::ATOMIC_LOAD_AND_64:
136  case ISD::ATOMIC_LOAD_OR_64:
137  case ISD::ATOMIC_LOAD_XOR_64:
138  case ISD::ATOMIC_LOAD_NAND_64:
139  case ISD::ATOMIC_LOAD_MIN_64:
140  case ISD::ATOMIC_LOAD_MAX_64:
141  case ISD::ATOMIC_LOAD_UMIN_64:
142  case ISD::ATOMIC_LOAD_UMAX_64:
143  case ISD::ATOMIC_SWAP_64:
144    Result = PromoteIntRes_Atomic1(cast<AtomicSDNode>(N)); break;
145
146  case ISD::ATOMIC_CMP_SWAP_8:
147  case ISD::ATOMIC_CMP_SWAP_16:
148  case ISD::ATOMIC_CMP_SWAP_32:
149  case ISD::ATOMIC_CMP_SWAP_64:
150    Result = PromoteIntRes_Atomic2(cast<AtomicSDNode>(N)); break;
151  }
152
153  // If Result is null, the sub-method took care of registering the result.
154  if (Result.getNode())
155    SetPromotedInteger(SDValue(N, ResNo), Result);
156}
157
158SDValue DAGTypeLegalizer::PromoteIntRes_AssertSext(SDNode *N) {
159  // Sign-extend the new bits, and continue the assertion.
160  MVT OldVT = N->getValueType(0);
161  SDValue Op = GetPromotedInteger(N->getOperand(0));
162  return DAG.getNode(ISD::AssertSext, Op.getValueType(),
163                     DAG.getNode(ISD::SIGN_EXTEND_INREG, Op.getValueType(), Op,
164                                 DAG.getValueType(OldVT)), N->getOperand(1));
165}
166
167SDValue DAGTypeLegalizer::PromoteIntRes_AssertZext(SDNode *N) {
168  // Zero the new bits, and continue the assertion.
169  MVT OldVT = N->getValueType(0);
170  SDValue Op = GetPromotedInteger(N->getOperand(0));
171  return DAG.getNode(ISD::AssertZext, Op.getValueType(),
172                     DAG.getZeroExtendInReg(Op, OldVT), N->getOperand(1));
173}
174
175SDValue DAGTypeLegalizer::PromoteIntRes_Atomic1(AtomicSDNode *N) {
176  SDValue Op2 = GetPromotedInteger(N->getOperand(2));
177  SDValue Res = DAG.getAtomic(N->getOpcode(), N->getChain(), N->getBasePtr(),
178                              Op2, N->getSrcValue(), N->getAlignment());
179  // Legalized the chain result - switch anything that used the old chain to
180  // use the new one.
181  ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
182  return Res;
183}
184
185SDValue DAGTypeLegalizer::PromoteIntRes_Atomic2(AtomicSDNode *N) {
186  SDValue Op2 = GetPromotedInteger(N->getOperand(2));
187  SDValue Op3 = GetPromotedInteger(N->getOperand(3));
188  SDValue Res = DAG.getAtomic(N->getOpcode(), N->getChain(), N->getBasePtr(),
189                              Op2, Op3, N->getSrcValue(), N->getAlignment());
190  // Legalized the chain result - switch anything that used the old chain to
191  // use the new one.
192  ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
193  return Res;
194}
195
196SDValue DAGTypeLegalizer::PromoteIntRes_BIT_CONVERT(SDNode *N) {
197  SDValue InOp = N->getOperand(0);
198  MVT InVT = InOp.getValueType();
199  MVT NInVT = TLI.getTypeToTransformTo(InVT);
200  MVT OutVT = TLI.getTypeToTransformTo(N->getValueType(0));
201
202  switch (getTypeAction(InVT)) {
203  default:
204    assert(false && "Unknown type action!");
205    break;
206  case Legal:
207    break;
208  case PromoteInteger:
209    if (OutVT.getSizeInBits() == NInVT.getSizeInBits())
210      // The input promotes to the same size.  Convert the promoted value.
211      return DAG.getNode(ISD::BIT_CONVERT, OutVT, GetPromotedInteger(InOp));
212    break;
213  case SoftenFloat:
214    // Promote the integer operand by hand.
215    return DAG.getNode(ISD::ANY_EXTEND, OutVT, GetSoftenedFloat(InOp));
216  case ExpandInteger:
217  case ExpandFloat:
218    break;
219  case ScalarizeVector:
220    // Convert the element to an integer and promote it by hand.
221    return DAG.getNode(ISD::ANY_EXTEND, OutVT,
222                       BitConvertToInteger(GetScalarizedVector(InOp)));
223  case SplitVector:
224    // For example, i32 = BIT_CONVERT v2i16 on alpha.  Convert the split
225    // pieces of the input into integers and reassemble in the final type.
226    SDValue Lo, Hi;
227    GetSplitVector(N->getOperand(0), Lo, Hi);
228    Lo = BitConvertToInteger(Lo);
229    Hi = BitConvertToInteger(Hi);
230
231    if (TLI.isBigEndian())
232      std::swap(Lo, Hi);
233
234    InOp = DAG.getNode(ISD::ANY_EXTEND,
235                       MVT::getIntegerVT(OutVT.getSizeInBits()),
236                       JoinIntegers(Lo, Hi));
237    return DAG.getNode(ISD::BIT_CONVERT, OutVT, InOp);
238  }
239
240  // Otherwise, lower the bit-convert to a store/load from the stack, then
241  // promote the load.
242  SDValue Op = CreateStackStoreLoad(InOp, N->getValueType(0));
243  return PromoteIntRes_LOAD(cast<LoadSDNode>(Op.getNode()));
244}
245
246SDValue DAGTypeLegalizer::PromoteIntRes_BSWAP(SDNode *N) {
247  SDValue Op = GetPromotedInteger(N->getOperand(0));
248  MVT OVT = N->getValueType(0);
249  MVT NVT = Op.getValueType();
250
251  unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
252  return DAG.getNode(ISD::SRL, NVT, DAG.getNode(ISD::BSWAP, NVT, Op),
253                     DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
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,
260                     TLI.getTypeToTransformTo(N->getValueType(0)),
261                     JoinIntegers(N->getOperand(0), N->getOperand(1)));
262}
263
264SDValue DAGTypeLegalizer::PromoteIntRes_Constant(SDNode *N) {
265  MVT VT = N->getValueType(0);
266  // Zero extend things like i1, sign extend everything else.  It shouldn't
267  // matter in theory which one we pick, but this tends to give better code?
268  unsigned Opc = VT.isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
269  SDValue Result = DAG.getNode(Opc, TLI.getTypeToTransformTo(VT),
270                                 SDValue(N, 0));
271  assert(isa<ConstantSDNode>(Result) && "Didn't constant fold ext?");
272  return Result;
273}
274
275SDValue DAGTypeLegalizer::PromoteIntRes_CTLZ(SDNode *N) {
276  SDValue Op = GetPromotedInteger(N->getOperand(0));
277  MVT OVT = N->getValueType(0);
278  MVT NVT = Op.getValueType();
279  // Zero extend to the promoted type and do the count there.
280  Op = DAG.getNode(ISD::CTLZ, NVT, DAG.getZeroExtendInReg(Op, OVT));
281  // Subtract off the extra leading bits in the bigger type.
282  return DAG.getNode(ISD::SUB, NVT, Op,
283                     DAG.getConstant(NVT.getSizeInBits() -
284                                     OVT.getSizeInBits(), NVT));
285}
286
287SDValue DAGTypeLegalizer::PromoteIntRes_CTPOP(SDNode *N) {
288  SDValue Op = GetPromotedInteger(N->getOperand(0));
289  MVT OVT = N->getValueType(0);
290  MVT NVT = Op.getValueType();
291  // Zero extend to the promoted type and do the count there.
292  return DAG.getNode(ISD::CTPOP, NVT, DAG.getZeroExtendInReg(Op, OVT));
293}
294
295SDValue DAGTypeLegalizer::PromoteIntRes_CTTZ(SDNode *N) {
296  SDValue Op = GetPromotedInteger(N->getOperand(0));
297  MVT OVT = N->getValueType(0);
298  MVT NVT = Op.getValueType();
299  // The count is the same in the promoted type except if the original
300  // value was zero.  This can be handled by setting the bit just off
301  // the top of the original type.
302  APInt TopBit(NVT.getSizeInBits(), 0);
303  TopBit.set(OVT.getSizeInBits());
304  Op = DAG.getNode(ISD::OR, NVT, Op, DAG.getConstant(TopBit, NVT));
305  return DAG.getNode(ISD::CTTZ, NVT, Op);
306}
307
308SDValue DAGTypeLegalizer::PromoteIntRes_EXTRACT_VECTOR_ELT(SDNode *N) {
309  MVT OldVT = N->getValueType(0);
310  SDValue OldVec = N->getOperand(0);
311  unsigned OldElts = OldVec.getValueType().getVectorNumElements();
312
313  if (OldElts == 1) {
314    assert(!isTypeLegal(OldVec.getValueType()) &&
315           "Legal one-element vector of a type needing promotion!");
316    // It is tempting to follow GetScalarizedVector by a call to
317    // GetPromotedInteger, but this would be wrong because the
318    // scalarized value may not yet have been processed.
319    return DAG.getNode(ISD::ANY_EXTEND, TLI.getTypeToTransformTo(OldVT),
320                       GetScalarizedVector(OldVec));
321  }
322
323  // Convert to a vector half as long with an element type of twice the width,
324  // for example <4 x i16> -> <2 x i32>.
325  assert(!(OldElts & 1) && "Odd length vectors not supported!");
326  MVT NewVT = MVT::getIntegerVT(2 * OldVT.getSizeInBits());
327  assert(OldVT.isSimple() && NewVT.isSimple());
328
329  SDValue NewVec = DAG.getNode(ISD::BIT_CONVERT,
330                                 MVT::getVectorVT(NewVT, OldElts / 2),
331                                 OldVec);
332
333  // Extract the element at OldIdx / 2 from the new vector.
334  SDValue OldIdx = N->getOperand(1);
335  SDValue NewIdx = DAG.getNode(ISD::SRL, OldIdx.getValueType(), OldIdx,
336                                 DAG.getConstant(1, TLI.getShiftAmountTy()));
337  SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, NewVT, NewVec, NewIdx);
338
339  // Select the appropriate half of the element: Lo if OldIdx was even,
340  // Hi if it was odd.
341  SDValue Lo = Elt;
342  SDValue Hi = DAG.getNode(ISD::SRL, NewVT, Elt,
343                             DAG.getConstant(OldVT.getSizeInBits(),
344                                             TLI.getShiftAmountTy()));
345  if (TLI.isBigEndian())
346    std::swap(Lo, Hi);
347
348  SDValue Odd = DAG.getNode(ISD::TRUNCATE, MVT::i1, OldIdx);
349  return DAG.getNode(ISD::SELECT, NewVT, Odd, Hi, Lo);
350}
351
352SDValue DAGTypeLegalizer::PromoteIntRes_FP_TO_XINT(SDNode *N) {
353  unsigned NewOpc = N->getOpcode();
354  MVT NVT = TLI.getTypeToTransformTo(N->getValueType(0));
355
356  // If we're promoting a UINT to a larger size, check to see if the new node
357  // will be legal.  If it isn't, check to see if FP_TO_SINT is legal, since
358  // we can use that instead.  This allows us to generate better code for
359  // FP_TO_UINT for small destination sizes on targets where FP_TO_UINT is not
360  // legal, such as PowerPC.
361  if (N->getOpcode() == ISD::FP_TO_UINT) {
362    if (!TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
363        (TLI.isOperationLegal(ISD::FP_TO_SINT, NVT) ||
364         TLI.getOperationAction(ISD::FP_TO_SINT, NVT)==TargetLowering::Custom))
365      NewOpc = ISD::FP_TO_SINT;
366  }
367
368  return DAG.getNode(NewOpc, NVT, N->getOperand(0));
369}
370
371SDValue DAGTypeLegalizer::PromoteIntRes_INT_EXTEND(SDNode *N) {
372  MVT NVT = TLI.getTypeToTransformTo(N->getValueType(0));
373
374  if (getTypeAction(N->getOperand(0).getValueType()) == PromoteInteger) {
375    SDValue Res = GetPromotedInteger(N->getOperand(0));
376    assert(Res.getValueType().getSizeInBits() <= NVT.getSizeInBits() &&
377           "Extension doesn't make sense!");
378
379    // If the result and operand types are the same after promotion, simplify
380    // to an in-register extension.
381    if (NVT == Res.getValueType()) {
382      // The high bits are not guaranteed to be anything.  Insert an extend.
383      if (N->getOpcode() == ISD::SIGN_EXTEND)
384        return DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Res,
385                           DAG.getValueType(N->getOperand(0).getValueType()));
386      if (N->getOpcode() == ISD::ZERO_EXTEND)
387        return DAG.getZeroExtendInReg(Res, N->getOperand(0).getValueType());
388      assert(N->getOpcode() == ISD::ANY_EXTEND && "Unknown integer extension!");
389      return Res;
390    }
391  }
392
393  // Otherwise, just extend the original operand all the way to the larger type.
394  return DAG.getNode(N->getOpcode(), NVT, N->getOperand(0));
395}
396
397SDValue DAGTypeLegalizer::PromoteIntRes_LOAD(LoadSDNode *N) {
398  assert(ISD::isUNINDEXEDLoad(N) && "Indexed load during type legalization!");
399  MVT NVT = TLI.getTypeToTransformTo(N->getValueType(0));
400  ISD::LoadExtType ExtType =
401    ISD::isNON_EXTLoad(N) ? ISD::EXTLOAD : N->getExtensionType();
402  SDValue Res = DAG.getExtLoad(ExtType, NVT, N->getChain(), N->getBasePtr(),
403                                 N->getSrcValue(), N->getSrcValueOffset(),
404                                 N->getMemoryVT(), N->isVolatile(),
405                                 N->getAlignment());
406
407  // Legalized the chain result - switch anything that used the old chain to
408  // use the new one.
409  ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
410  return Res;
411}
412
413SDValue DAGTypeLegalizer::PromoteIntRes_SDIV(SDNode *N) {
414  // Sign extend the input.
415  SDValue LHS = GetPromotedInteger(N->getOperand(0));
416  SDValue RHS = GetPromotedInteger(N->getOperand(1));
417  MVT VT = N->getValueType(0);
418  LHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, LHS.getValueType(), LHS,
419                    DAG.getValueType(VT));
420  RHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, RHS.getValueType(), RHS,
421                    DAG.getValueType(VT));
422
423  return DAG.getNode(N->getOpcode(), LHS.getValueType(), LHS, RHS);
424}
425
426SDValue DAGTypeLegalizer::PromoteIntRes_SELECT(SDNode *N) {
427  SDValue LHS = GetPromotedInteger(N->getOperand(1));
428  SDValue RHS = GetPromotedInteger(N->getOperand(2));
429  return DAG.getNode(ISD::SELECT, LHS.getValueType(), N->getOperand(0),LHS,RHS);
430}
431
432SDValue DAGTypeLegalizer::PromoteIntRes_SELECT_CC(SDNode *N) {
433  SDValue LHS = GetPromotedInteger(N->getOperand(2));
434  SDValue RHS = GetPromotedInteger(N->getOperand(3));
435  return DAG.getNode(ISD::SELECT_CC, LHS.getValueType(), N->getOperand(0),
436                     N->getOperand(1), LHS, RHS, N->getOperand(4));
437}
438
439SDValue DAGTypeLegalizer::PromoteIntRes_SETCC(SDNode *N) {
440  MVT SVT = TLI.getSetCCResultType(N->getOperand(0));
441  assert(isTypeLegal(SVT) && "Illegal SetCC type!");
442
443  // Get the SETCC result using the canonical SETCC type.
444  SDValue SetCC = DAG.getNode(ISD::SETCC, SVT, N->getOperand(0),
445                              N->getOperand(1), N->getOperand(2));
446
447  // Convert to the expected type.
448  MVT NVT = TLI.getTypeToTransformTo(N->getValueType(0));
449  assert(NVT.getSizeInBits() <= SVT.getSizeInBits() &&
450         "Integer type overpromoted?");
451  return DAG.getNode(ISD::TRUNCATE, NVT, SetCC);
452}
453
454SDValue DAGTypeLegalizer::PromoteIntRes_SHL(SDNode *N) {
455  return DAG.getNode(ISD::SHL, TLI.getTypeToTransformTo(N->getValueType(0)),
456                     GetPromotedInteger(N->getOperand(0)), N->getOperand(1));
457}
458
459SDValue DAGTypeLegalizer::PromoteIntRes_SIGN_EXTEND_INREG(SDNode *N) {
460  SDValue Op = GetPromotedInteger(N->getOperand(0));
461  return DAG.getNode(ISD::SIGN_EXTEND_INREG, Op.getValueType(), Op,
462                     N->getOperand(1));
463}
464
465SDValue DAGTypeLegalizer::PromoteIntRes_SimpleIntBinOp(SDNode *N) {
466  // The input may have strange things in the top bits of the registers, but
467  // these operations don't care.  They may have weird bits going out, but
468  // that too is okay if they are integer operations.
469  SDValue LHS = GetPromotedInteger(N->getOperand(0));
470  SDValue RHS = GetPromotedInteger(N->getOperand(1));
471  return DAG.getNode(N->getOpcode(), LHS.getValueType(), LHS, RHS);
472}
473
474SDValue DAGTypeLegalizer::PromoteIntRes_SRA(SDNode *N) {
475  // The input value must be properly sign extended.
476  MVT VT = N->getValueType(0);
477  MVT NVT = TLI.getTypeToTransformTo(VT);
478  SDValue Res = GetPromotedInteger(N->getOperand(0));
479  Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Res, DAG.getValueType(VT));
480  return DAG.getNode(ISD::SRA, NVT, Res, N->getOperand(1));
481}
482
483SDValue DAGTypeLegalizer::PromoteIntRes_SRL(SDNode *N) {
484  // The input value must be properly zero extended.
485  MVT VT = N->getValueType(0);
486  MVT NVT = TLI.getTypeToTransformTo(VT);
487  SDValue Res = ZExtPromotedInteger(N->getOperand(0));
488  return DAG.getNode(ISD::SRL, NVT, Res, N->getOperand(1));
489}
490
491SDValue DAGTypeLegalizer::PromoteIntRes_TRUNCATE(SDNode *N) {
492  SDValue Res;
493
494  switch (getTypeAction(N->getOperand(0).getValueType())) {
495  default: assert(0 && "Unknown type action!");
496  case Legal:
497  case ExpandInteger:
498    Res = N->getOperand(0);
499    break;
500  case PromoteInteger:
501    Res = GetPromotedInteger(N->getOperand(0));
502    break;
503  }
504
505  MVT NVT = TLI.getTypeToTransformTo(N->getValueType(0));
506  assert(Res.getValueType().getSizeInBits() >= NVT.getSizeInBits() &&
507         "Truncation doesn't make sense!");
508  if (Res.getValueType() == NVT)
509    return Res;
510
511  // Truncate to NVT instead of VT
512  return DAG.getNode(ISD::TRUNCATE, NVT, Res);
513}
514
515SDValue DAGTypeLegalizer::PromoteIntRes_UDIV(SDNode *N) {
516  // Zero extend the input.
517  SDValue LHS = GetPromotedInteger(N->getOperand(0));
518  SDValue RHS = GetPromotedInteger(N->getOperand(1));
519  MVT VT = N->getValueType(0);
520  LHS = DAG.getZeroExtendInReg(LHS, VT);
521  RHS = DAG.getZeroExtendInReg(RHS, VT);
522
523  return DAG.getNode(N->getOpcode(), LHS.getValueType(), LHS, RHS);
524}
525
526SDValue DAGTypeLegalizer::PromoteIntRes_UNDEF(SDNode *N) {
527  return DAG.getNode(ISD::UNDEF, TLI.getTypeToTransformTo(N->getValueType(0)));
528}
529
530SDValue DAGTypeLegalizer::PromoteIntRes_VAARG(SDNode *N) {
531  SDValue Chain = N->getOperand(0); // Get the chain.
532  SDValue Ptr = N->getOperand(1); // Get the pointer.
533  MVT VT = N->getValueType(0);
534
535  const Value *V = cast<SrcValueSDNode>(N->getOperand(2))->getValue();
536  SDValue VAList = DAG.getLoad(TLI.getPointerTy(), Chain, Ptr, V, 0);
537
538  // Increment the arg pointer, VAList, to the next vaarg
539  // FIXME: should the ABI size be used for the increment?  Think of
540  // x86 long double (10 bytes long, but aligned on 4 or 8 bytes) or
541  // integers of unusual size (such MVT::i1, which gives an increment
542  // of zero here!).
543  unsigned Increment = VT.getSizeInBits() / 8;
544  SDValue Tmp = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList,
545                            DAG.getIntPtrConstant(Increment));
546
547  // Store the incremented VAList to the pointer.
548  Tmp = DAG.getStore(VAList.getValue(1), Tmp, Ptr, V, 0);
549
550  // Load the actual argument out of the arg pointer VAList.
551  Tmp = DAG.getExtLoad(ISD::EXTLOAD, TLI.getTypeToTransformTo(VT), Tmp,
552                       VAList, NULL, 0, VT);
553
554  // Legalized the chain result - switch anything that used the old chain to
555  // use the new one.
556  ReplaceValueWith(SDValue(N, 1), Tmp.getValue(1));
557  return Tmp;
558}
559
560
561//===----------------------------------------------------------------------===//
562//  Integer Operand Promotion
563//===----------------------------------------------------------------------===//
564
565/// PromoteIntegerOperand - This method is called when the specified operand of
566/// the specified node is found to need promotion.  At this point, all of the
567/// result types of the node are known to be legal, but other operands of the
568/// node may need promotion or expansion as well as the specified one.
569bool DAGTypeLegalizer::PromoteIntegerOperand(SDNode *N, unsigned OpNo) {
570  DEBUG(cerr << "Promote integer operand: "; N->dump(&DAG); cerr << "\n");
571  SDValue Res = SDValue();
572
573  if (TLI.getOperationAction(N->getOpcode(), N->getOperand(OpNo).getValueType())
574      == TargetLowering::Custom)
575    Res = TLI.LowerOperation(SDValue(N, 0), DAG);
576
577  if (Res.getNode() == 0) {
578    switch (N->getOpcode()) {
579      default:
580  #ifndef NDEBUG
581      cerr << "PromoteIntegerOperand Op #" << OpNo << ": ";
582      N->dump(&DAG); cerr << "\n";
583  #endif
584      assert(0 && "Do not know how to promote this operator's operand!");
585      abort();
586
587    case ISD::ANY_EXTEND:   Res = PromoteIntOp_ANY_EXTEND(N); break;
588    case ISD::BR_CC:        Res = PromoteIntOp_BR_CC(N, OpNo); break;
589    case ISD::BRCOND:       Res = PromoteIntOp_BRCOND(N, OpNo); break;
590    case ISD::BUILD_PAIR:   Res = PromoteIntOp_BUILD_PAIR(N); break;
591    case ISD::BUILD_VECTOR: Res = PromoteIntOp_BUILD_VECTOR(N); break;
592    case ISD::FP_EXTEND:    Res = PromoteIntOp_FP_EXTEND(N); break;
593    case ISD::FP_ROUND:     Res = PromoteIntOp_FP_ROUND(N); break;
594    case ISD::INSERT_VECTOR_ELT:
595                            Res = PromoteIntOp_INSERT_VECTOR_ELT(N, OpNo);break;
596    case ISD::MEMBARRIER:   Res = PromoteIntOp_MEMBARRIER(N); break;
597    case ISD::SELECT:       Res = PromoteIntOp_SELECT(N, OpNo); break;
598    case ISD::SELECT_CC:    Res = PromoteIntOp_SELECT_CC(N, OpNo); break;
599    case ISD::SETCC:        Res = PromoteIntOp_SETCC(N, OpNo); break;
600    case ISD::SIGN_EXTEND:  Res = PromoteIntOp_SIGN_EXTEND(N); break;
601    case ISD::STORE:        Res = PromoteIntOp_STORE(cast<StoreSDNode>(N),
602                                                     OpNo); break;
603    case ISD::TRUNCATE:     Res = PromoteIntOp_TRUNCATE(N); break;
604    case ISD::ZERO_EXTEND:  Res = PromoteIntOp_ZERO_EXTEND(N); break;
605
606    case ISD::SINT_TO_FP:
607    case ISD::UINT_TO_FP: Res = PromoteIntOp_INT_TO_FP(N); break;
608    }
609  }
610
611  // If the result is null, the sub-method took care of registering results etc.
612  if (!Res.getNode()) return false;
613  // If the result is N, the sub-method updated N in place.
614  if (Res.getNode() == N) {
615    // Mark N as new and remark N and its operands.  This allows us to correctly
616    // revisit N if it needs another step of promotion and allows us to visit
617    // any new operands to N.
618    ReanalyzeNode(N);
619    return true;
620  }
621
622  assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
623         "Invalid operand expansion");
624
625  ReplaceValueWith(SDValue(N, 0), Res);
626  return false;
627}
628
629/// PromoteSetCCOperands - Promote the operands of a comparison.  This code is
630/// shared among BR_CC, SELECT_CC, and SETCC handlers.
631void DAGTypeLegalizer::PromoteSetCCOperands(SDValue &NewLHS,SDValue &NewRHS,
632                                            ISD::CondCode CCCode) {
633  MVT VT = NewLHS.getValueType();
634
635  // Get the promoted values.
636  NewLHS = GetPromotedInteger(NewLHS);
637  NewRHS = GetPromotedInteger(NewRHS);
638
639  // Otherwise, we have to insert explicit sign or zero extends.  Note
640  // that we could insert sign extends for ALL conditions, but zero extend
641  // is cheaper on many machines (an AND instead of two shifts), so prefer
642  // it.
643  switch (CCCode) {
644  default: assert(0 && "Unknown integer comparison!");
645  case ISD::SETEQ:
646  case ISD::SETNE:
647  case ISD::SETUGE:
648  case ISD::SETUGT:
649  case ISD::SETULE:
650  case ISD::SETULT:
651    // ALL of these operations will work if we either sign or zero extend
652    // the operands (including the unsigned comparisons!).  Zero extend is
653    // usually a simpler/cheaper operation, so prefer it.
654    NewLHS = DAG.getZeroExtendInReg(NewLHS, VT);
655    NewRHS = DAG.getZeroExtendInReg(NewRHS, VT);
656    break;
657  case ISD::SETGE:
658  case ISD::SETGT:
659  case ISD::SETLT:
660  case ISD::SETLE:
661    NewLHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, NewLHS.getValueType(), NewLHS,
662                         DAG.getValueType(VT));
663    NewRHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, NewRHS.getValueType(), NewRHS,
664                         DAG.getValueType(VT));
665    break;
666  }
667}
668
669SDValue DAGTypeLegalizer::PromoteIntOp_ANY_EXTEND(SDNode *N) {
670  SDValue Op = GetPromotedInteger(N->getOperand(0));
671  return DAG.getNode(ISD::ANY_EXTEND, N->getValueType(0), Op);
672}
673
674SDValue DAGTypeLegalizer::PromoteIntOp_BR_CC(SDNode *N, unsigned OpNo) {
675  assert(OpNo == 2 && "Don't know how to promote this operand!");
676
677  SDValue LHS = N->getOperand(2);
678  SDValue RHS = N->getOperand(3);
679  PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(1))->get());
680
681  // The chain (Op#0), CC (#1) and basic block destination (Op#4) are always
682  // legal types.
683  return DAG.UpdateNodeOperands(SDValue(N, 0), N->getOperand(0),
684                                N->getOperand(1), LHS, RHS, N->getOperand(4));
685}
686
687SDValue DAGTypeLegalizer::PromoteIntOp_BRCOND(SDNode *N, unsigned OpNo) {
688  assert(OpNo == 1 && "only know how to promote condition");
689  SDValue Cond = GetPromotedInteger(N->getOperand(1));  // Promote condition.
690
691  // The top bits of the promoted condition are not necessarily zero, ensure
692  // that the value is properly zero extended.
693  unsigned BitWidth = Cond.getValueSizeInBits();
694  if (!DAG.MaskedValueIsZero(Cond,
695                             APInt::getHighBitsSet(BitWidth, BitWidth-1)))
696    Cond = DAG.getZeroExtendInReg(Cond, MVT::i1);
697
698  // The chain (Op#0) and basic block destination (Op#2) are always legal types.
699  return DAG.UpdateNodeOperands(SDValue(N, 0), N->getOperand(0), Cond,
700                                N->getOperand(2));
701}
702
703SDValue DAGTypeLegalizer::PromoteIntOp_BUILD_PAIR(SDNode *N) {
704  // Since the result type is legal, the operands must promote to it.
705  MVT OVT = N->getOperand(0).getValueType();
706  SDValue Lo = GetPromotedInteger(N->getOperand(0));
707  SDValue Hi = GetPromotedInteger(N->getOperand(1));
708  assert(Lo.getValueType() == N->getValueType(0) && "Operand over promoted?");
709
710  Lo = DAG.getZeroExtendInReg(Lo, OVT);
711  Hi = DAG.getNode(ISD::SHL, N->getValueType(0), Hi,
712                   DAG.getConstant(OVT.getSizeInBits(),
713                                   TLI.getShiftAmountTy()));
714  return DAG.getNode(ISD::OR, N->getValueType(0), Lo, Hi);
715}
716
717SDValue DAGTypeLegalizer::PromoteIntOp_BUILD_VECTOR(SDNode *N) {
718  // The vector type is legal but the element type is not.  This implies
719  // that the vector is a power-of-two in length and that the element
720  // type does not have a strange size (eg: it is not i1).
721  MVT VecVT = N->getValueType(0);
722  unsigned NumElts = VecVT.getVectorNumElements();
723  assert(!(NumElts & 1) && "Legal vector of one illegal element?");
724
725  // Build a vector of half the length out of elements of twice the bitwidth.
726  // For example <4 x i16> -> <2 x i32>.
727  MVT OldVT = N->getOperand(0).getValueType();
728  MVT NewVT = MVT::getIntegerVT(2 * OldVT.getSizeInBits());
729  assert(OldVT.isSimple() && NewVT.isSimple());
730
731  std::vector<SDValue> NewElts;
732  NewElts.reserve(NumElts/2);
733
734  for (unsigned i = 0; i < NumElts; i += 2) {
735    // Combine two successive elements into one promoted element.
736    SDValue Lo = N->getOperand(i);
737    SDValue Hi = N->getOperand(i+1);
738    if (TLI.isBigEndian())
739      std::swap(Lo, Hi);
740    NewElts.push_back(JoinIntegers(Lo, Hi));
741  }
742
743  SDValue NewVec = DAG.getNode(ISD::BUILD_VECTOR,
744                                 MVT::getVectorVT(NewVT, NewElts.size()),
745                                 &NewElts[0], NewElts.size());
746
747  // Convert the new vector to the old vector type.
748  return DAG.getNode(ISD::BIT_CONVERT, VecVT, NewVec);
749}
750
751SDValue DAGTypeLegalizer::PromoteIntOp_FP_EXTEND(SDNode *N) {
752  SDValue Op = GetPromotedInteger(N->getOperand(0));
753  return DAG.getNode(ISD::FP_EXTEND, N->getValueType(0), Op);
754}
755
756SDValue DAGTypeLegalizer::PromoteIntOp_FP_ROUND(SDNode *N) {
757  SDValue Op = GetPromotedInteger(N->getOperand(0));
758  return DAG.getNode(ISD::FP_ROUND, N->getValueType(0), Op,
759                     DAG.getIntPtrConstant(0));
760}
761
762SDValue DAGTypeLegalizer::PromoteIntOp_INSERT_VECTOR_ELT(SDNode *N,
763                                                         unsigned OpNo) {
764  if (OpNo == 1) {
765    // Promote the inserted value.  This is valid because the type does not
766    // have to match the vector element type.
767
768    // Check that any extra bits introduced will be truncated away.
769    assert(N->getOperand(1).getValueType().getSizeInBits() >=
770           N->getValueType(0).getVectorElementType().getSizeInBits() &&
771           "Type of inserted value narrower than vector element type!");
772    return DAG.UpdateNodeOperands(SDValue(N, 0), N->getOperand(0),
773                                  GetPromotedInteger(N->getOperand(1)),
774                                  N->getOperand(2));
775  }
776
777  assert(OpNo == 2 && "Different operand and result vector types?");
778
779  // Promote the index.
780  SDValue Idx = N->getOperand(2);
781  Idx = DAG.getZeroExtendInReg(GetPromotedInteger(Idx), Idx.getValueType());
782  return DAG.UpdateNodeOperands(SDValue(N, 0), N->getOperand(0),
783                                N->getOperand(1), Idx);
784}
785
786SDValue DAGTypeLegalizer::PromoteIntOp_INT_TO_FP(SDNode *N) {
787  SDValue In = GetPromotedInteger(N->getOperand(0));
788  MVT OpVT = N->getOperand(0).getValueType();
789  if (N->getOpcode() == ISD::UINT_TO_FP)
790    In = DAG.getZeroExtendInReg(In, OpVT);
791  else
792    In = DAG.getNode(ISD::SIGN_EXTEND_INREG, In.getValueType(),
793                     In, DAG.getValueType(OpVT));
794
795  return DAG.UpdateNodeOperands(SDValue(N, 0), In);
796}
797
798SDValue DAGTypeLegalizer::PromoteIntOp_MEMBARRIER(SDNode *N) {
799  SDValue NewOps[6];
800  NewOps[0] = N->getOperand(0);
801  for (unsigned i = 1; i < array_lengthof(NewOps); ++i) {
802    SDValue Flag = GetPromotedInteger(N->getOperand(i));
803    NewOps[i] = DAG.getZeroExtendInReg(Flag, MVT::i1);
804  }
805  return DAG.UpdateNodeOperands(SDValue (N, 0), NewOps,
806                                array_lengthof(NewOps));
807}
808
809SDValue DAGTypeLegalizer::PromoteIntOp_SELECT(SDNode *N, unsigned OpNo) {
810  assert(OpNo == 0 && "Only know how to promote condition");
811  SDValue Cond = GetPromotedInteger(N->getOperand(0));
812
813  // Promote all the way up to SVT, the canonical SetCC type.
814  // FIXME: Not clear what value to pass to getSetCCResultType.
815  // [This only matters for CellSPU since all other targets
816  // ignore the argument.]  We used to pass Cond, resulting in
817  // SVT = MVT::i8, but CellSPU has no select patterns for i8,
818  // causing an abort later.  Passing the result type works
819  // around the problem.
820  MVT SVT = TLI.getSetCCResultType(N->getOperand(1));
821  assert(isTypeLegal(SVT) && "Illegal SetCC type!");
822  assert(Cond.getValueSizeInBits() <= SVT.getSizeInBits() &&
823         "Unexpected SetCC type!");
824
825  // Make sure the extra bits conform to getSetCCResultContents.  There are
826  // two sets of extra bits: those in Cond, which come from type promotion,
827  // and those we need to add to have the final type be SVT (for most targets
828  // this last set of bits is empty).
829  unsigned CondBits = Cond.getValueSizeInBits();
830  ISD::NodeType ExtendCode;
831  switch (TLI.getSetCCResultContents()) {
832  default:
833    assert(false && "Unknown SetCCResultValue!");
834  case TargetLowering::UndefinedSetCCResult:
835    // Extend to SVT by adding rubbish.
836    ExtendCode = ISD::ANY_EXTEND;
837    break;
838  case TargetLowering::ZeroOrOneSetCCResult:
839    ExtendCode = ISD::ZERO_EXTEND;
840    if (!DAG.MaskedValueIsZero(Cond,APInt::getHighBitsSet(CondBits,CondBits-1)))
841      // All extra bits need to be cleared.  Do this by zero extending the
842      // original condition value all the way to SVT.
843      Cond = N->getOperand(0);
844    break;
845  case TargetLowering::ZeroOrNegativeOneSetCCResult: {
846    ExtendCode = ISD::SIGN_EXTEND;
847    unsigned SignBits = DAG.ComputeNumSignBits(Cond);
848    if (SignBits != CondBits)
849      // All extra bits need to be sign extended.  Do this by sign extending the
850      // original condition value all the way to SVT.
851      Cond = N->getOperand(0);
852    break;
853  }
854  }
855  Cond = DAG.getNode(ExtendCode, SVT, Cond);
856
857  return DAG.UpdateNodeOperands(SDValue(N, 0), Cond,
858                                N->getOperand(1), N->getOperand(2));
859}
860
861SDValue DAGTypeLegalizer::PromoteIntOp_SELECT_CC(SDNode *N, unsigned OpNo) {
862  assert(OpNo == 0 && "Don't know how to promote this operand!");
863
864  SDValue LHS = N->getOperand(0);
865  SDValue RHS = N->getOperand(1);
866  PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(4))->get());
867
868  // The CC (#4) and the possible return values (#2 and #3) have legal types.
869  return DAG.UpdateNodeOperands(SDValue(N, 0), LHS, RHS, N->getOperand(2),
870                                N->getOperand(3), N->getOperand(4));
871}
872
873SDValue DAGTypeLegalizer::PromoteIntOp_SETCC(SDNode *N, unsigned OpNo) {
874  assert(OpNo == 0 && "Don't know how to promote this operand!");
875
876  SDValue LHS = N->getOperand(0);
877  SDValue RHS = N->getOperand(1);
878  PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(2))->get());
879
880  // The CC (#2) is always legal.
881  return DAG.UpdateNodeOperands(SDValue(N, 0), LHS, RHS, N->getOperand(2));
882}
883
884SDValue DAGTypeLegalizer::PromoteIntOp_SIGN_EXTEND(SDNode *N) {
885  SDValue Op = GetPromotedInteger(N->getOperand(0));
886  Op = DAG.getNode(ISD::ANY_EXTEND, N->getValueType(0), Op);
887  return DAG.getNode(ISD::SIGN_EXTEND_INREG, Op.getValueType(),
888                     Op, DAG.getValueType(N->getOperand(0).getValueType()));
889}
890
891SDValue DAGTypeLegalizer::PromoteIntOp_STORE(StoreSDNode *N, unsigned OpNo){
892  assert(ISD::isUNINDEXEDStore(N) && "Indexed store during type legalization!");
893  SDValue Ch = N->getChain(), Ptr = N->getBasePtr();
894  int SVOffset = N->getSrcValueOffset();
895  unsigned Alignment = N->getAlignment();
896  bool isVolatile = N->isVolatile();
897
898  SDValue Val = GetPromotedInteger(N->getValue());  // Get promoted value.
899
900  assert(!N->isTruncatingStore() && "Cannot promote this store operand!");
901
902  // Truncate the value and store the result.
903  return DAG.getTruncStore(Ch, Val, Ptr, N->getSrcValue(),
904                           SVOffset, N->getMemoryVT(),
905                           isVolatile, Alignment);
906}
907
908SDValue DAGTypeLegalizer::PromoteIntOp_TRUNCATE(SDNode *N) {
909  SDValue Op = GetPromotedInteger(N->getOperand(0));
910  return DAG.getNode(ISD::TRUNCATE, N->getValueType(0), Op);
911}
912
913SDValue DAGTypeLegalizer::PromoteIntOp_ZERO_EXTEND(SDNode *N) {
914  SDValue Op = GetPromotedInteger(N->getOperand(0));
915  Op = DAG.getNode(ISD::ANY_EXTEND, N->getValueType(0), Op);
916  return DAG.getZeroExtendInReg(Op, N->getOperand(0).getValueType());
917}
918
919
920//===----------------------------------------------------------------------===//
921//  Integer Result Expansion
922//===----------------------------------------------------------------------===//
923
924/// ExpandIntegerResult - This method is called when the specified result of the
925/// specified node is found to need expansion.  At this point, the node may also
926/// have invalid operands or may have other results that need promotion, we just
927/// know that (at least) one result needs expansion.
928void DAGTypeLegalizer::ExpandIntegerResult(SDNode *N, unsigned ResNo) {
929  DEBUG(cerr << "Expand integer result: "; N->dump(&DAG); cerr << "\n");
930  SDValue Lo, Hi;
931  Lo = Hi = SDValue();
932
933  // See if the target wants to custom expand this node.
934  if (TLI.getOperationAction(N->getOpcode(), N->getValueType(ResNo)) ==
935      TargetLowering::Custom) {
936    // If the target wants to, allow it to lower this itself.
937    if (SDNode *P = TLI.ReplaceNodeResults(N, DAG)) {
938      // Everything that once used N now uses P.  We are guaranteed that the
939      // result value types of N and the result value types of P match.
940      ReplaceNodeWith(N, P);
941      return;
942    }
943  }
944
945  switch (N->getOpcode()) {
946  default:
947#ifndef NDEBUG
948    cerr << "ExpandIntegerResult #" << ResNo << ": ";
949    N->dump(&DAG); cerr << "\n";
950#endif
951    assert(0 && "Do not know how to expand the result of this operator!");
952    abort();
953
954  case ISD::MERGE_VALUES: SplitRes_MERGE_VALUES(N, Lo, Hi); break;
955  case ISD::SELECT:       SplitRes_SELECT(N, Lo, Hi); break;
956  case ISD::SELECT_CC:    SplitRes_SELECT_CC(N, Lo, Hi); break;
957  case ISD::UNDEF:        SplitRes_UNDEF(N, Lo, Hi); break;
958
959  case ISD::BIT_CONVERT:        ExpandRes_BIT_CONVERT(N, Lo, Hi); break;
960  case ISD::BUILD_PAIR:         ExpandRes_BUILD_PAIR(N, Lo, Hi); break;
961  case ISD::EXTRACT_ELEMENT:    ExpandRes_EXTRACT_ELEMENT(N, Lo, Hi); break;
962  case ISD::EXTRACT_VECTOR_ELT: ExpandRes_EXTRACT_VECTOR_ELT(N, Lo, Hi); break;
963  case ISD::VAARG:              ExpandRes_VAARG(N, Lo, Hi); break;
964
965  case ISD::ANY_EXTEND:  ExpandIntRes_ANY_EXTEND(N, Lo, Hi); break;
966  case ISD::AssertSext:  ExpandIntRes_AssertSext(N, Lo, Hi); break;
967  case ISD::AssertZext:  ExpandIntRes_AssertZext(N, Lo, Hi); break;
968  case ISD::BSWAP:       ExpandIntRes_BSWAP(N, Lo, Hi); break;
969  case ISD::Constant:    ExpandIntRes_Constant(N, Lo, Hi); break;
970  case ISD::CTLZ:        ExpandIntRes_CTLZ(N, Lo, Hi); break;
971  case ISD::CTPOP:       ExpandIntRes_CTPOP(N, Lo, Hi); break;
972  case ISD::CTTZ:        ExpandIntRes_CTTZ(N, Lo, Hi); break;
973  case ISD::FP_TO_SINT:  ExpandIntRes_FP_TO_SINT(N, Lo, Hi); break;
974  case ISD::FP_TO_UINT:  ExpandIntRes_FP_TO_UINT(N, Lo, Hi); break;
975  case ISD::LOAD:        ExpandIntRes_LOAD(cast<LoadSDNode>(N), Lo, Hi); break;
976  case ISD::MUL:         ExpandIntRes_MUL(N, Lo, Hi); break;
977  case ISD::SDIV:        ExpandIntRes_SDIV(N, Lo, Hi); break;
978  case ISD::SIGN_EXTEND: ExpandIntRes_SIGN_EXTEND(N, Lo, Hi); break;
979  case ISD::SIGN_EXTEND_INREG: ExpandIntRes_SIGN_EXTEND_INREG(N, Lo, Hi); break;
980  case ISD::SREM:        ExpandIntRes_SREM(N, Lo, Hi); break;
981  case ISD::TRUNCATE:    ExpandIntRes_TRUNCATE(N, Lo, Hi); break;
982  case ISD::UDIV:        ExpandIntRes_UDIV(N, Lo, Hi); break;
983  case ISD::UREM:        ExpandIntRes_UREM(N, Lo, Hi); break;
984  case ISD::ZERO_EXTEND: ExpandIntRes_ZERO_EXTEND(N, Lo, Hi); break;
985
986  case ISD::AND:
987  case ISD::OR:
988  case ISD::XOR: ExpandIntRes_Logical(N, Lo, Hi); break;
989
990  case ISD::ADD:
991  case ISD::SUB: ExpandIntRes_ADDSUB(N, Lo, Hi); break;
992
993  case ISD::ADDC:
994  case ISD::SUBC: ExpandIntRes_ADDSUBC(N, Lo, Hi); break;
995
996  case ISD::ADDE:
997  case ISD::SUBE: ExpandIntRes_ADDSUBE(N, Lo, Hi); break;
998
999  case ISD::SHL:
1000  case ISD::SRA:
1001  case ISD::SRL: ExpandIntRes_Shift(N, Lo, Hi); break;
1002  }
1003
1004  // If Lo/Hi is null, the sub-method took care of registering results etc.
1005  if (Lo.getNode())
1006    SetExpandedInteger(SDValue(N, ResNo), Lo, Hi);
1007}
1008
1009/// ExpandShiftByConstant - N is a shift by a value that needs to be expanded,
1010/// and the shift amount is a constant 'Amt'.  Expand the operation.
1011void DAGTypeLegalizer::ExpandShiftByConstant(SDNode *N, unsigned Amt,
1012                                             SDValue &Lo, SDValue &Hi) {
1013  // Expand the incoming operand to be shifted, so that we have its parts
1014  SDValue InL, InH;
1015  GetExpandedInteger(N->getOperand(0), InL, InH);
1016
1017  MVT NVT = InL.getValueType();
1018  unsigned VTBits = N->getValueType(0).getSizeInBits();
1019  unsigned NVTBits = NVT.getSizeInBits();
1020  MVT ShTy = N->getOperand(1).getValueType();
1021
1022  if (N->getOpcode() == ISD::SHL) {
1023    if (Amt > VTBits) {
1024      Lo = Hi = DAG.getConstant(0, NVT);
1025    } else if (Amt > NVTBits) {
1026      Lo = DAG.getConstant(0, NVT);
1027      Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Amt-NVTBits,ShTy));
1028    } else if (Amt == NVTBits) {
1029      Lo = DAG.getConstant(0, NVT);
1030      Hi = InL;
1031    } else if (Amt == 1) {
1032      // Emit this X << 1 as X+X.
1033      SDVTList VTList = DAG.getVTList(NVT, MVT::Flag);
1034      SDValue LoOps[2] = { InL, InL };
1035      Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
1036      SDValue HiOps[3] = { InH, InH, Lo.getValue(1) };
1037      Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
1038    } else {
1039      Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Amt, ShTy));
1040      Hi = DAG.getNode(ISD::OR, NVT,
1041                       DAG.getNode(ISD::SHL, NVT, InH,
1042                                   DAG.getConstant(Amt, ShTy)),
1043                       DAG.getNode(ISD::SRL, NVT, InL,
1044                                   DAG.getConstant(NVTBits-Amt, ShTy)));
1045    }
1046    return;
1047  }
1048
1049  if (N->getOpcode() == ISD::SRL) {
1050    if (Amt > VTBits) {
1051      Lo = DAG.getConstant(0, NVT);
1052      Hi = DAG.getConstant(0, NVT);
1053    } else if (Amt > NVTBits) {
1054      Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Amt-NVTBits,ShTy));
1055      Hi = DAG.getConstant(0, NVT);
1056    } else if (Amt == NVTBits) {
1057      Lo = InH;
1058      Hi = DAG.getConstant(0, NVT);
1059    } else {
1060      Lo = DAG.getNode(ISD::OR, NVT,
1061                       DAG.getNode(ISD::SRL, NVT, InL,
1062                                   DAG.getConstant(Amt, ShTy)),
1063                       DAG.getNode(ISD::SHL, NVT, InH,
1064                                   DAG.getConstant(NVTBits-Amt, ShTy)));
1065      Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Amt, ShTy));
1066    }
1067    return;
1068  }
1069
1070  assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
1071  if (Amt > VTBits) {
1072    Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
1073                          DAG.getConstant(NVTBits-1, ShTy));
1074  } else if (Amt > NVTBits) {
1075    Lo = DAG.getNode(ISD::SRA, NVT, InH,
1076                     DAG.getConstant(Amt-NVTBits, ShTy));
1077    Hi = DAG.getNode(ISD::SRA, NVT, InH,
1078                     DAG.getConstant(NVTBits-1, ShTy));
1079  } else if (Amt == NVTBits) {
1080    Lo = InH;
1081    Hi = DAG.getNode(ISD::SRA, NVT, InH,
1082                     DAG.getConstant(NVTBits-1, ShTy));
1083  } else {
1084    Lo = DAG.getNode(ISD::OR, NVT,
1085                     DAG.getNode(ISD::SRL, NVT, InL,
1086                                 DAG.getConstant(Amt, ShTy)),
1087                     DAG.getNode(ISD::SHL, NVT, InH,
1088                                 DAG.getConstant(NVTBits-Amt, ShTy)));
1089    Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Amt, ShTy));
1090  }
1091}
1092
1093/// ExpandShiftWithKnownAmountBit - Try to determine whether we can simplify
1094/// this shift based on knowledge of the high bit of the shift amount.  If we
1095/// can tell this, we know that it is >= 32 or < 32, without knowing the actual
1096/// shift amount.
1097bool DAGTypeLegalizer::
1098ExpandShiftWithKnownAmountBit(SDNode *N, SDValue &Lo, SDValue &Hi) {
1099  SDValue Amt = N->getOperand(1);
1100  MVT NVT = TLI.getTypeToTransformTo(N->getValueType(0));
1101  MVT ShTy = Amt.getValueType();
1102  unsigned ShBits = ShTy.getSizeInBits();
1103  unsigned NVTBits = NVT.getSizeInBits();
1104  assert(isPowerOf2_32(NVTBits) &&
1105         "Expanded integer type size not a power of two!");
1106
1107  APInt HighBitMask = APInt::getHighBitsSet(ShBits, ShBits - Log2_32(NVTBits));
1108  APInt KnownZero, KnownOne;
1109  DAG.ComputeMaskedBits(N->getOperand(1), HighBitMask, KnownZero, KnownOne);
1110
1111  // If we don't know anything about the high bits, exit.
1112  if (((KnownZero|KnownOne) & HighBitMask) == 0)
1113    return false;
1114
1115  // Get the incoming operand to be shifted.
1116  SDValue InL, InH;
1117  GetExpandedInteger(N->getOperand(0), InL, InH);
1118
1119  // If we know that any of the high bits of the shift amount are one, then we
1120  // can do this as a couple of simple shifts.
1121  if (KnownOne.intersects(HighBitMask)) {
1122    // Mask out the high bit, which we know is set.
1123    Amt = DAG.getNode(ISD::AND, ShTy, Amt,
1124                      DAG.getConstant(~HighBitMask, ShTy));
1125
1126    switch (N->getOpcode()) {
1127    default: assert(0 && "Unknown shift");
1128    case ISD::SHL:
1129      Lo = DAG.getConstant(0, NVT);              // Low part is zero.
1130      Hi = DAG.getNode(ISD::SHL, NVT, InL, Amt); // High part from Lo part.
1131      return true;
1132    case ISD::SRL:
1133      Hi = DAG.getConstant(0, NVT);              // Hi part is zero.
1134      Lo = DAG.getNode(ISD::SRL, NVT, InH, Amt); // Lo part from Hi part.
1135      return true;
1136    case ISD::SRA:
1137      Hi = DAG.getNode(ISD::SRA, NVT, InH,       // Sign extend high part.
1138                       DAG.getConstant(NVTBits-1, ShTy));
1139      Lo = DAG.getNode(ISD::SRA, NVT, InH, Amt); // Lo part from Hi part.
1140      return true;
1141    }
1142  }
1143
1144  // If we know that all of the high bits of the shift amount are zero, then we
1145  // can do this as a couple of simple shifts.
1146  if ((KnownZero & HighBitMask) == HighBitMask) {
1147    // Compute 32-amt.
1148    SDValue Amt2 = DAG.getNode(ISD::SUB, ShTy,
1149                                 DAG.getConstant(NVTBits, ShTy),
1150                                 Amt);
1151    unsigned Op1, Op2;
1152    switch (N->getOpcode()) {
1153    default: assert(0 && "Unknown shift");
1154    case ISD::SHL:  Op1 = ISD::SHL; Op2 = ISD::SRL; break;
1155    case ISD::SRL:
1156    case ISD::SRA:  Op1 = ISD::SRL; Op2 = ISD::SHL; break;
1157    }
1158
1159    Lo = DAG.getNode(N->getOpcode(), NVT, InL, Amt);
1160    Hi = DAG.getNode(ISD::OR, NVT,
1161                     DAG.getNode(Op1, NVT, InH, Amt),
1162                     DAG.getNode(Op2, NVT, InL, Amt2));
1163    return true;
1164  }
1165
1166  return false;
1167}
1168
1169void DAGTypeLegalizer::ExpandIntRes_ADDSUB(SDNode *N,
1170                                           SDValue &Lo, SDValue &Hi) {
1171  // Expand the subcomponents.
1172  SDValue LHSL, LHSH, RHSL, RHSH;
1173  GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1174  GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1175
1176  MVT NVT = LHSL.getValueType();
1177  SDVTList VTList = DAG.getVTList(NVT, MVT::Flag);
1178  SDValue LoOps[2] = { LHSL, RHSL };
1179  SDValue HiOps[3] = { LHSH, RHSH };
1180
1181  // Do not generate ADDC/ADDE or SUBC/SUBE if the target does not support
1182  // them.  TODO: Teach operation legalization how to expand unsupported
1183  // ADDC/ADDE/SUBC/SUBE.  The problem is that these operations generate
1184  // a carry of type MVT::Flag, but there doesn't seem to be any way to
1185  // generate a value of this type in the expanded code sequence.
1186  bool hasCarry =
1187    TLI.isOperationLegal(N->getOpcode() == ISD::ADD ? ISD::ADDC : ISD::SUBC,
1188                         TLI.getTypeToExpandTo(NVT));
1189
1190  if (hasCarry) {
1191    if (N->getOpcode() == ISD::ADD) {
1192      Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
1193      HiOps[2] = Lo.getValue(1);
1194      Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
1195    } else {
1196      Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
1197      HiOps[2] = Lo.getValue(1);
1198      Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
1199    }
1200  } else {
1201    if (N->getOpcode() == ISD::ADD) {
1202      Lo = DAG.getNode(ISD::ADD, VTList, LoOps, 2);
1203      Hi = DAG.getNode(ISD::ADD, VTList, HiOps, 2);
1204      SDValue Cmp1 = DAG.getSetCC(TLI.getSetCCResultType(Lo), Lo, LoOps[0],
1205                                  ISD::SETULT);
1206      SDValue Carry1 = DAG.getNode(ISD::SELECT, NVT, Cmp1,
1207                                   DAG.getConstant(1, NVT),
1208                                   DAG.getConstant(0, NVT));
1209      SDValue Cmp2 = DAG.getSetCC(TLI.getSetCCResultType(Lo), Lo, LoOps[1],
1210                                  ISD::SETULT);
1211      SDValue Carry2 = DAG.getNode(ISD::SELECT, NVT, Cmp2,
1212                                   DAG.getConstant(1, NVT), Carry1);
1213      Hi = DAG.getNode(ISD::ADD, NVT, Hi, Carry2);
1214    } else {
1215      Lo = DAG.getNode(ISD::SUB, VTList, LoOps, 2);
1216      Hi = DAG.getNode(ISD::SUB, VTList, HiOps, 2);
1217      SDValue Cmp = DAG.getSetCC(NVT, LoOps[0], LoOps[1], ISD::SETULT);
1218      SDValue Borrow = DAG.getNode(ISD::SELECT, NVT, Cmp,
1219                                   DAG.getConstant(1, NVT),
1220                                   DAG.getConstant(0, NVT));
1221      Hi = DAG.getNode(ISD::SUB, NVT, Hi, Borrow);
1222    }
1223  }
1224}
1225
1226void DAGTypeLegalizer::ExpandIntRes_ADDSUBC(SDNode *N,
1227                                            SDValue &Lo, SDValue &Hi) {
1228  // Expand the subcomponents.
1229  SDValue LHSL, LHSH, RHSL, RHSH;
1230  GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1231  GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1232  SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
1233  SDValue LoOps[2] = { LHSL, RHSL };
1234  SDValue HiOps[3] = { LHSH, RHSH };
1235
1236  if (N->getOpcode() == ISD::ADDC) {
1237    Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
1238    HiOps[2] = Lo.getValue(1);
1239    Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
1240  } else {
1241    Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
1242    HiOps[2] = Lo.getValue(1);
1243    Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
1244  }
1245
1246  // Legalized the flag result - switch anything that used the old flag to
1247  // use the new one.
1248  ReplaceValueWith(SDValue(N, 1), Hi.getValue(1));
1249}
1250
1251void DAGTypeLegalizer::ExpandIntRes_ADDSUBE(SDNode *N,
1252                                            SDValue &Lo, SDValue &Hi) {
1253  // Expand the subcomponents.
1254  SDValue LHSL, LHSH, RHSL, RHSH;
1255  GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1256  GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1257  SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
1258  SDValue LoOps[3] = { LHSL, RHSL, N->getOperand(2) };
1259  SDValue HiOps[3] = { LHSH, RHSH };
1260
1261  Lo = DAG.getNode(N->getOpcode(), VTList, LoOps, 3);
1262  HiOps[2] = Lo.getValue(1);
1263  Hi = DAG.getNode(N->getOpcode(), VTList, HiOps, 3);
1264
1265  // Legalized the flag result - switch anything that used the old flag to
1266  // use the new one.
1267  ReplaceValueWith(SDValue(N, 1), Hi.getValue(1));
1268}
1269
1270void DAGTypeLegalizer::ExpandIntRes_ANY_EXTEND(SDNode *N,
1271                                               SDValue &Lo, SDValue &Hi) {
1272  MVT NVT = TLI.getTypeToTransformTo(N->getValueType(0));
1273  SDValue Op = N->getOperand(0);
1274  if (Op.getValueType().bitsLE(NVT)) {
1275    // The low part is any extension of the input (which degenerates to a copy).
1276    Lo = DAG.getNode(ISD::ANY_EXTEND, NVT, Op);
1277    Hi = DAG.getNode(ISD::UNDEF, NVT);   // The high part is undefined.
1278  } else {
1279    // For example, extension of an i48 to an i64.  The operand type necessarily
1280    // promotes to the result type, so will end up being expanded too.
1281    assert(getTypeAction(Op.getValueType()) == PromoteInteger &&
1282           "Only know how to promote this result!");
1283    SDValue Res = GetPromotedInteger(Op);
1284    assert(Res.getValueType() == N->getValueType(0) &&
1285           "Operand over promoted?");
1286    // Split the promoted operand.  This will simplify when it is expanded.
1287    SplitInteger(Res, Lo, Hi);
1288  }
1289}
1290
1291void DAGTypeLegalizer::ExpandIntRes_AssertSext(SDNode *N,
1292                                               SDValue &Lo, SDValue &Hi) {
1293  GetExpandedInteger(N->getOperand(0), Lo, Hi);
1294  MVT NVT = Lo.getValueType();
1295  MVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1296  unsigned NVTBits = NVT.getSizeInBits();
1297  unsigned EVTBits = EVT.getSizeInBits();
1298
1299  if (NVTBits < EVTBits) {
1300    Hi = DAG.getNode(ISD::AssertSext, NVT, Hi,
1301                     DAG.getValueType(MVT::getIntegerVT(EVTBits - NVTBits)));
1302  } else {
1303    Lo = DAG.getNode(ISD::AssertSext, NVT, Lo, DAG.getValueType(EVT));
1304    // The high part replicates the sign bit of Lo, make it explicit.
1305    Hi = DAG.getNode(ISD::SRA, NVT, Lo,
1306                     DAG.getConstant(NVTBits-1, TLI.getShiftAmountTy()));
1307  }
1308}
1309
1310void DAGTypeLegalizer::ExpandIntRes_AssertZext(SDNode *N,
1311                                               SDValue &Lo, SDValue &Hi) {
1312  GetExpandedInteger(N->getOperand(0), Lo, Hi);
1313  MVT NVT = Lo.getValueType();
1314  MVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1315  unsigned NVTBits = NVT.getSizeInBits();
1316  unsigned EVTBits = EVT.getSizeInBits();
1317
1318  if (NVTBits < EVTBits) {
1319    Hi = DAG.getNode(ISD::AssertZext, NVT, Hi,
1320                     DAG.getValueType(MVT::getIntegerVT(EVTBits - NVTBits)));
1321  } else {
1322    Lo = DAG.getNode(ISD::AssertZext, NVT, Lo, DAG.getValueType(EVT));
1323    // The high part must be zero, make it explicit.
1324    Hi = DAG.getConstant(0, NVT);
1325  }
1326}
1327
1328void DAGTypeLegalizer::ExpandIntRes_BSWAP(SDNode *N,
1329                                          SDValue &Lo, SDValue &Hi) {
1330  GetExpandedInteger(N->getOperand(0), Hi, Lo);  // Note swapped operands.
1331  Lo = DAG.getNode(ISD::BSWAP, Lo.getValueType(), Lo);
1332  Hi = DAG.getNode(ISD::BSWAP, Hi.getValueType(), Hi);
1333}
1334
1335void DAGTypeLegalizer::ExpandIntRes_Constant(SDNode *N,
1336                                             SDValue &Lo, SDValue &Hi) {
1337  MVT NVT = TLI.getTypeToTransformTo(N->getValueType(0));
1338  unsigned NBitWidth = NVT.getSizeInBits();
1339  const APInt &Cst = cast<ConstantSDNode>(N)->getAPIntValue();
1340  Lo = DAG.getConstant(APInt(Cst).trunc(NBitWidth), NVT);
1341  Hi = DAG.getConstant(Cst.lshr(NBitWidth).trunc(NBitWidth), NVT);
1342}
1343
1344void DAGTypeLegalizer::ExpandIntRes_CTLZ(SDNode *N,
1345                                         SDValue &Lo, SDValue &Hi) {
1346  // ctlz (HiLo) -> Hi != 0 ? ctlz(Hi) : (ctlz(Lo)+32)
1347  GetExpandedInteger(N->getOperand(0), Lo, Hi);
1348  MVT NVT = Lo.getValueType();
1349
1350  SDValue HiNotZero = DAG.getSetCC(TLI.getSetCCResultType(Hi), Hi,
1351                                   DAG.getConstant(0, NVT), ISD::SETNE);
1352
1353  SDValue LoLZ = DAG.getNode(ISD::CTLZ, NVT, Lo);
1354  SDValue HiLZ = DAG.getNode(ISD::CTLZ, NVT, Hi);
1355
1356  Lo = DAG.getNode(ISD::SELECT, NVT, HiNotZero, HiLZ,
1357                   DAG.getNode(ISD::ADD, NVT, LoLZ,
1358                               DAG.getConstant(NVT.getSizeInBits(), NVT)));
1359  Hi = DAG.getConstant(0, NVT);
1360}
1361
1362void DAGTypeLegalizer::ExpandIntRes_CTPOP(SDNode *N,
1363                                          SDValue &Lo, SDValue &Hi) {
1364  // ctpop(HiLo) -> ctpop(Hi)+ctpop(Lo)
1365  GetExpandedInteger(N->getOperand(0), Lo, Hi);
1366  MVT NVT = Lo.getValueType();
1367  Lo = DAG.getNode(ISD::ADD, NVT, DAG.getNode(ISD::CTPOP, NVT, Lo),
1368                   DAG.getNode(ISD::CTPOP, NVT, Hi));
1369  Hi = DAG.getConstant(0, NVT);
1370}
1371
1372void DAGTypeLegalizer::ExpandIntRes_CTTZ(SDNode *N,
1373                                         SDValue &Lo, SDValue &Hi) {
1374  // cttz (HiLo) -> Lo != 0 ? cttz(Lo) : (cttz(Hi)+32)
1375  GetExpandedInteger(N->getOperand(0), Lo, Hi);
1376  MVT NVT = Lo.getValueType();
1377
1378  SDValue LoNotZero = DAG.getSetCC(TLI.getSetCCResultType(Lo), Lo,
1379                                   DAG.getConstant(0, NVT), ISD::SETNE);
1380
1381  SDValue LoLZ = DAG.getNode(ISD::CTTZ, NVT, Lo);
1382  SDValue HiLZ = DAG.getNode(ISD::CTTZ, NVT, Hi);
1383
1384  Lo = DAG.getNode(ISD::SELECT, NVT, LoNotZero, LoLZ,
1385                   DAG.getNode(ISD::ADD, NVT, HiLZ,
1386                               DAG.getConstant(NVT.getSizeInBits(), NVT)));
1387  Hi = DAG.getConstant(0, NVT);
1388}
1389
1390void DAGTypeLegalizer::ExpandIntRes_FP_TO_SINT(SDNode *N, SDValue &Lo,
1391                                               SDValue &Hi) {
1392  MVT VT = N->getValueType(0);
1393  SDValue Op = N->getOperand(0);
1394  RTLIB::Libcall LC = RTLIB::getFPTOSINT(Op.getValueType(), VT);
1395  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-sint conversion!");
1396  SplitInteger(MakeLibCall(LC, VT, &Op, 1, true/*sign irrelevant*/), Lo, Hi);
1397}
1398
1399void DAGTypeLegalizer::ExpandIntRes_FP_TO_UINT(SDNode *N, SDValue &Lo,
1400                                               SDValue &Hi) {
1401  MVT VT = N->getValueType(0);
1402  SDValue Op = N->getOperand(0);
1403  RTLIB::Libcall LC = RTLIB::getFPTOUINT(Op.getValueType(), VT);
1404  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-uint conversion!");
1405  SplitInteger(MakeLibCall(LC, VT, &Op, 1, false/*sign irrelevant*/), Lo, Hi);
1406}
1407
1408void DAGTypeLegalizer::ExpandIntRes_LOAD(LoadSDNode *N,
1409                                         SDValue &Lo, SDValue &Hi) {
1410  if (ISD::isNormalLoad(N)) {
1411    ExpandRes_NormalLoad(N, Lo, Hi);
1412    return;
1413  }
1414
1415  assert(ISD::isUNINDEXEDLoad(N) && "Indexed load during type legalization!");
1416
1417  MVT VT = N->getValueType(0);
1418  MVT NVT = TLI.getTypeToTransformTo(VT);
1419  SDValue Ch  = N->getChain();
1420  SDValue Ptr = N->getBasePtr();
1421  ISD::LoadExtType ExtType = N->getExtensionType();
1422  int SVOffset = N->getSrcValueOffset();
1423  unsigned Alignment = N->getAlignment();
1424  bool isVolatile = N->isVolatile();
1425
1426  assert(NVT.isByteSized() && "Expanded type not byte sized!");
1427
1428  if (N->getMemoryVT().bitsLE(NVT)) {
1429    MVT EVT = N->getMemoryVT();
1430
1431    Lo = DAG.getExtLoad(ExtType, NVT, Ch, Ptr, N->getSrcValue(), SVOffset, EVT,
1432                        isVolatile, Alignment);
1433
1434    // Remember the chain.
1435    Ch = Lo.getValue(1);
1436
1437    if (ExtType == ISD::SEXTLOAD) {
1438      // The high part is obtained by SRA'ing all but one of the bits of the
1439      // lo part.
1440      unsigned LoSize = Lo.getValueType().getSizeInBits();
1441      Hi = DAG.getNode(ISD::SRA, NVT, Lo,
1442                       DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
1443    } else if (ExtType == ISD::ZEXTLOAD) {
1444      // The high part is just a zero.
1445      Hi = DAG.getConstant(0, NVT);
1446    } else {
1447      assert(ExtType == ISD::EXTLOAD && "Unknown extload!");
1448      // The high part is undefined.
1449      Hi = DAG.getNode(ISD::UNDEF, NVT);
1450    }
1451  } else if (TLI.isLittleEndian()) {
1452    // Little-endian - low bits are at low addresses.
1453    Lo = DAG.getLoad(NVT, Ch, Ptr, N->getSrcValue(), SVOffset,
1454                     isVolatile, Alignment);
1455
1456    unsigned ExcessBits =
1457      N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
1458    MVT NEVT = MVT::getIntegerVT(ExcessBits);
1459
1460    // Increment the pointer to the other half.
1461    unsigned IncrementSize = NVT.getSizeInBits()/8;
1462    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
1463                      DAG.getIntPtrConstant(IncrementSize));
1464    Hi = DAG.getExtLoad(ExtType, NVT, Ch, Ptr, N->getSrcValue(),
1465                        SVOffset+IncrementSize, NEVT,
1466                        isVolatile, MinAlign(Alignment, IncrementSize));
1467
1468    // Build a factor node to remember that this load is independent of the
1469    // other one.
1470    Ch = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
1471                     Hi.getValue(1));
1472  } else {
1473    // Big-endian - high bits are at low addresses.  Favor aligned loads at
1474    // the cost of some bit-fiddling.
1475    MVT EVT = N->getMemoryVT();
1476    unsigned EBytes = EVT.getStoreSizeInBits()/8;
1477    unsigned IncrementSize = NVT.getSizeInBits()/8;
1478    unsigned ExcessBits = (EBytes - IncrementSize)*8;
1479
1480    // Load both the high bits and maybe some of the low bits.
1481    Hi = DAG.getExtLoad(ExtType, NVT, Ch, Ptr, N->getSrcValue(), SVOffset,
1482                        MVT::getIntegerVT(EVT.getSizeInBits() - ExcessBits),
1483                        isVolatile, Alignment);
1484
1485    // Increment the pointer to the other half.
1486    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
1487                      DAG.getIntPtrConstant(IncrementSize));
1488    // Load the rest of the low bits.
1489    Lo = DAG.getExtLoad(ISD::ZEXTLOAD, NVT, Ch, Ptr, N->getSrcValue(),
1490                        SVOffset+IncrementSize,
1491                        MVT::getIntegerVT(ExcessBits),
1492                        isVolatile, MinAlign(Alignment, IncrementSize));
1493
1494    // Build a factor node to remember that this load is independent of the
1495    // other one.
1496    Ch = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
1497                     Hi.getValue(1));
1498
1499    if (ExcessBits < NVT.getSizeInBits()) {
1500      // Transfer low bits from the bottom of Hi to the top of Lo.
1501      Lo = DAG.getNode(ISD::OR, NVT, Lo,
1502                       DAG.getNode(ISD::SHL, NVT, Hi,
1503                                   DAG.getConstant(ExcessBits,
1504                                                   TLI.getShiftAmountTy())));
1505      // Move high bits to the right position in Hi.
1506      Hi = DAG.getNode(ExtType == ISD::SEXTLOAD ? ISD::SRA : ISD::SRL, NVT, Hi,
1507                       DAG.getConstant(NVT.getSizeInBits() - ExcessBits,
1508                                       TLI.getShiftAmountTy()));
1509    }
1510  }
1511
1512  // Legalized the chain result - switch anything that used the old chain to
1513  // use the new one.
1514  ReplaceValueWith(SDValue(N, 1), Ch);
1515}
1516
1517void DAGTypeLegalizer::ExpandIntRes_Logical(SDNode *N,
1518                                            SDValue &Lo, SDValue &Hi) {
1519  SDValue LL, LH, RL, RH;
1520  GetExpandedInteger(N->getOperand(0), LL, LH);
1521  GetExpandedInteger(N->getOperand(1), RL, RH);
1522  Lo = DAG.getNode(N->getOpcode(), LL.getValueType(), LL, RL);
1523  Hi = DAG.getNode(N->getOpcode(), LL.getValueType(), LH, RH);
1524}
1525
1526void DAGTypeLegalizer::ExpandIntRes_MUL(SDNode *N,
1527                                        SDValue &Lo, SDValue &Hi) {
1528  MVT VT = N->getValueType(0);
1529  MVT NVT = TLI.getTypeToTransformTo(VT);
1530
1531  bool HasMULHS = TLI.isOperationLegal(ISD::MULHS, NVT);
1532  bool HasMULHU = TLI.isOperationLegal(ISD::MULHU, NVT);
1533  bool HasSMUL_LOHI = TLI.isOperationLegal(ISD::SMUL_LOHI, NVT);
1534  bool HasUMUL_LOHI = TLI.isOperationLegal(ISD::UMUL_LOHI, NVT);
1535  if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
1536    SDValue LL, LH, RL, RH;
1537    GetExpandedInteger(N->getOperand(0), LL, LH);
1538    GetExpandedInteger(N->getOperand(1), RL, RH);
1539    unsigned OuterBitSize = VT.getSizeInBits();
1540    unsigned InnerBitSize = NVT.getSizeInBits();
1541    unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0));
1542    unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1));
1543
1544    APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
1545    if (DAG.MaskedValueIsZero(N->getOperand(0), HighMask) &&
1546        DAG.MaskedValueIsZero(N->getOperand(1), HighMask)) {
1547      // The inputs are both zero-extended.
1548      if (HasUMUL_LOHI) {
1549        // We can emit a umul_lohi.
1550        Lo = DAG.getNode(ISD::UMUL_LOHI, DAG.getVTList(NVT, NVT), LL, RL);
1551        Hi = SDValue(Lo.getNode(), 1);
1552        return;
1553      }
1554      if (HasMULHU) {
1555        // We can emit a mulhu+mul.
1556        Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
1557        Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
1558        return;
1559      }
1560    }
1561    if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
1562      // The input values are both sign-extended.
1563      if (HasSMUL_LOHI) {
1564        // We can emit a smul_lohi.
1565        Lo = DAG.getNode(ISD::SMUL_LOHI, DAG.getVTList(NVT, NVT), LL, RL);
1566        Hi = SDValue(Lo.getNode(), 1);
1567        return;
1568      }
1569      if (HasMULHS) {
1570        // We can emit a mulhs+mul.
1571        Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
1572        Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
1573        return;
1574      }
1575    }
1576    if (HasUMUL_LOHI) {
1577      // Lo,Hi = umul LHS, RHS.
1578      SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI,
1579                                       DAG.getVTList(NVT, NVT), LL, RL);
1580      Lo = UMulLOHI;
1581      Hi = UMulLOHI.getValue(1);
1582      RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
1583      LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
1584      Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
1585      Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
1586      return;
1587    }
1588    if (HasMULHU) {
1589      Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
1590      Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
1591      RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
1592      LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
1593      Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
1594      Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
1595      return;
1596    }
1597  }
1598
1599  // If nothing else, we can make a libcall.
1600  RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1601  if (VT == MVT::i32)
1602    LC = RTLIB::MUL_I32;
1603  else if (VT == MVT::i64)
1604    LC = RTLIB::MUL_I64;
1605  else if (VT == MVT::i128)
1606    LC = RTLIB::MUL_I128;
1607  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported MUL!");
1608
1609  SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1610  SplitInteger(MakeLibCall(LC, VT, Ops, 2, true/*sign irrelevant*/), Lo, Hi);
1611}
1612
1613void DAGTypeLegalizer::ExpandIntRes_SDIV(SDNode *N,
1614                                         SDValue &Lo, SDValue &Hi) {
1615  MVT VT = N->getValueType(0);
1616
1617  RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1618  if (VT == MVT::i32)
1619    LC = RTLIB::SDIV_I32;
1620  else if (VT == MVT::i64)
1621    LC = RTLIB::SDIV_I64;
1622  else if (VT == MVT::i128)
1623    LC = RTLIB::SDIV_I128;
1624  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
1625
1626  SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1627  SplitInteger(MakeLibCall(LC, VT, Ops, 2, true), Lo, Hi);
1628}
1629
1630void DAGTypeLegalizer::ExpandIntRes_Shift(SDNode *N,
1631                                          SDValue &Lo, SDValue &Hi) {
1632  MVT VT = N->getValueType(0);
1633
1634  // If we can emit an efficient shift operation, do so now.  Check to see if
1635  // the RHS is a constant.
1636  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1637    return ExpandShiftByConstant(N, CN->getZExtValue(), Lo, Hi);
1638
1639  // If we can determine that the high bit of the shift is zero or one, even if
1640  // the low bits are variable, emit this shift in an optimized form.
1641  if (ExpandShiftWithKnownAmountBit(N, Lo, Hi))
1642    return;
1643
1644  // If this target supports shift_PARTS, use it.  First, map to the _PARTS opc.
1645  unsigned PartsOpc;
1646  if (N->getOpcode() == ISD::SHL) {
1647    PartsOpc = ISD::SHL_PARTS;
1648  } else if (N->getOpcode() == ISD::SRL) {
1649    PartsOpc = ISD::SRL_PARTS;
1650  } else {
1651    assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
1652    PartsOpc = ISD::SRA_PARTS;
1653  }
1654
1655  // Next check to see if the target supports this SHL_PARTS operation or if it
1656  // will custom expand it.
1657  MVT NVT = TLI.getTypeToTransformTo(VT);
1658  TargetLowering::LegalizeAction Action = TLI.getOperationAction(PartsOpc, NVT);
1659  if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
1660      Action == TargetLowering::Custom) {
1661    // Expand the subcomponents.
1662    SDValue LHSL, LHSH;
1663    GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1664
1665    SDValue Ops[] = { LHSL, LHSH, N->getOperand(1) };
1666    MVT VT = LHSL.getValueType();
1667    Lo = DAG.getNode(PartsOpc, DAG.getNodeValueTypes(VT, VT), 2, Ops, 3);
1668    Hi = Lo.getValue(1);
1669    return;
1670  }
1671
1672  // Otherwise, emit a libcall.
1673  RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1674  bool isSigned;
1675  if (N->getOpcode() == ISD::SHL) {
1676    isSigned = false; /*sign irrelevant*/
1677    if (VT == MVT::i32)
1678      LC = RTLIB::SHL_I32;
1679    else if (VT == MVT::i64)
1680      LC = RTLIB::SHL_I64;
1681    else if (VT == MVT::i128)
1682      LC = RTLIB::SHL_I128;
1683  } else if (N->getOpcode() == ISD::SRL) {
1684    isSigned = false;
1685    if (VT == MVT::i32)
1686      LC = RTLIB::SRL_I32;
1687    else if (VT == MVT::i64)
1688      LC = RTLIB::SRL_I64;
1689    else if (VT == MVT::i128)
1690      LC = RTLIB::SRL_I128;
1691  } else {
1692    assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
1693    isSigned = true;
1694    if (VT == MVT::i32)
1695      LC = RTLIB::SRA_I32;
1696    else if (VT == MVT::i64)
1697      LC = RTLIB::SRA_I64;
1698    else if (VT == MVT::i128)
1699      LC = RTLIB::SRA_I128;
1700  }
1701  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported shift!");
1702
1703  SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1704  SplitInteger(MakeLibCall(LC, VT, Ops, 2, isSigned), Lo, Hi);
1705}
1706
1707void DAGTypeLegalizer::ExpandIntRes_SIGN_EXTEND(SDNode *N,
1708                                                SDValue &Lo, SDValue &Hi) {
1709  MVT NVT = TLI.getTypeToTransformTo(N->getValueType(0));
1710  SDValue Op = N->getOperand(0);
1711  if (Op.getValueType().bitsLE(NVT)) {
1712    // The low part is sign extension of the input (degenerates to a copy).
1713    Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, N->getOperand(0));
1714    // The high part is obtained by SRA'ing all but one of the bits of low part.
1715    unsigned LoSize = NVT.getSizeInBits();
1716    Hi = DAG.getNode(ISD::SRA, NVT, Lo,
1717                     DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
1718  } else {
1719    // For example, extension of an i48 to an i64.  The operand type necessarily
1720    // promotes to the result type, so will end up being expanded too.
1721    assert(getTypeAction(Op.getValueType()) == PromoteInteger &&
1722           "Only know how to promote this result!");
1723    SDValue Res = GetPromotedInteger(Op);
1724    assert(Res.getValueType() == N->getValueType(0) &&
1725           "Operand over promoted?");
1726    // Split the promoted operand.  This will simplify when it is expanded.
1727    SplitInteger(Res, Lo, Hi);
1728    unsigned ExcessBits =
1729      Op.getValueType().getSizeInBits() - NVT.getSizeInBits();
1730    Hi = DAG.getNode(ISD::SIGN_EXTEND_INREG, Hi.getValueType(), Hi,
1731                     DAG.getValueType(MVT::getIntegerVT(ExcessBits)));
1732  }
1733}
1734
1735void DAGTypeLegalizer::
1736ExpandIntRes_SIGN_EXTEND_INREG(SDNode *N, SDValue &Lo, SDValue &Hi) {
1737  GetExpandedInteger(N->getOperand(0), Lo, Hi);
1738  MVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1739
1740  if (EVT.bitsLE(Lo.getValueType())) {
1741    // sext_inreg the low part if needed.
1742    Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, Lo.getValueType(), Lo,
1743                     N->getOperand(1));
1744
1745    // The high part gets the sign extension from the lo-part.  This handles
1746    // things like sextinreg V:i64 from i8.
1747    Hi = DAG.getNode(ISD::SRA, Hi.getValueType(), Lo,
1748                     DAG.getConstant(Hi.getValueType().getSizeInBits()-1,
1749                                     TLI.getShiftAmountTy()));
1750  } else {
1751    // For example, extension of an i48 to an i64.  Leave the low part alone,
1752    // sext_inreg the high part.
1753    unsigned ExcessBits =
1754      EVT.getSizeInBits() - Lo.getValueType().getSizeInBits();
1755    Hi = DAG.getNode(ISD::SIGN_EXTEND_INREG, Hi.getValueType(), Hi,
1756                     DAG.getValueType(MVT::getIntegerVT(ExcessBits)));
1757  }
1758}
1759
1760void DAGTypeLegalizer::ExpandIntRes_SREM(SDNode *N,
1761                                         SDValue &Lo, SDValue &Hi) {
1762  MVT VT = N->getValueType(0);
1763
1764  RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1765  if (VT == MVT::i32)
1766    LC = RTLIB::SREM_I32;
1767  else if (VT == MVT::i64)
1768    LC = RTLIB::SREM_I64;
1769  else if (VT == MVT::i128)
1770    LC = RTLIB::SREM_I128;
1771  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
1772
1773  SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1774  SplitInteger(MakeLibCall(LC, VT, Ops, 2, true), Lo, Hi);
1775}
1776
1777void DAGTypeLegalizer::ExpandIntRes_TRUNCATE(SDNode *N,
1778                                             SDValue &Lo, SDValue &Hi) {
1779  MVT NVT = TLI.getTypeToTransformTo(N->getValueType(0));
1780  Lo = DAG.getNode(ISD::TRUNCATE, NVT, N->getOperand(0));
1781  Hi = DAG.getNode(ISD::SRL, N->getOperand(0).getValueType(), N->getOperand(0),
1782                   DAG.getConstant(NVT.getSizeInBits(),
1783                                   TLI.getShiftAmountTy()));
1784  Hi = DAG.getNode(ISD::TRUNCATE, NVT, Hi);
1785}
1786
1787void DAGTypeLegalizer::ExpandIntRes_UDIV(SDNode *N,
1788                                         SDValue &Lo, SDValue &Hi) {
1789  MVT VT = N->getValueType(0);
1790
1791  RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1792  if (VT == MVT::i32)
1793    LC = RTLIB::UDIV_I32;
1794  else if (VT == MVT::i64)
1795    LC = RTLIB::UDIV_I64;
1796  else if (VT == MVT::i128)
1797    LC = RTLIB::UDIV_I128;
1798  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UDIV!");
1799
1800  SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1801  SplitInteger(MakeLibCall(LC, VT, Ops, 2, false), Lo, Hi);
1802}
1803
1804void DAGTypeLegalizer::ExpandIntRes_UREM(SDNode *N,
1805                                         SDValue &Lo, SDValue &Hi) {
1806  MVT VT = N->getValueType(0);
1807
1808  RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1809  if (VT == MVT::i32)
1810    LC = RTLIB::UREM_I32;
1811  else if (VT == MVT::i64)
1812    LC = RTLIB::UREM_I64;
1813  else if (VT == MVT::i128)
1814    LC = RTLIB::UREM_I128;
1815  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UREM!");
1816
1817  SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1818  SplitInteger(MakeLibCall(LC, VT, Ops, 2, false), Lo, Hi);
1819}
1820
1821void DAGTypeLegalizer::ExpandIntRes_ZERO_EXTEND(SDNode *N,
1822                                                SDValue &Lo, SDValue &Hi) {
1823  MVT NVT = TLI.getTypeToTransformTo(N->getValueType(0));
1824  SDValue Op = N->getOperand(0);
1825  if (Op.getValueType().bitsLE(NVT)) {
1826    // The low part is zero extension of the input (degenerates to a copy).
1827    Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, N->getOperand(0));
1828    Hi = DAG.getConstant(0, NVT);   // The high part is just a zero.
1829  } else {
1830    // For example, extension of an i48 to an i64.  The operand type necessarily
1831    // promotes to the result type, so will end up being expanded too.
1832    assert(getTypeAction(Op.getValueType()) == PromoteInteger &&
1833           "Only know how to promote this result!");
1834    SDValue Res = GetPromotedInteger(Op);
1835    assert(Res.getValueType() == N->getValueType(0) &&
1836           "Operand over promoted?");
1837    // Split the promoted operand.  This will simplify when it is expanded.
1838    SplitInteger(Res, Lo, Hi);
1839    unsigned ExcessBits =
1840      Op.getValueType().getSizeInBits() - NVT.getSizeInBits();
1841    Hi = DAG.getZeroExtendInReg(Hi, MVT::getIntegerVT(ExcessBits));
1842  }
1843}
1844
1845
1846//===----------------------------------------------------------------------===//
1847//  Integer Operand Expansion
1848//===----------------------------------------------------------------------===//
1849
1850/// ExpandIntegerOperand - This method is called when the specified operand of
1851/// the specified node is found to need expansion.  At this point, all of the
1852/// result types of the node are known to be legal, but other operands of the
1853/// node may need promotion or expansion as well as the specified one.
1854bool DAGTypeLegalizer::ExpandIntegerOperand(SDNode *N, unsigned OpNo) {
1855  DEBUG(cerr << "Expand integer operand: "; N->dump(&DAG); cerr << "\n");
1856  SDValue Res = SDValue();
1857
1858  if (TLI.getOperationAction(N->getOpcode(), N->getOperand(OpNo).getValueType())
1859      == TargetLowering::Custom)
1860    Res = TLI.LowerOperation(SDValue(N, 0), DAG);
1861
1862  if (Res.getNode() == 0) {
1863    switch (N->getOpcode()) {
1864    default:
1865  #ifndef NDEBUG
1866      cerr << "ExpandIntegerOperand Op #" << OpNo << ": ";
1867      N->dump(&DAG); cerr << "\n";
1868  #endif
1869      assert(0 && "Do not know how to expand this operator's operand!");
1870      abort();
1871
1872    case ISD::BUILD_VECTOR:    Res = ExpandOp_BUILD_VECTOR(N); break;
1873    case ISD::BIT_CONVERT:     Res = ExpandOp_BIT_CONVERT(N); break;
1874    case ISD::EXTRACT_ELEMENT: Res = ExpandOp_EXTRACT_ELEMENT(N); break;
1875
1876    case ISD::BR_CC:      Res = ExpandIntOp_BR_CC(N); break;
1877    case ISD::SELECT_CC:  Res = ExpandIntOp_SELECT_CC(N); break;
1878    case ISD::SETCC:      Res = ExpandIntOp_SETCC(N); break;
1879    case ISD::SINT_TO_FP: Res = ExpandIntOp_SINT_TO_FP(N); break;
1880    case ISD::STORE:      Res = ExpandIntOp_STORE(cast<StoreSDNode>(N), OpNo);
1881                          break;
1882    case ISD::TRUNCATE:   Res = ExpandIntOp_TRUNCATE(N); break;
1883    case ISD::UINT_TO_FP: Res = ExpandIntOp_UINT_TO_FP(N); break;
1884    }
1885  }
1886
1887  // If the result is null, the sub-method took care of registering results etc.
1888  if (!Res.getNode()) return false;
1889  // If the result is N, the sub-method updated N in place.  Check to see if any
1890  // operands are new, and if so, mark them.
1891  if (Res.getNode() == N) {
1892    // Mark N as new and remark N and its operands.  This allows us to correctly
1893    // revisit N if it needs another step of expansion and allows us to visit
1894    // any new operands to N.
1895    ReanalyzeNode(N);
1896    return true;
1897  }
1898
1899  assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
1900         "Invalid operand expansion");
1901
1902  ReplaceValueWith(SDValue(N, 0), Res);
1903  return false;
1904}
1905
1906/// IntegerExpandSetCCOperands - Expand the operands of a comparison.  This code
1907/// is shared among BR_CC, SELECT_CC, and SETCC handlers.
1908void DAGTypeLegalizer::IntegerExpandSetCCOperands(SDValue &NewLHS,
1909                                                  SDValue &NewRHS,
1910                                                  ISD::CondCode &CCCode) {
1911  SDValue LHSLo, LHSHi, RHSLo, RHSHi;
1912  GetExpandedInteger(NewLHS, LHSLo, LHSHi);
1913  GetExpandedInteger(NewRHS, RHSLo, RHSHi);
1914
1915  MVT VT = NewLHS.getValueType();
1916
1917  if (CCCode == ISD::SETEQ || CCCode == ISD::SETNE) {
1918    if (RHSLo == RHSHi) {
1919      if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo)) {
1920        if (RHSCST->isAllOnesValue()) {
1921          // Equality comparison to -1.
1922          NewLHS = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
1923          NewRHS = RHSLo;
1924          return;
1925        }
1926      }
1927    }
1928
1929    NewLHS = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
1930    NewRHS = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
1931    NewLHS = DAG.getNode(ISD::OR, NewLHS.getValueType(), NewLHS, NewRHS);
1932    NewRHS = DAG.getConstant(0, NewLHS.getValueType());
1933    return;
1934  }
1935
1936  // If this is a comparison of the sign bit, just look at the top part.
1937  // X > -1,  x < 0
1938  if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(NewRHS))
1939    if ((CCCode == ISD::SETLT && CST->isNullValue()) ||     // X < 0
1940        (CCCode == ISD::SETGT && CST->isAllOnesValue())) {  // X > -1
1941      NewLHS = LHSHi;
1942      NewRHS = RHSHi;
1943      return;
1944    }
1945
1946  // FIXME: This generated code sucks.
1947  ISD::CondCode LowCC;
1948  switch (CCCode) {
1949  default: assert(0 && "Unknown integer setcc!");
1950  case ISD::SETLT:
1951  case ISD::SETULT: LowCC = ISD::SETULT; break;
1952  case ISD::SETGT:
1953  case ISD::SETUGT: LowCC = ISD::SETUGT; break;
1954  case ISD::SETLE:
1955  case ISD::SETULE: LowCC = ISD::SETULE; break;
1956  case ISD::SETGE:
1957  case ISD::SETUGE: LowCC = ISD::SETUGE; break;
1958  }
1959
1960  // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
1961  // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
1962  // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
1963
1964  // NOTE: on targets without efficient SELECT of bools, we can always use
1965  // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
1966  TargetLowering::DAGCombinerInfo DagCombineInfo(DAG, false, true, NULL);
1967  SDValue Tmp1, Tmp2;
1968  Tmp1 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSLo), LHSLo, RHSLo, LowCC,
1969                           false, DagCombineInfo);
1970  if (!Tmp1.getNode())
1971    Tmp1 = DAG.getSetCC(TLI.getSetCCResultType(LHSLo), LHSLo, RHSLo, LowCC);
1972  Tmp2 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi,
1973                           CCCode, false, DagCombineInfo);
1974  if (!Tmp2.getNode())
1975    Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi,
1976                       DAG.getCondCode(CCCode));
1977
1978  ConstantSDNode *Tmp1C = dyn_cast<ConstantSDNode>(Tmp1.getNode());
1979  ConstantSDNode *Tmp2C = dyn_cast<ConstantSDNode>(Tmp2.getNode());
1980  if ((Tmp1C && Tmp1C->isNullValue()) ||
1981      (Tmp2C && Tmp2C->isNullValue() &&
1982       (CCCode == ISD::SETLE || CCCode == ISD::SETGE ||
1983        CCCode == ISD::SETUGE || CCCode == ISD::SETULE)) ||
1984      (Tmp2C && Tmp2C->getAPIntValue() == 1 &&
1985       (CCCode == ISD::SETLT || CCCode == ISD::SETGT ||
1986        CCCode == ISD::SETUGT || CCCode == ISD::SETULT))) {
1987    // low part is known false, returns high part.
1988    // For LE / GE, if high part is known false, ignore the low part.
1989    // For LT / GT, if high part is known true, ignore the low part.
1990    NewLHS = Tmp2;
1991    NewRHS = SDValue();
1992    return;
1993  }
1994
1995  NewLHS = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi,
1996                             ISD::SETEQ, false, DagCombineInfo);
1997  if (!NewLHS.getNode())
1998    NewLHS = DAG.getSetCC(TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi,
1999                          ISD::SETEQ);
2000  NewLHS = DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
2001                       NewLHS, Tmp1, Tmp2);
2002  NewRHS = SDValue();
2003}
2004
2005SDValue DAGTypeLegalizer::ExpandIntOp_BR_CC(SDNode *N) {
2006  SDValue NewLHS = N->getOperand(2), NewRHS = N->getOperand(3);
2007  ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(1))->get();
2008  IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode);
2009
2010  // If ExpandSetCCOperands returned a scalar, we need to compare the result
2011  // against zero to select between true and false values.
2012  if (NewRHS.getNode() == 0) {
2013    NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2014    CCCode = ISD::SETNE;
2015  }
2016
2017  // Update N to have the operands specified.
2018  return DAG.UpdateNodeOperands(SDValue(N, 0), N->getOperand(0),
2019                                DAG.getCondCode(CCCode), NewLHS, NewRHS,
2020                                N->getOperand(4));
2021}
2022
2023SDValue DAGTypeLegalizer::ExpandIntOp_SELECT_CC(SDNode *N) {
2024  SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
2025  ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(4))->get();
2026  IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode);
2027
2028  // If ExpandSetCCOperands returned a scalar, we need to compare the result
2029  // against zero to select between true and false values.
2030  if (NewRHS.getNode() == 0) {
2031    NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2032    CCCode = ISD::SETNE;
2033  }
2034
2035  // Update N to have the operands specified.
2036  return DAG.UpdateNodeOperands(SDValue(N, 0), NewLHS, NewRHS,
2037                                N->getOperand(2), N->getOperand(3),
2038                                DAG.getCondCode(CCCode));
2039}
2040
2041SDValue DAGTypeLegalizer::ExpandIntOp_SETCC(SDNode *N) {
2042  SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
2043  ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(2))->get();
2044  IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode);
2045
2046  // If ExpandSetCCOperands returned a scalar, use it.
2047  if (NewRHS.getNode() == 0) {
2048    assert(NewLHS.getValueType() == N->getValueType(0) &&
2049           "Unexpected setcc expansion!");
2050    return NewLHS;
2051  }
2052
2053  // Otherwise, update N to have the operands specified.
2054  return DAG.UpdateNodeOperands(SDValue(N, 0), NewLHS, NewRHS,
2055                                DAG.getCondCode(CCCode));
2056}
2057
2058SDValue DAGTypeLegalizer::ExpandIntOp_SINT_TO_FP(SDNode *N) {
2059  SDValue Op = N->getOperand(0);
2060  MVT DstVT = N->getValueType(0);
2061  RTLIB::Libcall LC = RTLIB::getSINTTOFP(Op.getValueType(), DstVT);
2062  assert(LC != RTLIB::UNKNOWN_LIBCALL &&
2063         "Don't know how to expand this SINT_TO_FP!");
2064  return MakeLibCall(LC, DstVT, &Op, 1, true);
2065}
2066
2067SDValue DAGTypeLegalizer::ExpandIntOp_STORE(StoreSDNode *N, unsigned OpNo) {
2068  if (ISD::isNormalStore(N))
2069    return ExpandOp_NormalStore(N, OpNo);
2070
2071  assert(ISD::isUNINDEXEDStore(N) && "Indexed store during type legalization!");
2072  assert(OpNo == 1 && "Can only expand the stored value so far");
2073
2074  MVT VT = N->getOperand(1).getValueType();
2075  MVT NVT = TLI.getTypeToTransformTo(VT);
2076  SDValue Ch  = N->getChain();
2077  SDValue Ptr = N->getBasePtr();
2078  int SVOffset = N->getSrcValueOffset();
2079  unsigned Alignment = N->getAlignment();
2080  bool isVolatile = N->isVolatile();
2081  SDValue Lo, Hi;
2082
2083  assert(NVT.isByteSized() && "Expanded type not byte sized!");
2084
2085  if (N->getMemoryVT().bitsLE(NVT)) {
2086    GetExpandedInteger(N->getValue(), Lo, Hi);
2087    return DAG.getTruncStore(Ch, Lo, Ptr, N->getSrcValue(), SVOffset,
2088                             N->getMemoryVT(), isVolatile, Alignment);
2089  } else if (TLI.isLittleEndian()) {
2090    // Little-endian - low bits are at low addresses.
2091    GetExpandedInteger(N->getValue(), Lo, Hi);
2092
2093    Lo = DAG.getStore(Ch, Lo, Ptr, N->getSrcValue(), SVOffset,
2094                      isVolatile, Alignment);
2095
2096    unsigned ExcessBits =
2097      N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
2098    MVT NEVT = MVT::getIntegerVT(ExcessBits);
2099
2100    // Increment the pointer to the other half.
2101    unsigned IncrementSize = NVT.getSizeInBits()/8;
2102    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
2103                      DAG.getIntPtrConstant(IncrementSize));
2104    Hi = DAG.getTruncStore(Ch, Hi, Ptr, N->getSrcValue(),
2105                           SVOffset+IncrementSize, NEVT,
2106                           isVolatile, MinAlign(Alignment, IncrementSize));
2107    return DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
2108  } else {
2109    // Big-endian - high bits are at low addresses.  Favor aligned stores at
2110    // the cost of some bit-fiddling.
2111    GetExpandedInteger(N->getValue(), Lo, Hi);
2112
2113    MVT EVT = N->getMemoryVT();
2114    unsigned EBytes = EVT.getStoreSizeInBits()/8;
2115    unsigned IncrementSize = NVT.getSizeInBits()/8;
2116    unsigned ExcessBits = (EBytes - IncrementSize)*8;
2117    MVT HiVT = MVT::getIntegerVT(EVT.getSizeInBits() - ExcessBits);
2118
2119    if (ExcessBits < NVT.getSizeInBits()) {
2120      // Transfer high bits from the top of Lo to the bottom of Hi.
2121      Hi = DAG.getNode(ISD::SHL, NVT, Hi,
2122                       DAG.getConstant(NVT.getSizeInBits() - ExcessBits,
2123                                       TLI.getShiftAmountTy()));
2124      Hi = DAG.getNode(ISD::OR, NVT, Hi,
2125                       DAG.getNode(ISD::SRL, NVT, Lo,
2126                                   DAG.getConstant(ExcessBits,
2127                                                   TLI.getShiftAmountTy())));
2128    }
2129
2130    // Store both the high bits and maybe some of the low bits.
2131    Hi = DAG.getTruncStore(Ch, Hi, Ptr, N->getSrcValue(),
2132                           SVOffset, HiVT, isVolatile, Alignment);
2133
2134    // Increment the pointer to the other half.
2135    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
2136                      DAG.getIntPtrConstant(IncrementSize));
2137    // Store the lowest ExcessBits bits in the second half.
2138    Lo = DAG.getTruncStore(Ch, Lo, Ptr, N->getSrcValue(),
2139                           SVOffset+IncrementSize,
2140                           MVT::getIntegerVT(ExcessBits),
2141                           isVolatile, MinAlign(Alignment, IncrementSize));
2142    return DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
2143  }
2144}
2145
2146SDValue DAGTypeLegalizer::ExpandIntOp_TRUNCATE(SDNode *N) {
2147  SDValue InL, InH;
2148  GetExpandedInteger(N->getOperand(0), InL, InH);
2149  // Just truncate the low part of the source.
2150  return DAG.getNode(ISD::TRUNCATE, N->getValueType(0), InL);
2151}
2152
2153SDValue DAGTypeLegalizer::ExpandIntOp_UINT_TO_FP(SDNode *N) {
2154  SDValue Op = N->getOperand(0);
2155  MVT SrcVT = Op.getValueType();
2156  MVT DstVT = N->getValueType(0);
2157
2158  if (TLI.getOperationAction(ISD::SINT_TO_FP, SrcVT) == TargetLowering::Custom){
2159    // Do a signed conversion then adjust the result.
2160    SDValue SignedConv = DAG.getNode(ISD::SINT_TO_FP, DstVT, Op);
2161    SignedConv = TLI.LowerOperation(SignedConv, DAG);
2162
2163    // The result of the signed conversion needs adjusting if the 'sign bit' of
2164    // the incoming integer was set.  To handle this, we dynamically test to see
2165    // if it is set, and, if so, add a fudge factor.
2166
2167    const uint64_t F32TwoE32  = 0x4F800000ULL;
2168    const uint64_t F32TwoE64  = 0x5F800000ULL;
2169    const uint64_t F32TwoE128 = 0x7F800000ULL;
2170
2171    APInt FF(32, 0);
2172    if (SrcVT == MVT::i32)
2173      FF = APInt(32, F32TwoE32);
2174    else if (SrcVT == MVT::i64)
2175      FF = APInt(32, F32TwoE64);
2176    else if (SrcVT == MVT::i128)
2177      FF = APInt(32, F32TwoE128);
2178    else
2179      assert(false && "Unsupported UINT_TO_FP!");
2180
2181    // Check whether the sign bit is set.
2182    SDValue Lo, Hi;
2183    GetExpandedInteger(Op, Lo, Hi);
2184    SDValue SignSet = DAG.getSetCC(TLI.getSetCCResultType(Hi), Hi,
2185                                   DAG.getConstant(0, Hi.getValueType()),
2186                                   ISD::SETLT);
2187
2188    // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
2189    SDValue FudgePtr = DAG.getConstantPool(ConstantInt::get(FF.zext(64)),
2190                                           TLI.getPointerTy());
2191
2192    // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
2193    SDValue Zero = DAG.getIntPtrConstant(0);
2194    SDValue Four = DAG.getIntPtrConstant(4);
2195    if (TLI.isBigEndian()) std::swap(Zero, Four);
2196    SDValue Offset = DAG.getNode(ISD::SELECT, Zero.getValueType(), SignSet,
2197                                 Zero, Four);
2198    unsigned Alignment =
2199      1 << cast<ConstantPoolSDNode>(FudgePtr)->getAlignment();
2200    FudgePtr = DAG.getNode(ISD::ADD, TLI.getPointerTy(), FudgePtr, Offset);
2201    Alignment = std::min(Alignment, 4u);
2202
2203    // Load the value out, extending it from f32 to the destination float type.
2204    // FIXME: Avoid the extend by constructing the right constant pool?
2205    SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, DstVT, DAG.getEntryNode(),
2206                                   FudgePtr, NULL, 0, MVT::f32,
2207                                   false, Alignment);
2208    return DAG.getNode(ISD::FADD, DstVT, SignedConv, Fudge);
2209  }
2210
2211  // Otherwise, use a libcall.
2212  RTLIB::Libcall LC = RTLIB::getUINTTOFP(SrcVT, DstVT);
2213  assert(LC != RTLIB::UNKNOWN_LIBCALL &&
2214         "Don't know how to expand this UINT_TO_FP!");
2215  return MakeLibCall(LC, DstVT, &Op, 1, true);
2216}
2217