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