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