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