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