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