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