Remove unnecessary default cases in switches that cover all enum values.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeIntegerTypes.cpp
1 //===----- LegalizeIntegerTypes.cpp - Legalization of integer types -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements integer type expansion and promotion for LegalizeTypes.
11 // Promotion is the act of changing a computation in an illegal type into a
12 // computation in a larger type.  For example, implementing i8 arithmetic in an
13 // i32 register (often needed on powerpc).
14 // Expansion is the act of changing a computation in an illegal type into a
15 // computation in two identical registers of a smaller type.  For example,
16 // implementing i64 arithmetic in two i32 registers (often needed on 32-bit
17 // targets).
18 //
19 //===----------------------------------------------------------------------===//
20
21 #include "LegalizeTypes.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/raw_ostream.h"
25 using namespace llvm;
26
27 //===----------------------------------------------------------------------===//
28 //  Integer Result Promotion
29 //===----------------------------------------------------------------------===//
30
31 /// PromoteIntegerResult - This method is called when a result of a node is
32 /// found to be in need of promotion to a larger type.  At this point, the node
33 /// may also have invalid operands or may have other results that need
34 /// expansion, we just know that (at least) one result needs promotion.
35 void DAGTypeLegalizer::PromoteIntegerResult(SDNode *N, unsigned ResNo) {
36   DEBUG(dbgs() << "Promote integer result: "; N->dump(&DAG); dbgs() << "\n");
37   SDValue Res = SDValue();
38
39   // See if the target wants to custom expand this node.
40   if (CustomLowerNode(N, N->getValueType(ResNo), true))
41     return;
42
43   switch (N->getOpcode()) {
44   default:
45 #ifndef NDEBUG
46     dbgs() << "PromoteIntegerResult #" << ResNo << ": ";
47     N->dump(&DAG); dbgs() << "\n";
48 #endif
49     llvm_unreachable("Do not know how to promote this operator!");
50   case ISD::MERGE_VALUES:Res = PromoteIntRes_MERGE_VALUES(N, ResNo); break;
51   case ISD::AssertSext:  Res = PromoteIntRes_AssertSext(N); break;
52   case ISD::AssertZext:  Res = PromoteIntRes_AssertZext(N); break;
53   case ISD::BITCAST:     Res = PromoteIntRes_BITCAST(N); break;
54   case ISD::BSWAP:       Res = PromoteIntRes_BSWAP(N); break;
55   case ISD::BUILD_PAIR:  Res = PromoteIntRes_BUILD_PAIR(N); break;
56   case ISD::Constant:    Res = PromoteIntRes_Constant(N); break;
57   case ISD::CONVERT_RNDSAT:
58                          Res = PromoteIntRes_CONVERT_RNDSAT(N); break;
59   case ISD::CTLZ_ZERO_UNDEF:
60   case ISD::CTLZ:        Res = PromoteIntRes_CTLZ(N); break;
61   case ISD::CTPOP:       Res = PromoteIntRes_CTPOP(N); break;
62   case ISD::CTTZ_ZERO_UNDEF:
63   case ISD::CTTZ:        Res = PromoteIntRes_CTTZ(N); break;
64   case ISD::EXTRACT_VECTOR_ELT:
65                          Res = PromoteIntRes_EXTRACT_VECTOR_ELT(N); break;
66   case ISD::LOAD:        Res = PromoteIntRes_LOAD(cast<LoadSDNode>(N));break;
67   case ISD::SELECT:      Res = PromoteIntRes_SELECT(N); break;
68   case ISD::VSELECT:     Res = PromoteIntRes_VSELECT(N); break;
69   case ISD::SELECT_CC:   Res = PromoteIntRes_SELECT_CC(N); break;
70   case ISD::SETCC:       Res = PromoteIntRes_SETCC(N); break;
71   case ISD::SHL:         Res = PromoteIntRes_SHL(N); break;
72   case ISD::SIGN_EXTEND_INREG:
73                          Res = PromoteIntRes_SIGN_EXTEND_INREG(N); break;
74   case ISD::SRA:         Res = PromoteIntRes_SRA(N); break;
75   case ISD::SRL:         Res = PromoteIntRes_SRL(N); break;
76   case ISD::TRUNCATE:    Res = PromoteIntRes_TRUNCATE(N); break;
77   case ISD::UNDEF:       Res = PromoteIntRes_UNDEF(N); break;
78   case ISD::VAARG:       Res = PromoteIntRes_VAARG(N); break;
79
80   case ISD::EXTRACT_SUBVECTOR:
81                          Res = PromoteIntRes_EXTRACT_SUBVECTOR(N); break;
82   case ISD::VECTOR_SHUFFLE:
83                          Res = PromoteIntRes_VECTOR_SHUFFLE(N); break;
84   case ISD::INSERT_VECTOR_ELT:
85                          Res = PromoteIntRes_INSERT_VECTOR_ELT(N); break;
86   case ISD::BUILD_VECTOR:
87                          Res = PromoteIntRes_BUILD_VECTOR(N); break;
88   case ISD::SCALAR_TO_VECTOR:
89                          Res = PromoteIntRes_SCALAR_TO_VECTOR(N); break;
90   case ISD::CONCAT_VECTORS:
91                          Res = PromoteIntRes_CONCAT_VECTORS(N); break;
92
93   case ISD::SIGN_EXTEND:
94   case ISD::ZERO_EXTEND:
95   case ISD::ANY_EXTEND:  Res = PromoteIntRes_INT_EXTEND(N); break;
96
97   case ISD::FP_TO_SINT:
98   case ISD::FP_TO_UINT:  Res = PromoteIntRes_FP_TO_XINT(N); break;
99
100   case ISD::FP32_TO_FP16:Res = PromoteIntRes_FP32_TO_FP16(N); break;
101
102   case ISD::AND:
103   case ISD::OR:
104   case ISD::XOR:
105   case ISD::ADD:
106   case ISD::SUB:
107   case ISD::MUL:         Res = PromoteIntRes_SimpleIntBinOp(N); break;
108
109   case ISD::SDIV:
110   case ISD::SREM:        Res = PromoteIntRes_SDIV(N); break;
111
112   case ISD::UDIV:
113   case ISD::UREM:        Res = PromoteIntRes_UDIV(N); break;
114
115   case ISD::SADDO:
116   case ISD::SSUBO:       Res = PromoteIntRes_SADDSUBO(N, ResNo); break;
117   case ISD::UADDO:
118   case ISD::USUBO:       Res = PromoteIntRes_UADDSUBO(N, ResNo); break;
119   case ISD::SMULO:
120   case ISD::UMULO:       Res = PromoteIntRes_XMULO(N, ResNo); break;
121
122   case ISD::ATOMIC_LOAD:
123     Res = PromoteIntRes_Atomic0(cast<AtomicSDNode>(N)); break;
124
125   case ISD::ATOMIC_LOAD_ADD:
126   case ISD::ATOMIC_LOAD_SUB:
127   case ISD::ATOMIC_LOAD_AND:
128   case ISD::ATOMIC_LOAD_OR:
129   case ISD::ATOMIC_LOAD_XOR:
130   case ISD::ATOMIC_LOAD_NAND:
131   case ISD::ATOMIC_LOAD_MIN:
132   case ISD::ATOMIC_LOAD_MAX:
133   case ISD::ATOMIC_LOAD_UMIN:
134   case ISD::ATOMIC_LOAD_UMAX:
135   case ISD::ATOMIC_SWAP:
136     Res = PromoteIntRes_Atomic1(cast<AtomicSDNode>(N)); break;
137
138   case ISD::ATOMIC_CMP_SWAP:
139     Res = PromoteIntRes_Atomic2(cast<AtomicSDNode>(N)); break;
140   }
141
142   // If the result is null then the sub-method took care of registering it.
143   if (Res.getNode())
144     SetPromotedInteger(SDValue(N, ResNo), Res);
145 }
146
147 SDValue DAGTypeLegalizer::PromoteIntRes_MERGE_VALUES(SDNode *N,
148                                                      unsigned ResNo) {
149   SDValue Op = DisintegrateMERGE_VALUES(N, ResNo);
150   return GetPromotedInteger(Op);
151 }
152
153 SDValue DAGTypeLegalizer::PromoteIntRes_AssertSext(SDNode *N) {
154   // Sign-extend the new bits, and continue the assertion.
155   SDValue Op = SExtPromotedInteger(N->getOperand(0));
156   return DAG.getNode(ISD::AssertSext, N->getDebugLoc(),
157                      Op.getValueType(), Op, N->getOperand(1));
158 }
159
160 SDValue DAGTypeLegalizer::PromoteIntRes_AssertZext(SDNode *N) {
161   // Zero the new bits, and continue the assertion.
162   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
163   return DAG.getNode(ISD::AssertZext, N->getDebugLoc(),
164                      Op.getValueType(), Op, N->getOperand(1));
165 }
166
167 SDValue DAGTypeLegalizer::PromoteIntRes_Atomic0(AtomicSDNode *N) {
168   EVT ResVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
169   SDValue Res = DAG.getAtomic(N->getOpcode(), N->getDebugLoc(),
170                               N->getMemoryVT(), ResVT,
171                               N->getChain(), N->getBasePtr(),
172                               N->getMemOperand(), N->getOrdering(),
173                               N->getSynchScope());
174   // Legalized the chain result - switch anything that used the old chain to
175   // use the new one.
176   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
177   return Res;
178 }
179
180 SDValue DAGTypeLegalizer::PromoteIntRes_Atomic1(AtomicSDNode *N) {
181   SDValue Op2 = GetPromotedInteger(N->getOperand(2));
182   SDValue Res = DAG.getAtomic(N->getOpcode(), N->getDebugLoc(),
183                               N->getMemoryVT(),
184                               N->getChain(), N->getBasePtr(),
185                               Op2, N->getMemOperand(), N->getOrdering(),
186                               N->getSynchScope());
187   // Legalized the chain result - switch anything that used the old chain to
188   // use the new one.
189   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
190   return Res;
191 }
192
193 SDValue DAGTypeLegalizer::PromoteIntRes_Atomic2(AtomicSDNode *N) {
194   SDValue Op2 = GetPromotedInteger(N->getOperand(2));
195   SDValue Op3 = GetPromotedInteger(N->getOperand(3));
196   SDValue Res = DAG.getAtomic(N->getOpcode(), N->getDebugLoc(),
197                               N->getMemoryVT(), N->getChain(), N->getBasePtr(),
198                               Op2, Op3, N->getMemOperand(), N->getOrdering(),
199                               N->getSynchScope());
200   // Legalized the chain result - switch anything that used the old chain to
201   // use the new one.
202   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
203   return Res;
204 }
205
206 SDValue DAGTypeLegalizer::PromoteIntRes_BITCAST(SDNode *N) {
207   SDValue InOp = N->getOperand(0);
208   EVT InVT = InOp.getValueType();
209   EVT NInVT = TLI.getTypeToTransformTo(*DAG.getContext(), InVT);
210   EVT OutVT = N->getValueType(0);
211   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
212   DebugLoc dl = N->getDebugLoc();
213
214   switch (getTypeAction(InVT)) {
215   case TargetLowering::TypeLegal:
216     break;
217   case TargetLowering::TypePromoteInteger:
218     if (NOutVT.bitsEq(NInVT) && !NOutVT.isVector() && !NInVT.isVector())
219       // The input promotes to the same size.  Convert the promoted value.
220       return DAG.getNode(ISD::BITCAST, dl, NOutVT, GetPromotedInteger(InOp));
221     break;
222   case TargetLowering::TypeSoftenFloat:
223     // Promote the integer operand by hand.
224     return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT, GetSoftenedFloat(InOp));
225   case TargetLowering::TypeExpandInteger:
226   case TargetLowering::TypeExpandFloat:
227     break;
228   case TargetLowering::TypeScalarizeVector:
229     // Convert the element to an integer and promote it by hand.
230     if (!NOutVT.isVector())
231       return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT,
232                          BitConvertToInteger(GetScalarizedVector(InOp)));
233     break;
234   case TargetLowering::TypeSplitVector: {
235     // For example, i32 = BITCAST v2i16 on alpha.  Convert the split
236     // pieces of the input into integers and reassemble in the final type.
237     SDValue Lo, Hi;
238     GetSplitVector(N->getOperand(0), Lo, Hi);
239     Lo = BitConvertToInteger(Lo);
240     Hi = BitConvertToInteger(Hi);
241
242     if (TLI.isBigEndian())
243       std::swap(Lo, Hi);
244
245     InOp = DAG.getNode(ISD::ANY_EXTEND, dl,
246                        EVT::getIntegerVT(*DAG.getContext(),
247                                          NOutVT.getSizeInBits()),
248                        JoinIntegers(Lo, Hi));
249     return DAG.getNode(ISD::BITCAST, dl, NOutVT, InOp);
250   }
251   case TargetLowering::TypeWidenVector:
252     if (NOutVT.bitsEq(NInVT))
253       // The input is widened to the same size.  Convert to the widened value.
254       return DAG.getNode(ISD::BITCAST, dl, NOutVT, GetWidenedVector(InOp));
255   }
256
257   return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT,
258                      CreateStackStoreLoad(InOp, OutVT));
259 }
260
261 SDValue DAGTypeLegalizer::PromoteIntRes_BSWAP(SDNode *N) {
262   SDValue Op = GetPromotedInteger(N->getOperand(0));
263   EVT OVT = N->getValueType(0);
264   EVT NVT = Op.getValueType();
265   DebugLoc dl = N->getDebugLoc();
266
267   unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
268   return DAG.getNode(ISD::SRL, dl, NVT, DAG.getNode(ISD::BSWAP, dl, NVT, Op),
269                      DAG.getConstant(DiffBits, TLI.getPointerTy()));
270 }
271
272 SDValue DAGTypeLegalizer::PromoteIntRes_BUILD_PAIR(SDNode *N) {
273   // The pair element type may be legal, or may not promote to the same type as
274   // the result, for example i14 = BUILD_PAIR (i7, i7).  Handle all cases.
275   return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(),
276                      TLI.getTypeToTransformTo(*DAG.getContext(),
277                      N->getValueType(0)), JoinIntegers(N->getOperand(0),
278                      N->getOperand(1)));
279 }
280
281 SDValue DAGTypeLegalizer::PromoteIntRes_Constant(SDNode *N) {
282   EVT VT = N->getValueType(0);
283   // FIXME there is no actual debug info here
284   DebugLoc dl = N->getDebugLoc();
285   // Zero extend things like i1, sign extend everything else.  It shouldn't
286   // matter in theory which one we pick, but this tends to give better code?
287   unsigned Opc = VT.isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
288   SDValue Result = DAG.getNode(Opc, dl,
289                                TLI.getTypeToTransformTo(*DAG.getContext(), VT),
290                                SDValue(N, 0));
291   assert(isa<ConstantSDNode>(Result) && "Didn't constant fold ext?");
292   return Result;
293 }
294
295 SDValue DAGTypeLegalizer::PromoteIntRes_CONVERT_RNDSAT(SDNode *N) {
296   ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode();
297   assert ((CvtCode == ISD::CVT_SS || CvtCode == ISD::CVT_SU ||
298            CvtCode == ISD::CVT_US || CvtCode == ISD::CVT_UU ||
299            CvtCode == ISD::CVT_SF || CvtCode == ISD::CVT_UF) &&
300           "can only promote integers");
301   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
302   return DAG.getConvertRndSat(OutVT, N->getDebugLoc(), N->getOperand(0),
303                               N->getOperand(1), N->getOperand(2),
304                               N->getOperand(3), N->getOperand(4), CvtCode);
305 }
306
307 SDValue DAGTypeLegalizer::PromoteIntRes_CTLZ(SDNode *N) {
308   // Zero extend to the promoted type and do the count there.
309   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
310   DebugLoc dl = N->getDebugLoc();
311   EVT OVT = N->getValueType(0);
312   EVT NVT = Op.getValueType();
313   Op = DAG.getNode(N->getOpcode(), dl, NVT, Op);
314   // Subtract off the extra leading bits in the bigger type.
315   return DAG.getNode(ISD::SUB, dl, NVT, Op,
316                      DAG.getConstant(NVT.getSizeInBits() -
317                                      OVT.getSizeInBits(), NVT));
318 }
319
320 SDValue DAGTypeLegalizer::PromoteIntRes_CTPOP(SDNode *N) {
321   // Zero extend to the promoted type and do the count there.
322   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
323   return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), Op.getValueType(), Op);
324 }
325
326 SDValue DAGTypeLegalizer::PromoteIntRes_CTTZ(SDNode *N) {
327   SDValue Op = GetPromotedInteger(N->getOperand(0));
328   EVT OVT = N->getValueType(0);
329   EVT NVT = Op.getValueType();
330   DebugLoc dl = N->getDebugLoc();
331   if (N->getOpcode() == ISD::CTTZ) {
332     // The count is the same in the promoted type except if the original
333     // value was zero.  This can be handled by setting the bit just off
334     // the top of the original type.
335     APInt TopBit(NVT.getSizeInBits(), 0);
336     TopBit.setBit(OVT.getSizeInBits());
337     Op = DAG.getNode(ISD::OR, dl, NVT, Op, DAG.getConstant(TopBit, NVT));
338   }
339   return DAG.getNode(N->getOpcode(), dl, NVT, Op);
340 }
341
342 SDValue DAGTypeLegalizer::PromoteIntRes_EXTRACT_VECTOR_ELT(SDNode *N) {
343   DebugLoc dl = N->getDebugLoc();
344   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
345   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, NVT, N->getOperand(0),
346                      N->getOperand(1));
347 }
348
349 SDValue DAGTypeLegalizer::PromoteIntRes_FP_TO_XINT(SDNode *N) {
350   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
351   unsigned NewOpc = N->getOpcode();
352   DebugLoc dl = N->getDebugLoc();
353
354   // If we're promoting a UINT to a larger size and the larger FP_TO_UINT is
355   // not Legal, check to see if we can use FP_TO_SINT instead.  (If both UINT
356   // and SINT conversions are Custom, there is no way to tell which is
357   // preferable. We choose SINT because that's the right thing on PPC.)
358   if (N->getOpcode() == ISD::FP_TO_UINT &&
359       !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
360       TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NVT))
361     NewOpc = ISD::FP_TO_SINT;
362
363   SDValue Res = DAG.getNode(NewOpc, dl, NVT, N->getOperand(0));
364
365   // Assert that the converted value fits in the original type.  If it doesn't
366   // (eg: because the value being converted is too big), then the result of the
367   // original operation was undefined anyway, so the assert is still correct.
368   return DAG.getNode(N->getOpcode() == ISD::FP_TO_UINT ?
369                      ISD::AssertZext : ISD::AssertSext, dl, NVT, Res,
370                      DAG.getValueType(N->getValueType(0).getScalarType()));
371 }
372
373 SDValue DAGTypeLegalizer::PromoteIntRes_FP32_TO_FP16(SDNode *N) {
374   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
375   DebugLoc dl = N->getDebugLoc();
376
377   SDValue Res = DAG.getNode(N->getOpcode(), dl, NVT, N->getOperand(0));
378
379   return DAG.getNode(ISD::AssertZext, dl,
380                      NVT, Res, DAG.getValueType(N->getValueType(0)));
381 }
382
383 SDValue DAGTypeLegalizer::PromoteIntRes_INT_EXTEND(SDNode *N) {
384   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
385   DebugLoc dl = N->getDebugLoc();
386
387   if (getTypeAction(N->getOperand(0).getValueType())
388       == TargetLowering::TypePromoteInteger) {
389     SDValue Res = GetPromotedInteger(N->getOperand(0));
390     assert(Res.getValueType().bitsLE(NVT) && "Extension doesn't make sense!");
391
392     // If the result and operand types are the same after promotion, simplify
393     // to an in-register extension.
394     if (NVT == Res.getValueType()) {
395       // The high bits are not guaranteed to be anything.  Insert an extend.
396       if (N->getOpcode() == ISD::SIGN_EXTEND)
397         return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Res,
398                            DAG.getValueType(N->getOperand(0).getValueType()));
399       if (N->getOpcode() == ISD::ZERO_EXTEND)
400         return DAG.getZeroExtendInReg(Res, dl,
401                       N->getOperand(0).getValueType().getScalarType());
402       assert(N->getOpcode() == ISD::ANY_EXTEND && "Unknown integer extension!");
403       return Res;
404     }
405   }
406
407   // Otherwise, just extend the original operand all the way to the larger type.
408   return DAG.getNode(N->getOpcode(), dl, NVT, N->getOperand(0));
409 }
410
411 SDValue DAGTypeLegalizer::PromoteIntRes_LOAD(LoadSDNode *N) {
412   assert(ISD::isUNINDEXEDLoad(N) && "Indexed load during type legalization!");
413   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
414   ISD::LoadExtType ExtType =
415     ISD::isNON_EXTLoad(N) ? ISD::EXTLOAD : N->getExtensionType();
416   DebugLoc dl = N->getDebugLoc();
417   SDValue Res = DAG.getExtLoad(ExtType, dl, NVT, N->getChain(), N->getBasePtr(),
418                                N->getPointerInfo(),
419                                N->getMemoryVT(), N->isVolatile(),
420                                N->isNonTemporal(), N->getAlignment());
421
422   // Legalized the chain result - switch anything that used the old chain to
423   // use the new one.
424   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
425   return Res;
426 }
427
428 /// Promote the overflow flag of an overflowing arithmetic node.
429 SDValue DAGTypeLegalizer::PromoteIntRes_Overflow(SDNode *N) {
430   // Simply change the return type of the boolean result.
431   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(1));
432   EVT ValueVTs[] = { N->getValueType(0), NVT };
433   SDValue Ops[] = { N->getOperand(0), N->getOperand(1) };
434   SDValue Res = DAG.getNode(N->getOpcode(), N->getDebugLoc(),
435                             DAG.getVTList(ValueVTs, 2), Ops, 2);
436
437   // Modified the sum result - switch anything that used the old sum to use
438   // the new one.
439   ReplaceValueWith(SDValue(N, 0), Res);
440
441   return SDValue(Res.getNode(), 1);
442 }
443
444 SDValue DAGTypeLegalizer::PromoteIntRes_SADDSUBO(SDNode *N, unsigned ResNo) {
445   if (ResNo == 1)
446     return PromoteIntRes_Overflow(N);
447
448   // The operation overflowed iff the result in the larger type is not the
449   // sign extension of its truncation to the original type.
450   SDValue LHS = SExtPromotedInteger(N->getOperand(0));
451   SDValue RHS = SExtPromotedInteger(N->getOperand(1));
452   EVT OVT = N->getOperand(0).getValueType();
453   EVT NVT = LHS.getValueType();
454   DebugLoc dl = N->getDebugLoc();
455
456   // Do the arithmetic in the larger type.
457   unsigned Opcode = N->getOpcode() == ISD::SADDO ? ISD::ADD : ISD::SUB;
458   SDValue Res = DAG.getNode(Opcode, dl, NVT, LHS, RHS);
459
460   // Calculate the overflow flag: sign extend the arithmetic result from
461   // the original type.
462   SDValue Ofl = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Res,
463                             DAG.getValueType(OVT));
464   // Overflowed if and only if this is not equal to Res.
465   Ofl = DAG.getSetCC(dl, N->getValueType(1), Ofl, Res, ISD::SETNE);
466
467   // Use the calculated overflow everywhere.
468   ReplaceValueWith(SDValue(N, 1), Ofl);
469
470   return Res;
471 }
472
473 SDValue DAGTypeLegalizer::PromoteIntRes_SDIV(SDNode *N) {
474   // Sign extend the input.
475   SDValue LHS = SExtPromotedInteger(N->getOperand(0));
476   SDValue RHS = SExtPromotedInteger(N->getOperand(1));
477   return DAG.getNode(N->getOpcode(), N->getDebugLoc(),
478                      LHS.getValueType(), LHS, RHS);
479 }
480
481 SDValue DAGTypeLegalizer::PromoteIntRes_SELECT(SDNode *N) {
482   SDValue LHS = GetPromotedInteger(N->getOperand(1));
483   SDValue RHS = GetPromotedInteger(N->getOperand(2));
484   return DAG.getNode(ISD::SELECT, N->getDebugLoc(),
485                      LHS.getValueType(), N->getOperand(0),LHS,RHS);
486 }
487
488 SDValue DAGTypeLegalizer::PromoteIntRes_VSELECT(SDNode *N) {
489   SDValue Mask = N->getOperand(0);
490   EVT OpTy = N->getOperand(1).getValueType();
491
492   // Promote all the way up to the canonical SetCC type.
493   Mask = PromoteTargetBoolean(Mask, TLI.getSetCCResultType(OpTy));
494   SDValue LHS = GetPromotedInteger(N->getOperand(1));
495   SDValue RHS = GetPromotedInteger(N->getOperand(2));
496   return DAG.getNode(ISD::VSELECT, N->getDebugLoc(),
497                      LHS.getValueType(), Mask, LHS, RHS);
498 }
499
500 SDValue DAGTypeLegalizer::PromoteIntRes_SELECT_CC(SDNode *N) {
501   SDValue LHS = GetPromotedInteger(N->getOperand(2));
502   SDValue RHS = GetPromotedInteger(N->getOperand(3));
503   return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(),
504                      LHS.getValueType(), N->getOperand(0),
505                      N->getOperand(1), LHS, RHS, N->getOperand(4));
506 }
507
508 SDValue DAGTypeLegalizer::PromoteIntRes_SETCC(SDNode *N) {
509   EVT SVT = TLI.getSetCCResultType(N->getOperand(0).getValueType());
510
511   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
512
513   // Only use the result of getSetCCResultType if it is legal,
514   // otherwise just use the promoted result type (NVT).
515   if (!TLI.isTypeLegal(SVT))
516       SVT = NVT;
517
518   DebugLoc dl = N->getDebugLoc();
519   assert(SVT.isVector() == N->getOperand(0).getValueType().isVector() &&
520          "Vector compare must return a vector result!");
521
522   // Get the SETCC result using the canonical SETCC type.
523   SDValue SetCC = DAG.getNode(N->getOpcode(), dl, SVT, N->getOperand(0),
524                               N->getOperand(1), N->getOperand(2));
525
526   assert(NVT.bitsLE(SVT) && "Integer type overpromoted?");
527   // Convert to the expected type.
528   return DAG.getNode(ISD::TRUNCATE, dl, NVT, SetCC);
529 }
530
531 SDValue DAGTypeLegalizer::PromoteIntRes_SHL(SDNode *N) {
532   return DAG.getNode(ISD::SHL, N->getDebugLoc(),
533                 TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0)),
534                      GetPromotedInteger(N->getOperand(0)), N->getOperand(1));
535 }
536
537 SDValue DAGTypeLegalizer::PromoteIntRes_SIGN_EXTEND_INREG(SDNode *N) {
538   SDValue Op = GetPromotedInteger(N->getOperand(0));
539   return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(),
540                      Op.getValueType(), Op, N->getOperand(1));
541 }
542
543 SDValue DAGTypeLegalizer::PromoteIntRes_SimpleIntBinOp(SDNode *N) {
544   // The input may have strange things in the top bits of the registers, but
545   // these operations don't care.  They may have weird bits going out, but
546   // that too is okay if they are integer operations.
547   SDValue LHS = GetPromotedInteger(N->getOperand(0));
548   SDValue RHS = GetPromotedInteger(N->getOperand(1));
549   return DAG.getNode(N->getOpcode(), N->getDebugLoc(),
550                     LHS.getValueType(), LHS, RHS);
551 }
552
553 SDValue DAGTypeLegalizer::PromoteIntRes_SRA(SDNode *N) {
554   // The input value must be properly sign extended.
555   SDValue Res = SExtPromotedInteger(N->getOperand(0));
556   return DAG.getNode(ISD::SRA, N->getDebugLoc(),
557                      Res.getValueType(), Res, N->getOperand(1));
558 }
559
560 SDValue DAGTypeLegalizer::PromoteIntRes_SRL(SDNode *N) {
561   // The input value must be properly zero extended.
562   EVT VT = N->getValueType(0);
563   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
564   SDValue Res = ZExtPromotedInteger(N->getOperand(0));
565   return DAG.getNode(ISD::SRL, N->getDebugLoc(), NVT, Res, N->getOperand(1));
566 }
567
568 SDValue DAGTypeLegalizer::PromoteIntRes_TRUNCATE(SDNode *N) {
569   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
570   SDValue Res;
571   SDValue InOp = N->getOperand(0);
572   DebugLoc dl = N->getDebugLoc();
573
574   switch (getTypeAction(InOp.getValueType())) {
575   default: llvm_unreachable("Unknown type action!");
576   case TargetLowering::TypeLegal:
577   case TargetLowering::TypeExpandInteger:
578     Res = InOp;
579     break;
580   case TargetLowering::TypePromoteInteger:
581     Res = GetPromotedInteger(InOp);
582     break;
583   case TargetLowering::TypeSplitVector:
584     EVT InVT = InOp.getValueType();
585     assert(InVT.isVector() && "Cannot split scalar types");
586     unsigned NumElts = InVT.getVectorNumElements();
587     assert(NumElts == NVT.getVectorNumElements() &&
588            "Dst and Src must have the same number of elements");
589     EVT EltVT = InVT.getScalarType();
590     assert(isPowerOf2_32(NumElts) &&
591            "Promoted vector type must be a power of two");
592
593     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts/2);
594     EVT HalfNVT = EVT::getVectorVT(*DAG.getContext(), NVT.getScalarType(),
595                                    NumElts/2);
596
597     SDValue EOp1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, HalfVT, InOp,
598                                DAG.getIntPtrConstant(0));
599     SDValue EOp2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, HalfVT, InOp,
600                                DAG.getIntPtrConstant(NumElts/2));
601     EOp1 = DAG.getNode(ISD::TRUNCATE, dl, HalfNVT, EOp1);
602     EOp2 = DAG.getNode(ISD::TRUNCATE, dl, HalfNVT, EOp2);
603
604     return DAG.getNode(ISD::CONCAT_VECTORS, dl, NVT, EOp1, EOp2);
605   }
606
607   // Truncate to NVT instead of VT
608   return DAG.getNode(ISD::TRUNCATE, dl, NVT, Res);
609 }
610
611 SDValue DAGTypeLegalizer::PromoteIntRes_UADDSUBO(SDNode *N, unsigned ResNo) {
612   if (ResNo == 1)
613     return PromoteIntRes_Overflow(N);
614
615   // The operation overflowed iff the result in the larger type is not the
616   // zero extension of its truncation to the original type.
617   SDValue LHS = ZExtPromotedInteger(N->getOperand(0));
618   SDValue RHS = ZExtPromotedInteger(N->getOperand(1));
619   EVT OVT = N->getOperand(0).getValueType();
620   EVT NVT = LHS.getValueType();
621   DebugLoc dl = N->getDebugLoc();
622
623   // Do the arithmetic in the larger type.
624   unsigned Opcode = N->getOpcode() == ISD::UADDO ? ISD::ADD : ISD::SUB;
625   SDValue Res = DAG.getNode(Opcode, dl, NVT, LHS, RHS);
626
627   // Calculate the overflow flag: zero extend the arithmetic result from
628   // the original type.
629   SDValue Ofl = DAG.getZeroExtendInReg(Res, dl, OVT);
630   // Overflowed if and only if this is not equal to Res.
631   Ofl = DAG.getSetCC(dl, N->getValueType(1), Ofl, Res, ISD::SETNE);
632
633   // Use the calculated overflow everywhere.
634   ReplaceValueWith(SDValue(N, 1), Ofl);
635
636   return Res;
637 }
638
639 SDValue DAGTypeLegalizer::PromoteIntRes_XMULO(SDNode *N, unsigned ResNo) {
640   // Promote the overflow bit trivially.
641   if (ResNo == 1)
642     return PromoteIntRes_Overflow(N);
643
644   SDValue LHS = N->getOperand(0), RHS = N->getOperand(1);
645   DebugLoc DL = N->getDebugLoc();
646   EVT SmallVT = LHS.getValueType();
647
648   // To determine if the result overflowed in a larger type, we extend the
649   // input to the larger type, do the multiply, then check the high bits of
650   // the result to see if the overflow happened.
651   if (N->getOpcode() == ISD::SMULO) {
652     LHS = SExtPromotedInteger(LHS);
653     RHS = SExtPromotedInteger(RHS);
654   } else {
655     LHS = ZExtPromotedInteger(LHS);
656     RHS = ZExtPromotedInteger(RHS);
657   }
658   SDValue Mul = DAG.getNode(ISD::MUL, DL, LHS.getValueType(), LHS, RHS);
659
660   // Overflow occurred iff the high part of the result does not
661   // zero/sign-extend the low part.
662   SDValue Overflow;
663   if (N->getOpcode() == ISD::UMULO) {
664     // Unsigned overflow occurred iff the high part is non-zero.
665     SDValue Hi = DAG.getNode(ISD::SRL, DL, Mul.getValueType(), Mul,
666                              DAG.getIntPtrConstant(SmallVT.getSizeInBits()));
667     Overflow = DAG.getSetCC(DL, N->getValueType(1), Hi,
668                             DAG.getConstant(0, Hi.getValueType()), ISD::SETNE);
669   } else {
670     // Signed overflow occurred iff the high part does not sign extend the low.
671     SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Mul.getValueType(),
672                                Mul, DAG.getValueType(SmallVT));
673     Overflow = DAG.getSetCC(DL, N->getValueType(1), SExt, Mul, ISD::SETNE);
674   }
675
676   // Use the calculated overflow everywhere.
677   ReplaceValueWith(SDValue(N, 1), Overflow);
678   return Mul;
679 }
680
681 SDValue DAGTypeLegalizer::PromoteIntRes_UDIV(SDNode *N) {
682   // Zero extend the input.
683   SDValue LHS = ZExtPromotedInteger(N->getOperand(0));
684   SDValue RHS = ZExtPromotedInteger(N->getOperand(1));
685   return DAG.getNode(N->getOpcode(), N->getDebugLoc(),
686                      LHS.getValueType(), LHS, RHS);
687 }
688
689 SDValue DAGTypeLegalizer::PromoteIntRes_UNDEF(SDNode *N) {
690   return DAG.getUNDEF(TLI.getTypeToTransformTo(*DAG.getContext(),
691                                                N->getValueType(0)));
692 }
693
694 SDValue DAGTypeLegalizer::PromoteIntRes_VAARG(SDNode *N) {
695   SDValue Chain = N->getOperand(0); // Get the chain.
696   SDValue Ptr = N->getOperand(1); // Get the pointer.
697   EVT VT = N->getValueType(0);
698   DebugLoc dl = N->getDebugLoc();
699
700   EVT RegVT = TLI.getRegisterType(*DAG.getContext(), VT);
701   unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), VT);
702   // The argument is passed as NumRegs registers of type RegVT.
703
704   SmallVector<SDValue, 8> Parts(NumRegs);
705   for (unsigned i = 0; i < NumRegs; ++i) {
706     Parts[i] = DAG.getVAArg(RegVT, dl, Chain, Ptr, N->getOperand(2),
707                             N->getConstantOperandVal(3));
708     Chain = Parts[i].getValue(1);
709   }
710
711   // Handle endianness of the load.
712   if (TLI.isBigEndian())
713     std::reverse(Parts.begin(), Parts.end());
714
715   // Assemble the parts in the promoted type.
716   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
717   SDValue Res = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Parts[0]);
718   for (unsigned i = 1; i < NumRegs; ++i) {
719     SDValue Part = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Parts[i]);
720     // Shift it to the right position and "or" it in.
721     Part = DAG.getNode(ISD::SHL, dl, NVT, Part,
722                        DAG.getConstant(i * RegVT.getSizeInBits(),
723                                        TLI.getPointerTy()));
724     Res = DAG.getNode(ISD::OR, dl, NVT, Res, Part);
725   }
726
727   // Modified the chain result - switch anything that used the old chain to
728   // use the new one.
729   ReplaceValueWith(SDValue(N, 1), Chain);
730
731   return Res;
732 }
733
734 //===----------------------------------------------------------------------===//
735 //  Integer Operand Promotion
736 //===----------------------------------------------------------------------===//
737
738 /// PromoteIntegerOperand - This method is called when the specified operand of
739 /// the specified node is found to need promotion.  At this point, all of the
740 /// result types of the node are known to be legal, but other operands of the
741 /// node may need promotion or expansion as well as the specified one.
742 bool DAGTypeLegalizer::PromoteIntegerOperand(SDNode *N, unsigned OpNo) {
743   DEBUG(dbgs() << "Promote integer operand: "; N->dump(&DAG); dbgs() << "\n");
744   SDValue Res = SDValue();
745
746   if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
747     return false;
748
749   switch (N->getOpcode()) {
750     default:
751   #ifndef NDEBUG
752     dbgs() << "PromoteIntegerOperand Op #" << OpNo << ": ";
753     N->dump(&DAG); dbgs() << "\n";
754   #endif
755     llvm_unreachable("Do not know how to promote this operator's operand!");
756
757   case ISD::ANY_EXTEND:   Res = PromoteIntOp_ANY_EXTEND(N); break;
758   case ISD::ATOMIC_STORE:
759     Res = PromoteIntOp_ATOMIC_STORE(cast<AtomicSDNode>(N));
760     break;
761   case ISD::BITCAST:      Res = PromoteIntOp_BITCAST(N); break;
762   case ISD::BR_CC:        Res = PromoteIntOp_BR_CC(N, OpNo); break;
763   case ISD::BRCOND:       Res = PromoteIntOp_BRCOND(N, OpNo); break;
764   case ISD::BUILD_PAIR:   Res = PromoteIntOp_BUILD_PAIR(N); break;
765   case ISD::BUILD_VECTOR: Res = PromoteIntOp_BUILD_VECTOR(N); break;
766   case ISD::CONCAT_VECTORS: Res = PromoteIntOp_CONCAT_VECTORS(N); break;
767   case ISD::EXTRACT_VECTOR_ELT: Res = PromoteIntOp_EXTRACT_VECTOR_ELT(N); break;
768   case ISD::CONVERT_RNDSAT:
769                           Res = PromoteIntOp_CONVERT_RNDSAT(N); break;
770   case ISD::INSERT_VECTOR_ELT:
771                           Res = PromoteIntOp_INSERT_VECTOR_ELT(N, OpNo);break;
772   case ISD::MEMBARRIER:   Res = PromoteIntOp_MEMBARRIER(N); break;
773   case ISD::SCALAR_TO_VECTOR:
774                           Res = PromoteIntOp_SCALAR_TO_VECTOR(N); break;
775   case ISD::VSELECT:
776   case ISD::SELECT:       Res = PromoteIntOp_SELECT(N, OpNo); break;
777   case ISD::SELECT_CC:    Res = PromoteIntOp_SELECT_CC(N, OpNo); break;
778   case ISD::SETCC:        Res = PromoteIntOp_SETCC(N, OpNo); break;
779   case ISD::SIGN_EXTEND:  Res = PromoteIntOp_SIGN_EXTEND(N); break;
780   case ISD::SINT_TO_FP:   Res = PromoteIntOp_SINT_TO_FP(N); break;
781   case ISD::STORE:        Res = PromoteIntOp_STORE(cast<StoreSDNode>(N),
782                                                    OpNo); break;
783   case ISD::TRUNCATE:     Res = PromoteIntOp_TRUNCATE(N); break;
784   case ISD::FP16_TO_FP32:
785   case ISD::UINT_TO_FP:   Res = PromoteIntOp_UINT_TO_FP(N); break;
786   case ISD::ZERO_EXTEND:  Res = PromoteIntOp_ZERO_EXTEND(N); break;
787
788   case ISD::SHL:
789   case ISD::SRA:
790   case ISD::SRL:
791   case ISD::ROTL:
792   case ISD::ROTR: Res = PromoteIntOp_Shift(N); break;
793   }
794
795   // If the result is null, the sub-method took care of registering results etc.
796   if (!Res.getNode()) return false;
797
798   // If the result is N, the sub-method updated N in place.  Tell the legalizer
799   // core about this.
800   if (Res.getNode() == N)
801     return true;
802
803   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
804          "Invalid operand expansion");
805
806   ReplaceValueWith(SDValue(N, 0), Res);
807   return false;
808 }
809
810 /// PromoteSetCCOperands - Promote the operands of a comparison.  This code is
811 /// shared among BR_CC, SELECT_CC, and SETCC handlers.
812 void DAGTypeLegalizer::PromoteSetCCOperands(SDValue &NewLHS,SDValue &NewRHS,
813                                             ISD::CondCode CCCode) {
814   // We have to insert explicit sign or zero extends.  Note that we could
815   // insert sign extends for ALL conditions, but zero extend is cheaper on
816   // many machines (an AND instead of two shifts), so prefer it.
817   switch (CCCode) {
818   default: llvm_unreachable("Unknown integer comparison!");
819   case ISD::SETEQ:
820   case ISD::SETNE:
821   case ISD::SETUGE:
822   case ISD::SETUGT:
823   case ISD::SETULE:
824   case ISD::SETULT:
825     // ALL of these operations will work if we either sign or zero extend
826     // the operands (including the unsigned comparisons!).  Zero extend is
827     // usually a simpler/cheaper operation, so prefer it.
828     NewLHS = ZExtPromotedInteger(NewLHS);
829     NewRHS = ZExtPromotedInteger(NewRHS);
830     break;
831   case ISD::SETGE:
832   case ISD::SETGT:
833   case ISD::SETLT:
834   case ISD::SETLE:
835     NewLHS = SExtPromotedInteger(NewLHS);
836     NewRHS = SExtPromotedInteger(NewRHS);
837     break;
838   }
839 }
840
841 SDValue DAGTypeLegalizer::PromoteIntOp_ANY_EXTEND(SDNode *N) {
842   SDValue Op = GetPromotedInteger(N->getOperand(0));
843   return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), N->getValueType(0), Op);
844 }
845
846 SDValue DAGTypeLegalizer::PromoteIntOp_ATOMIC_STORE(AtomicSDNode *N) {
847   SDValue Op2 = GetPromotedInteger(N->getOperand(2));
848   return DAG.getAtomic(N->getOpcode(), N->getDebugLoc(), N->getMemoryVT(),
849                        N->getChain(), N->getBasePtr(), Op2, N->getMemOperand(),
850                        N->getOrdering(), N->getSynchScope());
851 }
852
853 SDValue DAGTypeLegalizer::PromoteIntOp_BITCAST(SDNode *N) {
854   // This should only occur in unusual situations like bitcasting to an
855   // x86_fp80, so just turn it into a store+load
856   return CreateStackStoreLoad(N->getOperand(0), N->getValueType(0));
857 }
858
859 SDValue DAGTypeLegalizer::PromoteIntOp_BR_CC(SDNode *N, unsigned OpNo) {
860   assert(OpNo == 2 && "Don't know how to promote this operand!");
861
862   SDValue LHS = N->getOperand(2);
863   SDValue RHS = N->getOperand(3);
864   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(1))->get());
865
866   // The chain (Op#0), CC (#1) and basic block destination (Op#4) are always
867   // legal types.
868   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
869                                 N->getOperand(1), LHS, RHS, N->getOperand(4)),
870                  0);
871 }
872
873 SDValue DAGTypeLegalizer::PromoteIntOp_BRCOND(SDNode *N, unsigned OpNo) {
874   assert(OpNo == 1 && "only know how to promote condition");
875
876   // Promote all the way up to the canonical SetCC type.
877   EVT SVT = TLI.getSetCCResultType(MVT::Other);
878   SDValue Cond = PromoteTargetBoolean(N->getOperand(1), SVT);
879
880   // The chain (Op#0) and basic block destination (Op#2) are always legal types.
881   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0), Cond,
882                                         N->getOperand(2)), 0);
883 }
884
885 SDValue DAGTypeLegalizer::PromoteIntOp_BUILD_PAIR(SDNode *N) {
886   // Since the result type is legal, the operands must promote to it.
887   EVT OVT = N->getOperand(0).getValueType();
888   SDValue Lo = ZExtPromotedInteger(N->getOperand(0));
889   SDValue Hi = GetPromotedInteger(N->getOperand(1));
890   assert(Lo.getValueType() == N->getValueType(0) && "Operand over promoted?");
891   DebugLoc dl = N->getDebugLoc();
892
893   Hi = DAG.getNode(ISD::SHL, dl, N->getValueType(0), Hi,
894                    DAG.getConstant(OVT.getSizeInBits(), TLI.getPointerTy()));
895   return DAG.getNode(ISD::OR, dl, N->getValueType(0), Lo, Hi);
896 }
897
898 SDValue DAGTypeLegalizer::PromoteIntOp_BUILD_VECTOR(SDNode *N) {
899   // The vector type is legal but the element type is not.  This implies
900   // that the vector is a power-of-two in length and that the element
901   // type does not have a strange size (eg: it is not i1).
902   EVT VecVT = N->getValueType(0);
903   unsigned NumElts = VecVT.getVectorNumElements();
904   assert(!(NumElts & 1) && "Legal vector of one illegal element?");
905
906   // Promote the inserted value.  The type does not need to match the
907   // vector element type.  Check that any extra bits introduced will be
908   // truncated away.
909   assert(N->getOperand(0).getValueType().getSizeInBits() >=
910          N->getValueType(0).getVectorElementType().getSizeInBits() &&
911          "Type of inserted value narrower than vector element type!");
912
913   SmallVector<SDValue, 16> NewOps;
914   for (unsigned i = 0; i < NumElts; ++i)
915     NewOps.push_back(GetPromotedInteger(N->getOperand(i)));
916
917   return SDValue(DAG.UpdateNodeOperands(N, &NewOps[0], NumElts), 0);
918 }
919
920 SDValue DAGTypeLegalizer::PromoteIntOp_CONVERT_RNDSAT(SDNode *N) {
921   ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode();
922   assert ((CvtCode == ISD::CVT_SS || CvtCode == ISD::CVT_SU ||
923            CvtCode == ISD::CVT_US || CvtCode == ISD::CVT_UU ||
924            CvtCode == ISD::CVT_FS || CvtCode == ISD::CVT_FU) &&
925            "can only promote integer arguments");
926   SDValue InOp = GetPromotedInteger(N->getOperand(0));
927   return DAG.getConvertRndSat(N->getValueType(0), N->getDebugLoc(), InOp,
928                               N->getOperand(1), N->getOperand(2),
929                               N->getOperand(3), N->getOperand(4), CvtCode);
930 }
931
932 SDValue DAGTypeLegalizer::PromoteIntOp_INSERT_VECTOR_ELT(SDNode *N,
933                                                          unsigned OpNo) {
934   if (OpNo == 1) {
935     // Promote the inserted value.  This is valid because the type does not
936     // have to match the vector element type.
937
938     // Check that any extra bits introduced will be truncated away.
939     assert(N->getOperand(1).getValueType().getSizeInBits() >=
940            N->getValueType(0).getVectorElementType().getSizeInBits() &&
941            "Type of inserted value narrower than vector element type!");
942     return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
943                                   GetPromotedInteger(N->getOperand(1)),
944                                   N->getOperand(2)),
945                    0);
946   }
947
948   assert(OpNo == 2 && "Different operand and result vector types?");
949
950   // Promote the index.
951   SDValue Idx = ZExtPromotedInteger(N->getOperand(2));
952   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
953                                 N->getOperand(1), Idx), 0);
954 }
955
956 SDValue DAGTypeLegalizer::PromoteIntOp_MEMBARRIER(SDNode *N) {
957   SDValue NewOps[6];
958   DebugLoc dl = N->getDebugLoc();
959   NewOps[0] = N->getOperand(0);
960   for (unsigned i = 1; i < array_lengthof(NewOps); ++i) {
961     SDValue Flag = GetPromotedInteger(N->getOperand(i));
962     NewOps[i] = DAG.getZeroExtendInReg(Flag, dl, MVT::i1);
963   }
964   return SDValue(DAG.UpdateNodeOperands(N, NewOps, array_lengthof(NewOps)), 0);
965 }
966
967 SDValue DAGTypeLegalizer::PromoteIntOp_SCALAR_TO_VECTOR(SDNode *N) {
968   // Integer SCALAR_TO_VECTOR operands are implicitly truncated, so just promote
969   // the operand in place.
970   return SDValue(DAG.UpdateNodeOperands(N,
971                                 GetPromotedInteger(N->getOperand(0))), 0);
972 }
973
974 SDValue DAGTypeLegalizer::PromoteIntOp_SELECT(SDNode *N, unsigned OpNo) {
975   assert(OpNo == 0 && "Only know how to promote the condition!");
976   SDValue Cond = N->getOperand(0);
977   EVT OpTy = N->getOperand(1).getValueType();
978
979   // Promote all the way up to the canonical SetCC type.
980   EVT SVT = TLI.getSetCCResultType(N->getOpcode() == ISD::SELECT ?
981                                    OpTy.getScalarType() : OpTy);
982   Cond = PromoteTargetBoolean(Cond, SVT);
983
984   return SDValue(DAG.UpdateNodeOperands(N, Cond, N->getOperand(1),
985                                         N->getOperand(2)), 0);
986 }
987
988 SDValue DAGTypeLegalizer::PromoteIntOp_SELECT_CC(SDNode *N, unsigned OpNo) {
989   assert(OpNo == 0 && "Don't know how to promote this operand!");
990
991   SDValue LHS = N->getOperand(0);
992   SDValue RHS = N->getOperand(1);
993   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(4))->get());
994
995   // The CC (#4) and the possible return values (#2 and #3) have legal types.
996   return SDValue(DAG.UpdateNodeOperands(N, LHS, RHS, N->getOperand(2),
997                                 N->getOperand(3), N->getOperand(4)), 0);
998 }
999
1000 SDValue DAGTypeLegalizer::PromoteIntOp_SETCC(SDNode *N, unsigned OpNo) {
1001   assert(OpNo == 0 && "Don't know how to promote this operand!");
1002
1003   SDValue LHS = N->getOperand(0);
1004   SDValue RHS = N->getOperand(1);
1005   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(2))->get());
1006
1007   // The CC (#2) is always legal.
1008   return SDValue(DAG.UpdateNodeOperands(N, LHS, RHS, N->getOperand(2)), 0);
1009 }
1010
1011 SDValue DAGTypeLegalizer::PromoteIntOp_Shift(SDNode *N) {
1012   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
1013                                 ZExtPromotedInteger(N->getOperand(1))), 0);
1014 }
1015
1016 SDValue DAGTypeLegalizer::PromoteIntOp_SIGN_EXTEND(SDNode *N) {
1017   SDValue Op = GetPromotedInteger(N->getOperand(0));
1018   DebugLoc dl = N->getDebugLoc();
1019   Op = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Op);
1020   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Op.getValueType(),
1021                      Op, DAG.getValueType(N->getOperand(0).getValueType()));
1022 }
1023
1024 SDValue DAGTypeLegalizer::PromoteIntOp_SINT_TO_FP(SDNode *N) {
1025   return SDValue(DAG.UpdateNodeOperands(N,
1026                                 SExtPromotedInteger(N->getOperand(0))), 0);
1027 }
1028
1029 SDValue DAGTypeLegalizer::PromoteIntOp_STORE(StoreSDNode *N, unsigned OpNo){
1030   assert(ISD::isUNINDEXEDStore(N) && "Indexed store during type legalization!");
1031   SDValue Ch = N->getChain(), Ptr = N->getBasePtr();
1032   unsigned Alignment = N->getAlignment();
1033   bool isVolatile = N->isVolatile();
1034   bool isNonTemporal = N->isNonTemporal();
1035   DebugLoc dl = N->getDebugLoc();
1036
1037   SDValue Val = GetPromotedInteger(N->getValue());  // Get promoted value.
1038
1039   // Truncate the value and store the result.
1040   return DAG.getTruncStore(Ch, dl, Val, Ptr, N->getPointerInfo(),
1041                            N->getMemoryVT(),
1042                            isVolatile, isNonTemporal, Alignment);
1043 }
1044
1045 SDValue DAGTypeLegalizer::PromoteIntOp_TRUNCATE(SDNode *N) {
1046   SDValue Op = GetPromotedInteger(N->getOperand(0));
1047   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), N->getValueType(0), Op);
1048 }
1049
1050 SDValue DAGTypeLegalizer::PromoteIntOp_UINT_TO_FP(SDNode *N) {
1051   return SDValue(DAG.UpdateNodeOperands(N,
1052                                 ZExtPromotedInteger(N->getOperand(0))), 0);
1053 }
1054
1055 SDValue DAGTypeLegalizer::PromoteIntOp_ZERO_EXTEND(SDNode *N) {
1056   DebugLoc dl = N->getDebugLoc();
1057   SDValue Op = GetPromotedInteger(N->getOperand(0));
1058   Op = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Op);
1059   return DAG.getZeroExtendInReg(Op, dl,
1060                                 N->getOperand(0).getValueType().getScalarType());
1061 }
1062
1063
1064 //===----------------------------------------------------------------------===//
1065 //  Integer Result Expansion
1066 //===----------------------------------------------------------------------===//
1067
1068 /// ExpandIntegerResult - This method is called when the specified result of the
1069 /// specified node is found to need expansion.  At this point, the node may also
1070 /// have invalid operands or may have other results that need promotion, we just
1071 /// know that (at least) one result needs expansion.
1072 void DAGTypeLegalizer::ExpandIntegerResult(SDNode *N, unsigned ResNo) {
1073   DEBUG(dbgs() << "Expand integer result: "; N->dump(&DAG); dbgs() << "\n");
1074   SDValue Lo, Hi;
1075   Lo = Hi = SDValue();
1076
1077   // See if the target wants to custom expand this node.
1078   if (CustomLowerNode(N, N->getValueType(ResNo), true))
1079     return;
1080
1081   switch (N->getOpcode()) {
1082   default:
1083 #ifndef NDEBUG
1084     dbgs() << "ExpandIntegerResult #" << ResNo << ": ";
1085     N->dump(&DAG); dbgs() << "\n";
1086 #endif
1087     llvm_unreachable("Do not know how to expand the result of this operator!");
1088
1089   case ISD::MERGE_VALUES: SplitRes_MERGE_VALUES(N, ResNo, Lo, Hi); break;
1090   case ISD::SELECT:       SplitRes_SELECT(N, Lo, Hi); break;
1091   case ISD::SELECT_CC:    SplitRes_SELECT_CC(N, Lo, Hi); break;
1092   case ISD::UNDEF:        SplitRes_UNDEF(N, Lo, Hi); break;
1093
1094   case ISD::BITCAST:            ExpandRes_BITCAST(N, Lo, Hi); break;
1095   case ISD::BUILD_PAIR:         ExpandRes_BUILD_PAIR(N, Lo, Hi); break;
1096   case ISD::EXTRACT_ELEMENT:    ExpandRes_EXTRACT_ELEMENT(N, Lo, Hi); break;
1097   case ISD::EXTRACT_VECTOR_ELT: ExpandRes_EXTRACT_VECTOR_ELT(N, Lo, Hi); break;
1098   case ISD::VAARG:              ExpandRes_VAARG(N, Lo, Hi); break;
1099
1100   case ISD::ANY_EXTEND:  ExpandIntRes_ANY_EXTEND(N, Lo, Hi); break;
1101   case ISD::AssertSext:  ExpandIntRes_AssertSext(N, Lo, Hi); break;
1102   case ISD::AssertZext:  ExpandIntRes_AssertZext(N, Lo, Hi); break;
1103   case ISD::BSWAP:       ExpandIntRes_BSWAP(N, Lo, Hi); break;
1104   case ISD::Constant:    ExpandIntRes_Constant(N, Lo, Hi); break;
1105   case ISD::CTLZ_ZERO_UNDEF:
1106   case ISD::CTLZ:        ExpandIntRes_CTLZ(N, Lo, Hi); break;
1107   case ISD::CTPOP:       ExpandIntRes_CTPOP(N, Lo, Hi); break;
1108   case ISD::CTTZ_ZERO_UNDEF:
1109   case ISD::CTTZ:        ExpandIntRes_CTTZ(N, Lo, Hi); break;
1110   case ISD::FP_TO_SINT:  ExpandIntRes_FP_TO_SINT(N, Lo, Hi); break;
1111   case ISD::FP_TO_UINT:  ExpandIntRes_FP_TO_UINT(N, Lo, Hi); break;
1112   case ISD::LOAD:        ExpandIntRes_LOAD(cast<LoadSDNode>(N), Lo, Hi); break;
1113   case ISD::MUL:         ExpandIntRes_MUL(N, Lo, Hi); break;
1114   case ISD::SDIV:        ExpandIntRes_SDIV(N, Lo, Hi); break;
1115   case ISD::SIGN_EXTEND: ExpandIntRes_SIGN_EXTEND(N, Lo, Hi); break;
1116   case ISD::SIGN_EXTEND_INREG: ExpandIntRes_SIGN_EXTEND_INREG(N, Lo, Hi); break;
1117   case ISD::SREM:        ExpandIntRes_SREM(N, Lo, Hi); break;
1118   case ISD::TRUNCATE:    ExpandIntRes_TRUNCATE(N, Lo, Hi); break;
1119   case ISD::UDIV:        ExpandIntRes_UDIV(N, Lo, Hi); break;
1120   case ISD::UREM:        ExpandIntRes_UREM(N, Lo, Hi); break;
1121   case ISD::ZERO_EXTEND: ExpandIntRes_ZERO_EXTEND(N, Lo, Hi); break;
1122   case ISD::ATOMIC_LOAD: ExpandIntRes_ATOMIC_LOAD(N, Lo, Hi); break;
1123
1124   case ISD::ATOMIC_LOAD_ADD:
1125   case ISD::ATOMIC_LOAD_SUB:
1126   case ISD::ATOMIC_LOAD_AND:
1127   case ISD::ATOMIC_LOAD_OR:
1128   case ISD::ATOMIC_LOAD_XOR:
1129   case ISD::ATOMIC_LOAD_NAND:
1130   case ISD::ATOMIC_LOAD_MIN:
1131   case ISD::ATOMIC_LOAD_MAX:
1132   case ISD::ATOMIC_LOAD_UMIN:
1133   case ISD::ATOMIC_LOAD_UMAX:
1134   case ISD::ATOMIC_SWAP: {
1135     std::pair<SDValue, SDValue> Tmp = ExpandAtomic(N);
1136     SplitInteger(Tmp.first, Lo, Hi);
1137     ReplaceValueWith(SDValue(N, 1), Tmp.second);
1138     break;
1139   }
1140
1141   case ISD::AND:
1142   case ISD::OR:
1143   case ISD::XOR: ExpandIntRes_Logical(N, Lo, Hi); break;
1144
1145   case ISD::ADD:
1146   case ISD::SUB: ExpandIntRes_ADDSUB(N, Lo, Hi); break;
1147
1148   case ISD::ADDC:
1149   case ISD::SUBC: ExpandIntRes_ADDSUBC(N, Lo, Hi); break;
1150
1151   case ISD::ADDE:
1152   case ISD::SUBE: ExpandIntRes_ADDSUBE(N, Lo, Hi); break;
1153
1154   case ISD::SHL:
1155   case ISD::SRA:
1156   case ISD::SRL: ExpandIntRes_Shift(N, Lo, Hi); break;
1157
1158   case ISD::SADDO:
1159   case ISD::SSUBO: ExpandIntRes_SADDSUBO(N, Lo, Hi); break;
1160   case ISD::UADDO:
1161   case ISD::USUBO: ExpandIntRes_UADDSUBO(N, Lo, Hi); break;
1162   case ISD::UMULO:
1163   case ISD::SMULO: ExpandIntRes_XMULO(N, Lo, Hi); break;
1164   }
1165
1166   // If Lo/Hi is null, the sub-method took care of registering results etc.
1167   if (Lo.getNode())
1168     SetExpandedInteger(SDValue(N, ResNo), Lo, Hi);
1169 }
1170
1171 /// Lower an atomic node to the appropriate builtin call.
1172 std::pair <SDValue, SDValue> DAGTypeLegalizer::ExpandAtomic(SDNode *Node) {
1173   unsigned Opc = Node->getOpcode();
1174   MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
1175   RTLIB::Libcall LC;
1176
1177   switch (Opc) {
1178   default:
1179     llvm_unreachable("Unhandled atomic intrinsic Expand!");
1180     break;
1181   case ISD::ATOMIC_SWAP:
1182     switch (VT.SimpleTy) {
1183     default: llvm_unreachable("Unexpected value type for atomic!");
1184     case MVT::i8:  LC = RTLIB::SYNC_LOCK_TEST_AND_SET_1; break;
1185     case MVT::i16: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_2; break;
1186     case MVT::i32: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_4; break;
1187     case MVT::i64: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_8; break;
1188     }
1189     break;
1190   case ISD::ATOMIC_CMP_SWAP:
1191     switch (VT.SimpleTy) {
1192     default: llvm_unreachable("Unexpected value type for atomic!");
1193     case MVT::i8:  LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_1; break;
1194     case MVT::i16: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_2; break;
1195     case MVT::i32: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_4; break;
1196     case MVT::i64: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_8; break;
1197     }
1198     break;
1199   case ISD::ATOMIC_LOAD_ADD:
1200     switch (VT.SimpleTy) {
1201     default: llvm_unreachable("Unexpected value type for atomic!");
1202     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_ADD_1; break;
1203     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_ADD_2; break;
1204     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_ADD_4; break;
1205     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_ADD_8; break;
1206     }
1207     break;
1208   case ISD::ATOMIC_LOAD_SUB:
1209     switch (VT.SimpleTy) {
1210     default: llvm_unreachable("Unexpected value type for atomic!");
1211     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_SUB_1; break;
1212     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_SUB_2; break;
1213     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_SUB_4; break;
1214     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_SUB_8; break;
1215     }
1216     break;
1217   case ISD::ATOMIC_LOAD_AND:
1218     switch (VT.SimpleTy) {
1219     default: llvm_unreachable("Unexpected value type for atomic!");
1220     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_AND_1; break;
1221     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_AND_2; break;
1222     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_AND_4; break;
1223     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_AND_8; break;
1224     }
1225     break;
1226   case ISD::ATOMIC_LOAD_OR:
1227     switch (VT.SimpleTy) {
1228     default: llvm_unreachable("Unexpected value type for atomic!");
1229     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_OR_1; break;
1230     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_OR_2; break;
1231     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_OR_4; break;
1232     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_OR_8; break;
1233     }
1234     break;
1235   case ISD::ATOMIC_LOAD_XOR:
1236     switch (VT.SimpleTy) {
1237     default: llvm_unreachable("Unexpected value type for atomic!");
1238     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_XOR_1; break;
1239     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_XOR_2; break;
1240     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_XOR_4; break;
1241     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_XOR_8; break;
1242     }
1243     break;
1244   case ISD::ATOMIC_LOAD_NAND:
1245     switch (VT.SimpleTy) {
1246     default: llvm_unreachable("Unexpected value type for atomic!");
1247     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_NAND_1; break;
1248     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_NAND_2; break;
1249     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_NAND_4; break;
1250     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_NAND_8; break;
1251     }
1252     break;
1253   }
1254
1255   return ExpandChainLibCall(LC, Node, false);
1256 }
1257
1258 /// ExpandShiftByConstant - N is a shift by a value that needs to be expanded,
1259 /// and the shift amount is a constant 'Amt'.  Expand the operation.
1260 void DAGTypeLegalizer::ExpandShiftByConstant(SDNode *N, unsigned Amt,
1261                                              SDValue &Lo, SDValue &Hi) {
1262   DebugLoc DL = N->getDebugLoc();
1263   // Expand the incoming operand to be shifted, so that we have its parts
1264   SDValue InL, InH;
1265   GetExpandedInteger(N->getOperand(0), InL, InH);
1266
1267   EVT NVT = InL.getValueType();
1268   unsigned VTBits = N->getValueType(0).getSizeInBits();
1269   unsigned NVTBits = NVT.getSizeInBits();
1270   EVT ShTy = N->getOperand(1).getValueType();
1271
1272   if (N->getOpcode() == ISD::SHL) {
1273     if (Amt > VTBits) {
1274       Lo = Hi = DAG.getConstant(0, NVT);
1275     } else if (Amt > NVTBits) {
1276       Lo = DAG.getConstant(0, NVT);
1277       Hi = DAG.getNode(ISD::SHL, DL,
1278                        NVT, InL, DAG.getConstant(Amt-NVTBits, ShTy));
1279     } else if (Amt == NVTBits) {
1280       Lo = DAG.getConstant(0, NVT);
1281       Hi = InL;
1282     } else if (Amt == 1 &&
1283                TLI.isOperationLegalOrCustom(ISD::ADDC,
1284                               TLI.getTypeToExpandTo(*DAG.getContext(), NVT))) {
1285       // Emit this X << 1 as X+X.
1286       SDVTList VTList = DAG.getVTList(NVT, MVT::Glue);
1287       SDValue LoOps[2] = { InL, InL };
1288       Lo = DAG.getNode(ISD::ADDC, DL, VTList, LoOps, 2);
1289       SDValue HiOps[3] = { InH, InH, Lo.getValue(1) };
1290       Hi = DAG.getNode(ISD::ADDE, DL, VTList, HiOps, 3);
1291     } else {
1292       Lo = DAG.getNode(ISD::SHL, DL, NVT, InL, DAG.getConstant(Amt, ShTy));
1293       Hi = DAG.getNode(ISD::OR, DL, NVT,
1294                        DAG.getNode(ISD::SHL, DL, NVT, InH,
1295                                    DAG.getConstant(Amt, ShTy)),
1296                        DAG.getNode(ISD::SRL, DL, NVT, InL,
1297                                    DAG.getConstant(NVTBits-Amt, ShTy)));
1298     }
1299     return;
1300   }
1301
1302   if (N->getOpcode() == ISD::SRL) {
1303     if (Amt > VTBits) {
1304       Lo = DAG.getConstant(0, NVT);
1305       Hi = DAG.getConstant(0, NVT);
1306     } else if (Amt > NVTBits) {
1307       Lo = DAG.getNode(ISD::SRL, DL,
1308                        NVT, InH, DAG.getConstant(Amt-NVTBits,ShTy));
1309       Hi = DAG.getConstant(0, NVT);
1310     } else if (Amt == NVTBits) {
1311       Lo = InH;
1312       Hi = DAG.getConstant(0, NVT);
1313     } else {
1314       Lo = DAG.getNode(ISD::OR, DL, NVT,
1315                        DAG.getNode(ISD::SRL, DL, NVT, InL,
1316                                    DAG.getConstant(Amt, ShTy)),
1317                        DAG.getNode(ISD::SHL, DL, NVT, InH,
1318                                    DAG.getConstant(NVTBits-Amt, ShTy)));
1319       Hi = DAG.getNode(ISD::SRL, DL, NVT, InH, DAG.getConstant(Amt, ShTy));
1320     }
1321     return;
1322   }
1323
1324   assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
1325   if (Amt > VTBits) {
1326     Hi = Lo = DAG.getNode(ISD::SRA, DL, NVT, InH,
1327                           DAG.getConstant(NVTBits-1, ShTy));
1328   } else if (Amt > NVTBits) {
1329     Lo = DAG.getNode(ISD::SRA, DL, NVT, InH,
1330                      DAG.getConstant(Amt-NVTBits, ShTy));
1331     Hi = DAG.getNode(ISD::SRA, DL, NVT, InH,
1332                      DAG.getConstant(NVTBits-1, ShTy));
1333   } else if (Amt == NVTBits) {
1334     Lo = InH;
1335     Hi = DAG.getNode(ISD::SRA, DL, NVT, InH,
1336                      DAG.getConstant(NVTBits-1, ShTy));
1337   } else {
1338     Lo = DAG.getNode(ISD::OR, DL, NVT,
1339                      DAG.getNode(ISD::SRL, DL, NVT, InL,
1340                                  DAG.getConstant(Amt, ShTy)),
1341                      DAG.getNode(ISD::SHL, DL, NVT, InH,
1342                                  DAG.getConstant(NVTBits-Amt, ShTy)));
1343     Hi = DAG.getNode(ISD::SRA, DL, NVT, InH, DAG.getConstant(Amt, ShTy));
1344   }
1345 }
1346
1347 /// ExpandShiftWithKnownAmountBit - Try to determine whether we can simplify
1348 /// this shift based on knowledge of the high bit of the shift amount.  If we
1349 /// can tell this, we know that it is >= 32 or < 32, without knowing the actual
1350 /// shift amount.
1351 bool DAGTypeLegalizer::
1352 ExpandShiftWithKnownAmountBit(SDNode *N, SDValue &Lo, SDValue &Hi) {
1353   SDValue Amt = N->getOperand(1);
1354   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1355   EVT ShTy = Amt.getValueType();
1356   unsigned ShBits = ShTy.getScalarType().getSizeInBits();
1357   unsigned NVTBits = NVT.getScalarType().getSizeInBits();
1358   assert(isPowerOf2_32(NVTBits) &&
1359          "Expanded integer type size not a power of two!");
1360   DebugLoc dl = N->getDebugLoc();
1361
1362   APInt HighBitMask = APInt::getHighBitsSet(ShBits, ShBits - Log2_32(NVTBits));
1363   APInt KnownZero, KnownOne;
1364   DAG.ComputeMaskedBits(N->getOperand(1), HighBitMask, KnownZero, KnownOne);
1365
1366   // If we don't know anything about the high bits, exit.
1367   if (((KnownZero|KnownOne) & HighBitMask) == 0)
1368     return false;
1369
1370   // Get the incoming operand to be shifted.
1371   SDValue InL, InH;
1372   GetExpandedInteger(N->getOperand(0), InL, InH);
1373
1374   // If we know that any of the high bits of the shift amount are one, then we
1375   // can do this as a couple of simple shifts.
1376   if (KnownOne.intersects(HighBitMask)) {
1377     // Mask out the high bit, which we know is set.
1378     Amt = DAG.getNode(ISD::AND, dl, ShTy, Amt,
1379                       DAG.getConstant(~HighBitMask, ShTy));
1380
1381     switch (N->getOpcode()) {
1382     default: llvm_unreachable("Unknown shift");
1383     case ISD::SHL:
1384       Lo = DAG.getConstant(0, NVT);              // Low part is zero.
1385       Hi = DAG.getNode(ISD::SHL, dl, NVT, InL, Amt); // High part from Lo part.
1386       return true;
1387     case ISD::SRL:
1388       Hi = DAG.getConstant(0, NVT);              // Hi part is zero.
1389       Lo = DAG.getNode(ISD::SRL, dl, NVT, InH, Amt); // Lo part from Hi part.
1390       return true;
1391     case ISD::SRA:
1392       Hi = DAG.getNode(ISD::SRA, dl, NVT, InH,       // Sign extend high part.
1393                        DAG.getConstant(NVTBits-1, ShTy));
1394       Lo = DAG.getNode(ISD::SRA, dl, NVT, InH, Amt); // Lo part from Hi part.
1395       return true;
1396     }
1397   }
1398
1399 #if 0
1400   // FIXME: This code is broken for shifts with a zero amount!
1401   // If we know that all of the high bits of the shift amount are zero, then we
1402   // can do this as a couple of simple shifts.
1403   if ((KnownZero & HighBitMask) == HighBitMask) {
1404     // Compute 32-amt.
1405     SDValue Amt2 = DAG.getNode(ISD::SUB, ShTy,
1406                                  DAG.getConstant(NVTBits, ShTy),
1407                                  Amt);
1408     unsigned Op1, Op2;
1409     switch (N->getOpcode()) {
1410     default: llvm_unreachable("Unknown shift");
1411     case ISD::SHL:  Op1 = ISD::SHL; Op2 = ISD::SRL; break;
1412     case ISD::SRL:
1413     case ISD::SRA:  Op1 = ISD::SRL; Op2 = ISD::SHL; break;
1414     }
1415
1416     Lo = DAG.getNode(N->getOpcode(), NVT, InL, Amt);
1417     Hi = DAG.getNode(ISD::OR, NVT,
1418                      DAG.getNode(Op1, NVT, InH, Amt),
1419                      DAG.getNode(Op2, NVT, InL, Amt2));
1420     return true;
1421   }
1422 #endif
1423
1424   return false;
1425 }
1426
1427 /// ExpandShiftWithUnknownAmountBit - Fully general expansion of integer shift
1428 /// of any size.
1429 bool DAGTypeLegalizer::
1430 ExpandShiftWithUnknownAmountBit(SDNode *N, SDValue &Lo, SDValue &Hi) {
1431   SDValue Amt = N->getOperand(1);
1432   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1433   EVT ShTy = Amt.getValueType();
1434   unsigned NVTBits = NVT.getSizeInBits();
1435   assert(isPowerOf2_32(NVTBits) &&
1436          "Expanded integer type size not a power of two!");
1437   DebugLoc dl = N->getDebugLoc();
1438
1439   // Get the incoming operand to be shifted.
1440   SDValue InL, InH;
1441   GetExpandedInteger(N->getOperand(0), InL, InH);
1442
1443   SDValue NVBitsNode = DAG.getConstant(NVTBits, ShTy);
1444   SDValue AmtExcess = DAG.getNode(ISD::SUB, dl, ShTy, Amt, NVBitsNode);
1445   SDValue AmtLack = DAG.getNode(ISD::SUB, dl, ShTy, NVBitsNode, Amt);
1446   SDValue isShort = DAG.getSetCC(dl, TLI.getSetCCResultType(ShTy),
1447                                  Amt, NVBitsNode, ISD::SETULT);
1448
1449   SDValue LoS, HiS, LoL, HiL;
1450   switch (N->getOpcode()) {
1451   default: llvm_unreachable("Unknown shift");
1452   case ISD::SHL:
1453     // Short: ShAmt < NVTBits
1454     LoS = DAG.getNode(ISD::SHL, dl, NVT, InL, Amt);
1455     HiS = DAG.getNode(ISD::OR, dl, NVT,
1456                       DAG.getNode(ISD::SHL, dl, NVT, InH, Amt),
1457     // FIXME: If Amt is zero, the following shift generates an undefined result
1458     // on some architectures.
1459                       DAG.getNode(ISD::SRL, dl, NVT, InL, AmtLack));
1460
1461     // Long: ShAmt >= NVTBits
1462     LoL = DAG.getConstant(0, NVT);                        // Lo part is zero.
1463     HiL = DAG.getNode(ISD::SHL, dl, NVT, InL, AmtExcess); // Hi from Lo part.
1464
1465     Lo = DAG.getNode(ISD::SELECT, dl, NVT, isShort, LoS, LoL);
1466     Hi = DAG.getNode(ISD::SELECT, dl, NVT, isShort, HiS, HiL);
1467     return true;
1468   case ISD::SRL:
1469     // Short: ShAmt < NVTBits
1470     HiS = DAG.getNode(ISD::SRL, dl, NVT, InH, Amt);
1471     LoS = DAG.getNode(ISD::OR, dl, NVT,
1472                       DAG.getNode(ISD::SRL, dl, NVT, InL, Amt),
1473     // FIXME: If Amt is zero, the following shift generates an undefined result
1474     // on some architectures.
1475                       DAG.getNode(ISD::SHL, dl, NVT, InH, AmtLack));
1476
1477     // Long: ShAmt >= NVTBits
1478     HiL = DAG.getConstant(0, NVT);                        // Hi part is zero.
1479     LoL = DAG.getNode(ISD::SRL, dl, NVT, InH, AmtExcess); // Lo from Hi part.
1480
1481     Lo = DAG.getNode(ISD::SELECT, dl, NVT, isShort, LoS, LoL);
1482     Hi = DAG.getNode(ISD::SELECT, dl, NVT, isShort, HiS, HiL);
1483     return true;
1484   case ISD::SRA:
1485     // Short: ShAmt < NVTBits
1486     HiS = DAG.getNode(ISD::SRA, dl, NVT, InH, Amt);
1487     LoS = DAG.getNode(ISD::OR, dl, NVT,
1488                       DAG.getNode(ISD::SRL, dl, NVT, InL, Amt),
1489     // FIXME: If Amt is zero, the following shift generates an undefined result
1490     // on some architectures.
1491                       DAG.getNode(ISD::SHL, dl, NVT, InH, AmtLack));
1492
1493     // Long: ShAmt >= NVTBits
1494     HiL = DAG.getNode(ISD::SRA, dl, NVT, InH,             // Sign of Hi part.
1495                       DAG.getConstant(NVTBits-1, ShTy));
1496     LoL = DAG.getNode(ISD::SRA, dl, NVT, InH, AmtExcess); // Lo from Hi part.
1497
1498     Lo = DAG.getNode(ISD::SELECT, dl, NVT, isShort, LoS, LoL);
1499     Hi = DAG.getNode(ISD::SELECT, dl, NVT, isShort, HiS, HiL);
1500     return true;
1501   }
1502
1503   return false;
1504 }
1505
1506 void DAGTypeLegalizer::ExpandIntRes_ADDSUB(SDNode *N,
1507                                            SDValue &Lo, SDValue &Hi) {
1508   DebugLoc dl = N->getDebugLoc();
1509   // Expand the subcomponents.
1510   SDValue LHSL, LHSH, RHSL, RHSH;
1511   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1512   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1513
1514   EVT NVT = LHSL.getValueType();
1515   SDValue LoOps[2] = { LHSL, RHSL };
1516   SDValue HiOps[3] = { LHSH, RHSH };
1517
1518   // Do not generate ADDC/ADDE or SUBC/SUBE if the target does not support
1519   // them.  TODO: Teach operation legalization how to expand unsupported
1520   // ADDC/ADDE/SUBC/SUBE.  The problem is that these operations generate
1521   // a carry of type MVT::Glue, but there doesn't seem to be any way to
1522   // generate a value of this type in the expanded code sequence.
1523   bool hasCarry =
1524     TLI.isOperationLegalOrCustom(N->getOpcode() == ISD::ADD ?
1525                                    ISD::ADDC : ISD::SUBC,
1526                                  TLI.getTypeToExpandTo(*DAG.getContext(), NVT));
1527
1528   if (hasCarry) {
1529     SDVTList VTList = DAG.getVTList(NVT, MVT::Glue);
1530     if (N->getOpcode() == ISD::ADD) {
1531       Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps, 2);
1532       HiOps[2] = Lo.getValue(1);
1533       Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps, 3);
1534     } else {
1535       Lo = DAG.getNode(ISD::SUBC, dl, VTList, LoOps, 2);
1536       HiOps[2] = Lo.getValue(1);
1537       Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps, 3);
1538     }
1539     return;
1540   }
1541
1542   if (N->getOpcode() == ISD::ADD) {
1543     Lo = DAG.getNode(ISD::ADD, dl, NVT, LoOps, 2);
1544     Hi = DAG.getNode(ISD::ADD, dl, NVT, HiOps, 2);
1545     SDValue Cmp1 = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), Lo, LoOps[0],
1546                                 ISD::SETULT);
1547     SDValue Carry1 = DAG.getNode(ISD::SELECT, dl, NVT, Cmp1,
1548                                  DAG.getConstant(1, NVT),
1549                                  DAG.getConstant(0, NVT));
1550     SDValue Cmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), Lo, LoOps[1],
1551                                 ISD::SETULT);
1552     SDValue Carry2 = DAG.getNode(ISD::SELECT, dl, NVT, Cmp2,
1553                                  DAG.getConstant(1, NVT), Carry1);
1554     Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, Carry2);
1555   } else {
1556     Lo = DAG.getNode(ISD::SUB, dl, NVT, LoOps, 2);
1557     Hi = DAG.getNode(ISD::SUB, dl, NVT, HiOps, 2);
1558     SDValue Cmp =
1559       DAG.getSetCC(dl, TLI.getSetCCResultType(LoOps[0].getValueType()),
1560                    LoOps[0], LoOps[1], ISD::SETULT);
1561     SDValue Borrow = DAG.getNode(ISD::SELECT, dl, NVT, Cmp,
1562                                  DAG.getConstant(1, NVT),
1563                                  DAG.getConstant(0, NVT));
1564     Hi = DAG.getNode(ISD::SUB, dl, NVT, Hi, Borrow);
1565   }
1566 }
1567
1568 void DAGTypeLegalizer::ExpandIntRes_ADDSUBC(SDNode *N,
1569                                             SDValue &Lo, SDValue &Hi) {
1570   // Expand the subcomponents.
1571   SDValue LHSL, LHSH, RHSL, RHSH;
1572   DebugLoc dl = N->getDebugLoc();
1573   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1574   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1575   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Glue);
1576   SDValue LoOps[2] = { LHSL, RHSL };
1577   SDValue HiOps[3] = { LHSH, RHSH };
1578
1579   if (N->getOpcode() == ISD::ADDC) {
1580     Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps, 2);
1581     HiOps[2] = Lo.getValue(1);
1582     Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps, 3);
1583   } else {
1584     Lo = DAG.getNode(ISD::SUBC, dl, VTList, LoOps, 2);
1585     HiOps[2] = Lo.getValue(1);
1586     Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps, 3);
1587   }
1588
1589   // Legalized the flag result - switch anything that used the old flag to
1590   // use the new one.
1591   ReplaceValueWith(SDValue(N, 1), Hi.getValue(1));
1592 }
1593
1594 void DAGTypeLegalizer::ExpandIntRes_ADDSUBE(SDNode *N,
1595                                             SDValue &Lo, SDValue &Hi) {
1596   // Expand the subcomponents.
1597   SDValue LHSL, LHSH, RHSL, RHSH;
1598   DebugLoc dl = N->getDebugLoc();
1599   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1600   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1601   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Glue);
1602   SDValue LoOps[3] = { LHSL, RHSL, N->getOperand(2) };
1603   SDValue HiOps[3] = { LHSH, RHSH };
1604
1605   Lo = DAG.getNode(N->getOpcode(), dl, VTList, LoOps, 3);
1606   HiOps[2] = Lo.getValue(1);
1607   Hi = DAG.getNode(N->getOpcode(), dl, VTList, HiOps, 3);
1608
1609   // Legalized the flag result - switch anything that used the old flag to
1610   // use the new one.
1611   ReplaceValueWith(SDValue(N, 1), Hi.getValue(1));
1612 }
1613
1614 void DAGTypeLegalizer::ExpandIntRes_MERGE_VALUES(SDNode *N, unsigned ResNo,
1615                                                  SDValue &Lo, SDValue &Hi) {
1616   SDValue Res = DisintegrateMERGE_VALUES(N, ResNo);
1617   SplitInteger(Res, Lo, Hi);
1618 }
1619
1620 void DAGTypeLegalizer::ExpandIntRes_ANY_EXTEND(SDNode *N,
1621                                                SDValue &Lo, SDValue &Hi) {
1622   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1623   DebugLoc dl = N->getDebugLoc();
1624   SDValue Op = N->getOperand(0);
1625   if (Op.getValueType().bitsLE(NVT)) {
1626     // The low part is any extension of the input (which degenerates to a copy).
1627     Lo = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Op);
1628     Hi = DAG.getUNDEF(NVT);   // The high part is undefined.
1629   } else {
1630     // For example, extension of an i48 to an i64.  The operand type necessarily
1631     // promotes to the result type, so will end up being expanded too.
1632     assert(getTypeAction(Op.getValueType()) ==
1633            TargetLowering::TypePromoteInteger &&
1634            "Only know how to promote this result!");
1635     SDValue Res = GetPromotedInteger(Op);
1636     assert(Res.getValueType() == N->getValueType(0) &&
1637            "Operand over promoted?");
1638     // Split the promoted operand.  This will simplify when it is expanded.
1639     SplitInteger(Res, Lo, Hi);
1640   }
1641 }
1642
1643 void DAGTypeLegalizer::ExpandIntRes_AssertSext(SDNode *N,
1644                                                SDValue &Lo, SDValue &Hi) {
1645   DebugLoc dl = N->getDebugLoc();
1646   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1647   EVT NVT = Lo.getValueType();
1648   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1649   unsigned NVTBits = NVT.getSizeInBits();
1650   unsigned EVTBits = EVT.getSizeInBits();
1651
1652   if (NVTBits < EVTBits) {
1653     Hi = DAG.getNode(ISD::AssertSext, dl, NVT, Hi,
1654                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
1655                                                         EVTBits - NVTBits)));
1656   } else {
1657     Lo = DAG.getNode(ISD::AssertSext, dl, NVT, Lo, DAG.getValueType(EVT));
1658     // The high part replicates the sign bit of Lo, make it explicit.
1659     Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
1660                      DAG.getConstant(NVTBits-1, TLI.getPointerTy()));
1661   }
1662 }
1663
1664 void DAGTypeLegalizer::ExpandIntRes_AssertZext(SDNode *N,
1665                                                SDValue &Lo, SDValue &Hi) {
1666   DebugLoc dl = N->getDebugLoc();
1667   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1668   EVT NVT = Lo.getValueType();
1669   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1670   unsigned NVTBits = NVT.getSizeInBits();
1671   unsigned EVTBits = EVT.getSizeInBits();
1672
1673   if (NVTBits < EVTBits) {
1674     Hi = DAG.getNode(ISD::AssertZext, dl, NVT, Hi,
1675                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
1676                                                         EVTBits - NVTBits)));
1677   } else {
1678     Lo = DAG.getNode(ISD::AssertZext, dl, NVT, Lo, DAG.getValueType(EVT));
1679     // The high part must be zero, make it explicit.
1680     Hi = DAG.getConstant(0, NVT);
1681   }
1682 }
1683
1684 void DAGTypeLegalizer::ExpandIntRes_BSWAP(SDNode *N,
1685                                           SDValue &Lo, SDValue &Hi) {
1686   DebugLoc dl = N->getDebugLoc();
1687   GetExpandedInteger(N->getOperand(0), Hi, Lo);  // Note swapped operands.
1688   Lo = DAG.getNode(ISD::BSWAP, dl, Lo.getValueType(), Lo);
1689   Hi = DAG.getNode(ISD::BSWAP, dl, Hi.getValueType(), Hi);
1690 }
1691
1692 void DAGTypeLegalizer::ExpandIntRes_Constant(SDNode *N,
1693                                              SDValue &Lo, SDValue &Hi) {
1694   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1695   unsigned NBitWidth = NVT.getSizeInBits();
1696   const APInt &Cst = cast<ConstantSDNode>(N)->getAPIntValue();
1697   Lo = DAG.getConstant(Cst.trunc(NBitWidth), NVT);
1698   Hi = DAG.getConstant(Cst.lshr(NBitWidth).trunc(NBitWidth), NVT);
1699 }
1700
1701 void DAGTypeLegalizer::ExpandIntRes_CTLZ(SDNode *N,
1702                                          SDValue &Lo, SDValue &Hi) {
1703   DebugLoc dl = N->getDebugLoc();
1704   // ctlz (HiLo) -> Hi != 0 ? ctlz(Hi) : (ctlz(Lo)+32)
1705   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1706   EVT NVT = Lo.getValueType();
1707
1708   SDValue HiNotZero = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), Hi,
1709                                    DAG.getConstant(0, NVT), ISD::SETNE);
1710
1711   SDValue LoLZ = DAG.getNode(N->getOpcode(), dl, NVT, Lo);
1712   SDValue HiLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, NVT, Hi);
1713
1714   Lo = DAG.getNode(ISD::SELECT, dl, NVT, HiNotZero, HiLZ,
1715                    DAG.getNode(ISD::ADD, dl, NVT, LoLZ,
1716                                DAG.getConstant(NVT.getSizeInBits(), NVT)));
1717   Hi = DAG.getConstant(0, NVT);
1718 }
1719
1720 void DAGTypeLegalizer::ExpandIntRes_CTPOP(SDNode *N,
1721                                           SDValue &Lo, SDValue &Hi) {
1722   DebugLoc dl = N->getDebugLoc();
1723   // ctpop(HiLo) -> ctpop(Hi)+ctpop(Lo)
1724   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1725   EVT NVT = Lo.getValueType();
1726   Lo = DAG.getNode(ISD::ADD, dl, NVT, DAG.getNode(ISD::CTPOP, dl, NVT, Lo),
1727                    DAG.getNode(ISD::CTPOP, dl, NVT, Hi));
1728   Hi = DAG.getConstant(0, NVT);
1729 }
1730
1731 void DAGTypeLegalizer::ExpandIntRes_CTTZ(SDNode *N,
1732                                          SDValue &Lo, SDValue &Hi) {
1733   DebugLoc dl = N->getDebugLoc();
1734   // cttz (HiLo) -> Lo != 0 ? cttz(Lo) : (cttz(Hi)+32)
1735   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1736   EVT NVT = Lo.getValueType();
1737
1738   SDValue LoNotZero = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), Lo,
1739                                    DAG.getConstant(0, NVT), ISD::SETNE);
1740
1741   SDValue LoLZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, NVT, Lo);
1742   SDValue HiLZ = DAG.getNode(N->getOpcode(), dl, NVT, Hi);
1743
1744   Lo = DAG.getNode(ISD::SELECT, dl, NVT, LoNotZero, LoLZ,
1745                    DAG.getNode(ISD::ADD, dl, NVT, HiLZ,
1746                                DAG.getConstant(NVT.getSizeInBits(), NVT)));
1747   Hi = DAG.getConstant(0, NVT);
1748 }
1749
1750 void DAGTypeLegalizer::ExpandIntRes_FP_TO_SINT(SDNode *N, SDValue &Lo,
1751                                                SDValue &Hi) {
1752   DebugLoc dl = N->getDebugLoc();
1753   EVT VT = N->getValueType(0);
1754   SDValue Op = N->getOperand(0);
1755   RTLIB::Libcall LC = RTLIB::getFPTOSINT(Op.getValueType(), VT);
1756   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-sint conversion!");
1757   SplitInteger(MakeLibCall(LC, VT, &Op, 1, true/*irrelevant*/, dl), Lo, Hi);
1758 }
1759
1760 void DAGTypeLegalizer::ExpandIntRes_FP_TO_UINT(SDNode *N, SDValue &Lo,
1761                                                SDValue &Hi) {
1762   DebugLoc dl = N->getDebugLoc();
1763   EVT VT = N->getValueType(0);
1764   SDValue Op = N->getOperand(0);
1765   RTLIB::Libcall LC = RTLIB::getFPTOUINT(Op.getValueType(), VT);
1766   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-uint conversion!");
1767   SplitInteger(MakeLibCall(LC, VT, &Op, 1, false/*irrelevant*/, dl), Lo, Hi);
1768 }
1769
1770 void DAGTypeLegalizer::ExpandIntRes_LOAD(LoadSDNode *N,
1771                                          SDValue &Lo, SDValue &Hi) {
1772   if (ISD::isNormalLoad(N)) {
1773     ExpandRes_NormalLoad(N, Lo, Hi);
1774     return;
1775   }
1776
1777   assert(ISD::isUNINDEXEDLoad(N) && "Indexed load during type legalization!");
1778
1779   EVT VT = N->getValueType(0);
1780   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
1781   SDValue Ch  = N->getChain();
1782   SDValue Ptr = N->getBasePtr();
1783   ISD::LoadExtType ExtType = N->getExtensionType();
1784   unsigned Alignment = N->getAlignment();
1785   bool isVolatile = N->isVolatile();
1786   bool isNonTemporal = N->isNonTemporal();
1787   bool isInvariant = N->isInvariant();
1788   DebugLoc dl = N->getDebugLoc();
1789
1790   assert(NVT.isByteSized() && "Expanded type not byte sized!");
1791
1792   if (N->getMemoryVT().bitsLE(NVT)) {
1793     EVT MemVT = N->getMemoryVT();
1794
1795     Lo = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr, N->getPointerInfo(),
1796                         MemVT, isVolatile, isNonTemporal, Alignment);
1797
1798     // Remember the chain.
1799     Ch = Lo.getValue(1);
1800
1801     if (ExtType == ISD::SEXTLOAD) {
1802       // The high part is obtained by SRA'ing all but one of the bits of the
1803       // lo part.
1804       unsigned LoSize = Lo.getValueType().getSizeInBits();
1805       Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
1806                        DAG.getConstant(LoSize-1, TLI.getPointerTy()));
1807     } else if (ExtType == ISD::ZEXTLOAD) {
1808       // The high part is just a zero.
1809       Hi = DAG.getConstant(0, NVT);
1810     } else {
1811       assert(ExtType == ISD::EXTLOAD && "Unknown extload!");
1812       // The high part is undefined.
1813       Hi = DAG.getUNDEF(NVT);
1814     }
1815   } else if (TLI.isLittleEndian()) {
1816     // Little-endian - low bits are at low addresses.
1817     Lo = DAG.getLoad(NVT, dl, Ch, Ptr, N->getPointerInfo(),
1818                      isVolatile, isNonTemporal, isInvariant, Alignment);
1819
1820     unsigned ExcessBits =
1821       N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
1822     EVT NEVT = EVT::getIntegerVT(*DAG.getContext(), ExcessBits);
1823
1824     // Increment the pointer to the other half.
1825     unsigned IncrementSize = NVT.getSizeInBits()/8;
1826     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
1827                       DAG.getIntPtrConstant(IncrementSize));
1828     Hi = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr,
1829                         N->getPointerInfo().getWithOffset(IncrementSize), NEVT,
1830                         isVolatile, isNonTemporal,
1831                         MinAlign(Alignment, IncrementSize));
1832
1833     // Build a factor node to remember that this load is independent of the
1834     // other one.
1835     Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1836                      Hi.getValue(1));
1837   } else {
1838     // Big-endian - high bits are at low addresses.  Favor aligned loads at
1839     // the cost of some bit-fiddling.
1840     EVT MemVT = N->getMemoryVT();
1841     unsigned EBytes = MemVT.getStoreSize();
1842     unsigned IncrementSize = NVT.getSizeInBits()/8;
1843     unsigned ExcessBits = (EBytes - IncrementSize)*8;
1844
1845     // Load both the high bits and maybe some of the low bits.
1846     Hi = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr, N->getPointerInfo(),
1847                         EVT::getIntegerVT(*DAG.getContext(),
1848                                           MemVT.getSizeInBits() - ExcessBits),
1849                         isVolatile, isNonTemporal, Alignment);
1850
1851     // Increment the pointer to the other half.
1852     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
1853                       DAG.getIntPtrConstant(IncrementSize));
1854     // Load the rest of the low bits.
1855     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, NVT, Ch, Ptr,
1856                         N->getPointerInfo().getWithOffset(IncrementSize),
1857                         EVT::getIntegerVT(*DAG.getContext(), ExcessBits),
1858                         isVolatile, isNonTemporal,
1859                         MinAlign(Alignment, IncrementSize));
1860
1861     // Build a factor node to remember that this load is independent of the
1862     // other one.
1863     Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1864                      Hi.getValue(1));
1865
1866     if (ExcessBits < NVT.getSizeInBits()) {
1867       // Transfer low bits from the bottom of Hi to the top of Lo.
1868       Lo = DAG.getNode(ISD::OR, dl, NVT, Lo,
1869                        DAG.getNode(ISD::SHL, dl, NVT, Hi,
1870                                    DAG.getConstant(ExcessBits,
1871                                                    TLI.getPointerTy())));
1872       // Move high bits to the right position in Hi.
1873       Hi = DAG.getNode(ExtType == ISD::SEXTLOAD ? ISD::SRA : ISD::SRL, dl,
1874                        NVT, Hi,
1875                        DAG.getConstant(NVT.getSizeInBits() - ExcessBits,
1876                                        TLI.getPointerTy()));
1877     }
1878   }
1879
1880   // Legalized the chain result - switch anything that used the old chain to
1881   // use the new one.
1882   ReplaceValueWith(SDValue(N, 1), Ch);
1883 }
1884
1885 void DAGTypeLegalizer::ExpandIntRes_Logical(SDNode *N,
1886                                             SDValue &Lo, SDValue &Hi) {
1887   DebugLoc dl = N->getDebugLoc();
1888   SDValue LL, LH, RL, RH;
1889   GetExpandedInteger(N->getOperand(0), LL, LH);
1890   GetExpandedInteger(N->getOperand(1), RL, RH);
1891   Lo = DAG.getNode(N->getOpcode(), dl, LL.getValueType(), LL, RL);
1892   Hi = DAG.getNode(N->getOpcode(), dl, LL.getValueType(), LH, RH);
1893 }
1894
1895 void DAGTypeLegalizer::ExpandIntRes_MUL(SDNode *N,
1896                                         SDValue &Lo, SDValue &Hi) {
1897   EVT VT = N->getValueType(0);
1898   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
1899   DebugLoc dl = N->getDebugLoc();
1900
1901   bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, NVT);
1902   bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, NVT);
1903   bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, NVT);
1904   bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, NVT);
1905   if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
1906     SDValue LL, LH, RL, RH;
1907     GetExpandedInteger(N->getOperand(0), LL, LH);
1908     GetExpandedInteger(N->getOperand(1), RL, RH);
1909     unsigned OuterBitSize = VT.getSizeInBits();
1910     unsigned InnerBitSize = NVT.getSizeInBits();
1911     unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0));
1912     unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1));
1913
1914     APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
1915     if (DAG.MaskedValueIsZero(N->getOperand(0), HighMask) &&
1916         DAG.MaskedValueIsZero(N->getOperand(1), HighMask)) {
1917       // The inputs are both zero-extended.
1918       if (HasUMUL_LOHI) {
1919         // We can emit a umul_lohi.
1920         Lo = DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(NVT, NVT), LL, RL);
1921         Hi = SDValue(Lo.getNode(), 1);
1922         return;
1923       }
1924       if (HasMULHU) {
1925         // We can emit a mulhu+mul.
1926         Lo = DAG.getNode(ISD::MUL, dl, NVT, LL, RL);
1927         Hi = DAG.getNode(ISD::MULHU, dl, NVT, LL, RL);
1928         return;
1929       }
1930     }
1931     if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
1932       // The input values are both sign-extended.
1933       if (HasSMUL_LOHI) {
1934         // We can emit a smul_lohi.
1935         Lo = DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(NVT, NVT), LL, RL);
1936         Hi = SDValue(Lo.getNode(), 1);
1937         return;
1938       }
1939       if (HasMULHS) {
1940         // We can emit a mulhs+mul.
1941         Lo = DAG.getNode(ISD::MUL, dl, NVT, LL, RL);
1942         Hi = DAG.getNode(ISD::MULHS, dl, NVT, LL, RL);
1943         return;
1944       }
1945     }
1946     if (HasUMUL_LOHI) {
1947       // Lo,Hi = umul LHS, RHS.
1948       SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI, dl,
1949                                        DAG.getVTList(NVT, NVT), LL, RL);
1950       Lo = UMulLOHI;
1951       Hi = UMulLOHI.getValue(1);
1952       RH = DAG.getNode(ISD::MUL, dl, NVT, LL, RH);
1953       LH = DAG.getNode(ISD::MUL, dl, NVT, LH, RL);
1954       Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, RH);
1955       Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, LH);
1956       return;
1957     }
1958     if (HasMULHU) {
1959       Lo = DAG.getNode(ISD::MUL, dl, NVT, LL, RL);
1960       Hi = DAG.getNode(ISD::MULHU, dl, NVT, LL, RL);
1961       RH = DAG.getNode(ISD::MUL, dl, NVT, LL, RH);
1962       LH = DAG.getNode(ISD::MUL, dl, NVT, LH, RL);
1963       Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, RH);
1964       Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, LH);
1965       return;
1966     }
1967   }
1968
1969   // If nothing else, we can make a libcall.
1970   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1971   if (VT == MVT::i16)
1972     LC = RTLIB::MUL_I16;
1973   else if (VT == MVT::i32)
1974     LC = RTLIB::MUL_I32;
1975   else if (VT == MVT::i64)
1976     LC = RTLIB::MUL_I64;
1977   else if (VT == MVT::i128)
1978     LC = RTLIB::MUL_I128;
1979   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported MUL!");
1980
1981   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1982   SplitInteger(MakeLibCall(LC, VT, Ops, 2, true/*irrelevant*/, dl), Lo, Hi);
1983 }
1984
1985 void DAGTypeLegalizer::ExpandIntRes_SADDSUBO(SDNode *Node,
1986                                              SDValue &Lo, SDValue &Hi) {
1987   SDValue LHS = Node->getOperand(0);
1988   SDValue RHS = Node->getOperand(1);
1989   DebugLoc dl = Node->getDebugLoc();
1990
1991   // Expand the result by simply replacing it with the equivalent
1992   // non-overflow-checking operation.
1993   SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
1994                             ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
1995                             LHS, RHS);
1996   SplitInteger(Sum, Lo, Hi);
1997
1998   // Compute the overflow.
1999   //
2000   //   LHSSign -> LHS >= 0
2001   //   RHSSign -> RHS >= 0
2002   //   SumSign -> Sum >= 0
2003   //
2004   //   Add:
2005   //   Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
2006   //   Sub:
2007   //   Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
2008   //
2009   EVT OType = Node->getValueType(1);
2010   SDValue Zero = DAG.getConstant(0, LHS.getValueType());
2011
2012   SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
2013   SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
2014   SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
2015                                     Node->getOpcode() == ISD::SADDO ?
2016                                     ISD::SETEQ : ISD::SETNE);
2017
2018   SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
2019   SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
2020
2021   SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
2022
2023   // Use the calculated overflow everywhere.
2024   ReplaceValueWith(SDValue(Node, 1), Cmp);
2025 }
2026
2027 void DAGTypeLegalizer::ExpandIntRes_SDIV(SDNode *N,
2028                                          SDValue &Lo, SDValue &Hi) {
2029   EVT VT = N->getValueType(0);
2030   DebugLoc dl = N->getDebugLoc();
2031
2032   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2033   if (VT == MVT::i16)
2034     LC = RTLIB::SDIV_I16;
2035   else if (VT == MVT::i32)
2036     LC = RTLIB::SDIV_I32;
2037   else if (VT == MVT::i64)
2038     LC = RTLIB::SDIV_I64;
2039   else if (VT == MVT::i128)
2040     LC = RTLIB::SDIV_I128;
2041   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
2042
2043   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2044   SplitInteger(MakeLibCall(LC, VT, Ops, 2, true, dl), Lo, Hi);
2045 }
2046
2047 void DAGTypeLegalizer::ExpandIntRes_Shift(SDNode *N,
2048                                           SDValue &Lo, SDValue &Hi) {
2049   EVT VT = N->getValueType(0);
2050   DebugLoc dl = N->getDebugLoc();
2051
2052   // If we can emit an efficient shift operation, do so now.  Check to see if
2053   // the RHS is a constant.
2054   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2055     return ExpandShiftByConstant(N, CN->getZExtValue(), Lo, Hi);
2056
2057   // If we can determine that the high bit of the shift is zero or one, even if
2058   // the low bits are variable, emit this shift in an optimized form.
2059   if (ExpandShiftWithKnownAmountBit(N, Lo, Hi))
2060     return;
2061
2062   // If this target supports shift_PARTS, use it.  First, map to the _PARTS opc.
2063   unsigned PartsOpc;
2064   if (N->getOpcode() == ISD::SHL) {
2065     PartsOpc = ISD::SHL_PARTS;
2066   } else if (N->getOpcode() == ISD::SRL) {
2067     PartsOpc = ISD::SRL_PARTS;
2068   } else {
2069     assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
2070     PartsOpc = ISD::SRA_PARTS;
2071   }
2072
2073   // Next check to see if the target supports this SHL_PARTS operation or if it
2074   // will custom expand it.
2075   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2076   TargetLowering::LegalizeAction Action = TLI.getOperationAction(PartsOpc, NVT);
2077   if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
2078       Action == TargetLowering::Custom) {
2079     // Expand the subcomponents.
2080     SDValue LHSL, LHSH;
2081     GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
2082
2083     SDValue Ops[] = { LHSL, LHSH, N->getOperand(1) };
2084     EVT VT = LHSL.getValueType();
2085     Lo = DAG.getNode(PartsOpc, dl, DAG.getVTList(VT, VT), Ops, 3);
2086     Hi = Lo.getValue(1);
2087     return;
2088   }
2089
2090   // Otherwise, emit a libcall.
2091   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2092   bool isSigned;
2093   if (N->getOpcode() == ISD::SHL) {
2094     isSigned = false; /*sign irrelevant*/
2095     if (VT == MVT::i16)
2096       LC = RTLIB::SHL_I16;
2097     else if (VT == MVT::i32)
2098       LC = RTLIB::SHL_I32;
2099     else if (VT == MVT::i64)
2100       LC = RTLIB::SHL_I64;
2101     else if (VT == MVT::i128)
2102       LC = RTLIB::SHL_I128;
2103   } else if (N->getOpcode() == ISD::SRL) {
2104     isSigned = false;
2105     if (VT == MVT::i16)
2106       LC = RTLIB::SRL_I16;
2107     else if (VT == MVT::i32)
2108       LC = RTLIB::SRL_I32;
2109     else if (VT == MVT::i64)
2110       LC = RTLIB::SRL_I64;
2111     else if (VT == MVT::i128)
2112       LC = RTLIB::SRL_I128;
2113   } else {
2114     assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
2115     isSigned = true;
2116     if (VT == MVT::i16)
2117       LC = RTLIB::SRA_I16;
2118     else if (VT == MVT::i32)
2119       LC = RTLIB::SRA_I32;
2120     else if (VT == MVT::i64)
2121       LC = RTLIB::SRA_I64;
2122     else if (VT == MVT::i128)
2123       LC = RTLIB::SRA_I128;
2124   }
2125
2126   if (LC != RTLIB::UNKNOWN_LIBCALL && TLI.getLibcallName(LC)) {
2127     SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2128     SplitInteger(MakeLibCall(LC, VT, Ops, 2, isSigned, dl), Lo, Hi);
2129     return;
2130   }
2131
2132   if (!ExpandShiftWithUnknownAmountBit(N, Lo, Hi))
2133     llvm_unreachable("Unsupported shift!");
2134 }
2135
2136 void DAGTypeLegalizer::ExpandIntRes_SIGN_EXTEND(SDNode *N,
2137                                                 SDValue &Lo, SDValue &Hi) {
2138   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2139   DebugLoc dl = N->getDebugLoc();
2140   SDValue Op = N->getOperand(0);
2141   if (Op.getValueType().bitsLE(NVT)) {
2142     // The low part is sign extension of the input (degenerates to a copy).
2143     Lo = DAG.getNode(ISD::SIGN_EXTEND, dl, NVT, N->getOperand(0));
2144     // The high part is obtained by SRA'ing all but one of the bits of low part.
2145     unsigned LoSize = NVT.getSizeInBits();
2146     Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
2147                      DAG.getConstant(LoSize-1, TLI.getPointerTy()));
2148   } else {
2149     // For example, extension of an i48 to an i64.  The operand type necessarily
2150     // promotes to the result type, so will end up being expanded too.
2151     assert(getTypeAction(Op.getValueType()) ==
2152            TargetLowering::TypePromoteInteger &&
2153            "Only know how to promote this result!");
2154     SDValue Res = GetPromotedInteger(Op);
2155     assert(Res.getValueType() == N->getValueType(0) &&
2156            "Operand over promoted?");
2157     // Split the promoted operand.  This will simplify when it is expanded.
2158     SplitInteger(Res, Lo, Hi);
2159     unsigned ExcessBits =
2160       Op.getValueType().getSizeInBits() - NVT.getSizeInBits();
2161     Hi = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Hi.getValueType(), Hi,
2162                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
2163                                                         ExcessBits)));
2164   }
2165 }
2166
2167 void DAGTypeLegalizer::
2168 ExpandIntRes_SIGN_EXTEND_INREG(SDNode *N, SDValue &Lo, SDValue &Hi) {
2169   DebugLoc dl = N->getDebugLoc();
2170   GetExpandedInteger(N->getOperand(0), Lo, Hi);
2171   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
2172
2173   if (EVT.bitsLE(Lo.getValueType())) {
2174     // sext_inreg the low part if needed.
2175     Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Lo.getValueType(), Lo,
2176                      N->getOperand(1));
2177
2178     // The high part gets the sign extension from the lo-part.  This handles
2179     // things like sextinreg V:i64 from i8.
2180     Hi = DAG.getNode(ISD::SRA, dl, Hi.getValueType(), Lo,
2181                      DAG.getConstant(Hi.getValueType().getSizeInBits()-1,
2182                                      TLI.getPointerTy()));
2183   } else {
2184     // For example, extension of an i48 to an i64.  Leave the low part alone,
2185     // sext_inreg the high part.
2186     unsigned ExcessBits =
2187       EVT.getSizeInBits() - Lo.getValueType().getSizeInBits();
2188     Hi = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Hi.getValueType(), Hi,
2189                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
2190                                                         ExcessBits)));
2191   }
2192 }
2193
2194 void DAGTypeLegalizer::ExpandIntRes_SREM(SDNode *N,
2195                                          SDValue &Lo, SDValue &Hi) {
2196   EVT VT = N->getValueType(0);
2197   DebugLoc dl = N->getDebugLoc();
2198
2199   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2200   if (VT == MVT::i16)
2201     LC = RTLIB::SREM_I16;
2202   else if (VT == MVT::i32)
2203     LC = RTLIB::SREM_I32;
2204   else if (VT == MVT::i64)
2205     LC = RTLIB::SREM_I64;
2206   else if (VT == MVT::i128)
2207     LC = RTLIB::SREM_I128;
2208   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
2209
2210   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2211   SplitInteger(MakeLibCall(LC, VT, Ops, 2, true, dl), Lo, Hi);
2212 }
2213
2214 void DAGTypeLegalizer::ExpandIntRes_TRUNCATE(SDNode *N,
2215                                              SDValue &Lo, SDValue &Hi) {
2216   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2217   DebugLoc dl = N->getDebugLoc();
2218   Lo = DAG.getNode(ISD::TRUNCATE, dl, NVT, N->getOperand(0));
2219   Hi = DAG.getNode(ISD::SRL, dl,
2220                    N->getOperand(0).getValueType(), N->getOperand(0),
2221                    DAG.getConstant(NVT.getSizeInBits(), TLI.getPointerTy()));
2222   Hi = DAG.getNode(ISD::TRUNCATE, dl, NVT, Hi);
2223 }
2224
2225 void DAGTypeLegalizer::ExpandIntRes_UADDSUBO(SDNode *N,
2226                                              SDValue &Lo, SDValue &Hi) {
2227   SDValue LHS = N->getOperand(0);
2228   SDValue RHS = N->getOperand(1);
2229   DebugLoc dl = N->getDebugLoc();
2230
2231   // Expand the result by simply replacing it with the equivalent
2232   // non-overflow-checking operation.
2233   SDValue Sum = DAG.getNode(N->getOpcode() == ISD::UADDO ?
2234                             ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
2235                             LHS, RHS);
2236   SplitInteger(Sum, Lo, Hi);
2237
2238   // Calculate the overflow: addition overflows iff a + b < a, and subtraction
2239   // overflows iff a - b > a.
2240   SDValue Ofl = DAG.getSetCC(dl, N->getValueType(1), Sum, LHS,
2241                              N->getOpcode () == ISD::UADDO ?
2242                              ISD::SETULT : ISD::SETUGT);
2243
2244   // Use the calculated overflow everywhere.
2245   ReplaceValueWith(SDValue(N, 1), Ofl);
2246 }
2247
2248 void DAGTypeLegalizer::ExpandIntRes_XMULO(SDNode *N,
2249                                           SDValue &Lo, SDValue &Hi) {
2250   EVT VT = N->getValueType(0);
2251   Type *RetTy = VT.getTypeForEVT(*DAG.getContext());
2252   EVT PtrVT = TLI.getPointerTy();
2253   Type *PtrTy = PtrVT.getTypeForEVT(*DAG.getContext());
2254   DebugLoc dl = N->getDebugLoc();
2255
2256   // A divide for UMULO should be faster than a function call.
2257   if (N->getOpcode() == ISD::UMULO) {
2258     SDValue LHS = N->getOperand(0), RHS = N->getOperand(1);
2259     DebugLoc DL = N->getDebugLoc();
2260
2261     SDValue MUL = DAG.getNode(ISD::MUL, DL, LHS.getValueType(), LHS, RHS);
2262     SplitInteger(MUL, Lo, Hi);
2263
2264     // A divide for UMULO will be faster than a function call. Select to
2265     // make sure we aren't using 0.
2266     SDValue isZero = DAG.getSetCC(dl, TLI.getSetCCResultType(VT),
2267                                   RHS, DAG.getConstant(0, VT), ISD::SETNE);
2268     SDValue NotZero = DAG.getNode(ISD::SELECT, dl, VT, isZero,
2269                                   DAG.getConstant(1, VT), RHS);
2270     SDValue DIV = DAG.getNode(ISD::UDIV, DL, LHS.getValueType(), MUL, NotZero);
2271     SDValue Overflow;
2272     Overflow = DAG.getSetCC(DL, N->getValueType(1), DIV, LHS, ISD::SETNE);
2273     ReplaceValueWith(SDValue(N, 1), Overflow);
2274     return;
2275   }
2276
2277   // Replace this with a libcall that will check overflow.
2278   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2279   if (VT == MVT::i32)
2280     LC = RTLIB::MULO_I32;
2281   else if (VT == MVT::i64)
2282     LC = RTLIB::MULO_I64;
2283   else if (VT == MVT::i128)
2284     LC = RTLIB::MULO_I128;
2285   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported XMULO!");
2286
2287   SDValue Temp = DAG.CreateStackTemporary(PtrVT);
2288   // Temporary for the overflow value, default it to zero.
2289   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl,
2290                                DAG.getConstant(0, PtrVT), Temp,
2291                                MachinePointerInfo(), false, false, 0);
2292
2293   TargetLowering::ArgListTy Args;
2294   TargetLowering::ArgListEntry Entry;
2295   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2296     EVT ArgVT = N->getOperand(i).getValueType();
2297     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2298     Entry.Node = N->getOperand(i);
2299     Entry.Ty = ArgTy;
2300     Entry.isSExt = true;
2301     Entry.isZExt = false;
2302     Args.push_back(Entry);
2303   }
2304
2305   // Also pass the address of the overflow check.
2306   Entry.Node = Temp;
2307   Entry.Ty = PtrTy->getPointerTo();
2308   Entry.isSExt = true;
2309   Entry.isZExt = false;
2310   Args.push_back(Entry);
2311
2312   SDValue Func = DAG.getExternalSymbol(TLI.getLibcallName(LC), PtrVT);
2313   std::pair<SDValue, SDValue> CallInfo =
2314     TLI.LowerCallTo(Chain, RetTy, true, false, false, false,
2315                     0, TLI.getLibcallCallingConv(LC), false,
2316                     true, Func, Args, DAG, dl);
2317
2318   SplitInteger(CallInfo.first, Lo, Hi);
2319   SDValue Temp2 = DAG.getLoad(PtrVT, dl, CallInfo.second, Temp,
2320                               MachinePointerInfo(), false, false, false, 0);
2321   SDValue Ofl = DAG.getSetCC(dl, N->getValueType(1), Temp2,
2322                              DAG.getConstant(0, PtrVT),
2323                              ISD::SETNE);
2324   // Use the overflow from the libcall everywhere.
2325   ReplaceValueWith(SDValue(N, 1), Ofl);
2326 }
2327
2328 void DAGTypeLegalizer::ExpandIntRes_UDIV(SDNode *N,
2329                                          SDValue &Lo, SDValue &Hi) {
2330   EVT VT = N->getValueType(0);
2331   DebugLoc dl = N->getDebugLoc();
2332
2333   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2334   if (VT == MVT::i16)
2335     LC = RTLIB::UDIV_I16;
2336   else if (VT == MVT::i32)
2337     LC = RTLIB::UDIV_I32;
2338   else if (VT == MVT::i64)
2339     LC = RTLIB::UDIV_I64;
2340   else if (VT == MVT::i128)
2341     LC = RTLIB::UDIV_I128;
2342   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UDIV!");
2343
2344   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2345   SplitInteger(MakeLibCall(LC, VT, Ops, 2, false, dl), Lo, Hi);
2346 }
2347
2348 void DAGTypeLegalizer::ExpandIntRes_UREM(SDNode *N,
2349                                          SDValue &Lo, SDValue &Hi) {
2350   EVT VT = N->getValueType(0);
2351   DebugLoc dl = N->getDebugLoc();
2352
2353   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2354   if (VT == MVT::i16)
2355     LC = RTLIB::UREM_I16;
2356   else if (VT == MVT::i32)
2357     LC = RTLIB::UREM_I32;
2358   else if (VT == MVT::i64)
2359     LC = RTLIB::UREM_I64;
2360   else if (VT == MVT::i128)
2361     LC = RTLIB::UREM_I128;
2362   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UREM!");
2363
2364   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2365   SplitInteger(MakeLibCall(LC, VT, Ops, 2, false, dl), Lo, Hi);
2366 }
2367
2368 void DAGTypeLegalizer::ExpandIntRes_ZERO_EXTEND(SDNode *N,
2369                                                 SDValue &Lo, SDValue &Hi) {
2370   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2371   DebugLoc dl = N->getDebugLoc();
2372   SDValue Op = N->getOperand(0);
2373   if (Op.getValueType().bitsLE(NVT)) {
2374     // The low part is zero extension of the input (degenerates to a copy).
2375     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N->getOperand(0));
2376     Hi = DAG.getConstant(0, NVT);   // The high part is just a zero.
2377   } else {
2378     // For example, extension of an i48 to an i64.  The operand type necessarily
2379     // promotes to the result type, so will end up being expanded too.
2380     assert(getTypeAction(Op.getValueType()) ==
2381            TargetLowering::TypePromoteInteger &&
2382            "Only know how to promote this result!");
2383     SDValue Res = GetPromotedInteger(Op);
2384     assert(Res.getValueType() == N->getValueType(0) &&
2385            "Operand over promoted?");
2386     // Split the promoted operand.  This will simplify when it is expanded.
2387     SplitInteger(Res, Lo, Hi);
2388     unsigned ExcessBits =
2389       Op.getValueType().getSizeInBits() - NVT.getSizeInBits();
2390     Hi = DAG.getZeroExtendInReg(Hi, dl,
2391                                 EVT::getIntegerVT(*DAG.getContext(),
2392                                                   ExcessBits));
2393   }
2394 }
2395
2396 void DAGTypeLegalizer::ExpandIntRes_ATOMIC_LOAD(SDNode *N,
2397                                                 SDValue &Lo, SDValue &Hi) {
2398   DebugLoc dl = N->getDebugLoc();
2399   EVT VT = cast<AtomicSDNode>(N)->getMemoryVT();
2400   SDValue Zero = DAG.getConstant(0, VT);
2401   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
2402                                N->getOperand(0),
2403                                N->getOperand(1), Zero, Zero,
2404                                cast<AtomicSDNode>(N)->getMemOperand(),
2405                                cast<AtomicSDNode>(N)->getOrdering(),
2406                                cast<AtomicSDNode>(N)->getSynchScope());
2407   ReplaceValueWith(SDValue(N, 0), Swap.getValue(0));
2408   ReplaceValueWith(SDValue(N, 1), Swap.getValue(1));
2409 }
2410
2411 //===----------------------------------------------------------------------===//
2412 //  Integer Operand Expansion
2413 //===----------------------------------------------------------------------===//
2414
2415 /// ExpandIntegerOperand - This method is called when the specified operand of
2416 /// the specified node is found to need expansion.  At this point, all of the
2417 /// result types of the node are known to be legal, but other operands of the
2418 /// node may need promotion or expansion as well as the specified one.
2419 bool DAGTypeLegalizer::ExpandIntegerOperand(SDNode *N, unsigned OpNo) {
2420   DEBUG(dbgs() << "Expand integer operand: "; N->dump(&DAG); dbgs() << "\n");
2421   SDValue Res = SDValue();
2422
2423   if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
2424     return false;
2425
2426   switch (N->getOpcode()) {
2427   default:
2428   #ifndef NDEBUG
2429     dbgs() << "ExpandIntegerOperand Op #" << OpNo << ": ";
2430     N->dump(&DAG); dbgs() << "\n";
2431   #endif
2432     llvm_unreachable("Do not know how to expand this operator's operand!");
2433
2434   case ISD::BITCAST:           Res = ExpandOp_BITCAST(N); break;
2435   case ISD::BR_CC:             Res = ExpandIntOp_BR_CC(N); break;
2436   case ISD::BUILD_VECTOR:      Res = ExpandOp_BUILD_VECTOR(N); break;
2437   case ISD::EXTRACT_ELEMENT:   Res = ExpandOp_EXTRACT_ELEMENT(N); break;
2438   case ISD::INSERT_VECTOR_ELT: Res = ExpandOp_INSERT_VECTOR_ELT(N); break;
2439   case ISD::SCALAR_TO_VECTOR:  Res = ExpandOp_SCALAR_TO_VECTOR(N); break;
2440   case ISD::SELECT_CC:         Res = ExpandIntOp_SELECT_CC(N); break;
2441   case ISD::SETCC:             Res = ExpandIntOp_SETCC(N); break;
2442   case ISD::SINT_TO_FP:        Res = ExpandIntOp_SINT_TO_FP(N); break;
2443   case ISD::STORE:   Res = ExpandIntOp_STORE(cast<StoreSDNode>(N), OpNo); break;
2444   case ISD::TRUNCATE:          Res = ExpandIntOp_TRUNCATE(N); break;
2445   case ISD::UINT_TO_FP:        Res = ExpandIntOp_UINT_TO_FP(N); break;
2446
2447   case ISD::SHL:
2448   case ISD::SRA:
2449   case ISD::SRL:
2450   case ISD::ROTL:
2451   case ISD::ROTR:              Res = ExpandIntOp_Shift(N); break;
2452   case ISD::RETURNADDR:
2453   case ISD::FRAMEADDR:         Res = ExpandIntOp_RETURNADDR(N); break;
2454
2455   case ISD::ATOMIC_STORE:      Res = ExpandIntOp_ATOMIC_STORE(N); break;
2456   }
2457
2458   // If the result is null, the sub-method took care of registering results etc.
2459   if (!Res.getNode()) return false;
2460
2461   // If the result is N, the sub-method updated N in place.  Tell the legalizer
2462   // core about this.
2463   if (Res.getNode() == N)
2464     return true;
2465
2466   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
2467          "Invalid operand expansion");
2468
2469   ReplaceValueWith(SDValue(N, 0), Res);
2470   return false;
2471 }
2472
2473 /// IntegerExpandSetCCOperands - Expand the operands of a comparison.  This code
2474 /// is shared among BR_CC, SELECT_CC, and SETCC handlers.
2475 void DAGTypeLegalizer::IntegerExpandSetCCOperands(SDValue &NewLHS,
2476                                                   SDValue &NewRHS,
2477                                                   ISD::CondCode &CCCode,
2478                                                   DebugLoc dl) {
2479   SDValue LHSLo, LHSHi, RHSLo, RHSHi;
2480   GetExpandedInteger(NewLHS, LHSLo, LHSHi);
2481   GetExpandedInteger(NewRHS, RHSLo, RHSHi);
2482
2483   if (CCCode == ISD::SETEQ || CCCode == ISD::SETNE) {
2484     if (RHSLo == RHSHi) {
2485       if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo)) {
2486         if (RHSCST->isAllOnesValue()) {
2487           // Equality comparison to -1.
2488           NewLHS = DAG.getNode(ISD::AND, dl,
2489                                LHSLo.getValueType(), LHSLo, LHSHi);
2490           NewRHS = RHSLo;
2491           return;
2492         }
2493       }
2494     }
2495
2496     NewLHS = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSLo, RHSLo);
2497     NewRHS = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSHi, RHSHi);
2498     NewLHS = DAG.getNode(ISD::OR, dl, NewLHS.getValueType(), NewLHS, NewRHS);
2499     NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2500     return;
2501   }
2502
2503   // If this is a comparison of the sign bit, just look at the top part.
2504   // X > -1,  x < 0
2505   if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(NewRHS))
2506     if ((CCCode == ISD::SETLT && CST->isNullValue()) ||     // X < 0
2507         (CCCode == ISD::SETGT && CST->isAllOnesValue())) {  // X > -1
2508       NewLHS = LHSHi;
2509       NewRHS = RHSHi;
2510       return;
2511     }
2512
2513   // FIXME: This generated code sucks.
2514   ISD::CondCode LowCC;
2515   switch (CCCode) {
2516   default: llvm_unreachable("Unknown integer setcc!");
2517   case ISD::SETLT:
2518   case ISD::SETULT: LowCC = ISD::SETULT; break;
2519   case ISD::SETGT:
2520   case ISD::SETUGT: LowCC = ISD::SETUGT; break;
2521   case ISD::SETLE:
2522   case ISD::SETULE: LowCC = ISD::SETULE; break;
2523   case ISD::SETGE:
2524   case ISD::SETUGE: LowCC = ISD::SETUGE; break;
2525   }
2526
2527   // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
2528   // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
2529   // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
2530
2531   // NOTE: on targets without efficient SELECT of bools, we can always use
2532   // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
2533   TargetLowering::DAGCombinerInfo DagCombineInfo(DAG, false, true, true, NULL);
2534   SDValue Tmp1, Tmp2;
2535   Tmp1 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSLo.getValueType()),
2536                            LHSLo, RHSLo, LowCC, false, DagCombineInfo, dl);
2537   if (!Tmp1.getNode())
2538     Tmp1 = DAG.getSetCC(dl, TLI.getSetCCResultType(LHSLo.getValueType()),
2539                         LHSLo, RHSLo, LowCC);
2540   Tmp2 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi.getValueType()),
2541                            LHSHi, RHSHi, CCCode, false, DagCombineInfo, dl);
2542   if (!Tmp2.getNode())
2543     Tmp2 = DAG.getNode(ISD::SETCC, dl,
2544                        TLI.getSetCCResultType(LHSHi.getValueType()),
2545                        LHSHi, RHSHi, DAG.getCondCode(CCCode));
2546
2547   ConstantSDNode *Tmp1C = dyn_cast<ConstantSDNode>(Tmp1.getNode());
2548   ConstantSDNode *Tmp2C = dyn_cast<ConstantSDNode>(Tmp2.getNode());
2549   if ((Tmp1C && Tmp1C->isNullValue()) ||
2550       (Tmp2C && Tmp2C->isNullValue() &&
2551        (CCCode == ISD::SETLE || CCCode == ISD::SETGE ||
2552         CCCode == ISD::SETUGE || CCCode == ISD::SETULE)) ||
2553       (Tmp2C && Tmp2C->getAPIntValue() == 1 &&
2554        (CCCode == ISD::SETLT || CCCode == ISD::SETGT ||
2555         CCCode == ISD::SETUGT || CCCode == ISD::SETULT))) {
2556     // low part is known false, returns high part.
2557     // For LE / GE, if high part is known false, ignore the low part.
2558     // For LT / GT, if high part is known true, ignore the low part.
2559     NewLHS = Tmp2;
2560     NewRHS = SDValue();
2561     return;
2562   }
2563
2564   NewLHS = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi.getValueType()),
2565                              LHSHi, RHSHi, ISD::SETEQ, false,
2566                              DagCombineInfo, dl);
2567   if (!NewLHS.getNode())
2568     NewLHS = DAG.getSetCC(dl, TLI.getSetCCResultType(LHSHi.getValueType()),
2569                           LHSHi, RHSHi, ISD::SETEQ);
2570   NewLHS = DAG.getNode(ISD::SELECT, dl, Tmp1.getValueType(),
2571                        NewLHS, Tmp1, Tmp2);
2572   NewRHS = SDValue();
2573 }
2574
2575 SDValue DAGTypeLegalizer::ExpandIntOp_BR_CC(SDNode *N) {
2576   SDValue NewLHS = N->getOperand(2), NewRHS = N->getOperand(3);
2577   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(1))->get();
2578   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, N->getDebugLoc());
2579
2580   // If ExpandSetCCOperands returned a scalar, we need to compare the result
2581   // against zero to select between true and false values.
2582   if (NewRHS.getNode() == 0) {
2583     NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2584     CCCode = ISD::SETNE;
2585   }
2586
2587   // Update N to have the operands specified.
2588   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
2589                                 DAG.getCondCode(CCCode), NewLHS, NewRHS,
2590                                 N->getOperand(4)), 0);
2591 }
2592
2593 SDValue DAGTypeLegalizer::ExpandIntOp_SELECT_CC(SDNode *N) {
2594   SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
2595   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(4))->get();
2596   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, N->getDebugLoc());
2597
2598   // If ExpandSetCCOperands returned a scalar, we need to compare the result
2599   // against zero to select between true and false values.
2600   if (NewRHS.getNode() == 0) {
2601     NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2602     CCCode = ISD::SETNE;
2603   }
2604
2605   // Update N to have the operands specified.
2606   return SDValue(DAG.UpdateNodeOperands(N, NewLHS, NewRHS,
2607                                 N->getOperand(2), N->getOperand(3),
2608                                 DAG.getCondCode(CCCode)), 0);
2609 }
2610
2611 SDValue DAGTypeLegalizer::ExpandIntOp_SETCC(SDNode *N) {
2612   SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
2613   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(2))->get();
2614   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, N->getDebugLoc());
2615
2616   // If ExpandSetCCOperands returned a scalar, use it.
2617   if (NewRHS.getNode() == 0) {
2618     assert(NewLHS.getValueType() == N->getValueType(0) &&
2619            "Unexpected setcc expansion!");
2620     return NewLHS;
2621   }
2622
2623   // Otherwise, update N to have the operands specified.
2624   return SDValue(DAG.UpdateNodeOperands(N, NewLHS, NewRHS,
2625                                 DAG.getCondCode(CCCode)), 0);
2626 }
2627
2628 SDValue DAGTypeLegalizer::ExpandIntOp_Shift(SDNode *N) {
2629   // The value being shifted is legal, but the shift amount is too big.
2630   // It follows that either the result of the shift is undefined, or the
2631   // upper half of the shift amount is zero.  Just use the lower half.
2632   SDValue Lo, Hi;
2633   GetExpandedInteger(N->getOperand(1), Lo, Hi);
2634   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0), Lo), 0);
2635 }
2636
2637 SDValue DAGTypeLegalizer::ExpandIntOp_RETURNADDR(SDNode *N) {
2638   // The argument of RETURNADDR / FRAMEADDR builtin is 32 bit contant.  This
2639   // surely makes pretty nice problems on 8/16 bit targets. Just truncate this
2640   // constant to valid type.
2641   SDValue Lo, Hi;
2642   GetExpandedInteger(N->getOperand(0), Lo, Hi);
2643   return SDValue(DAG.UpdateNodeOperands(N, Lo), 0);
2644 }
2645
2646 SDValue DAGTypeLegalizer::ExpandIntOp_SINT_TO_FP(SDNode *N) {
2647   SDValue Op = N->getOperand(0);
2648   EVT DstVT = N->getValueType(0);
2649   RTLIB::Libcall LC = RTLIB::getSINTTOFP(Op.getValueType(), DstVT);
2650   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
2651          "Don't know how to expand this SINT_TO_FP!");
2652   return MakeLibCall(LC, DstVT, &Op, 1, true, N->getDebugLoc());
2653 }
2654
2655 SDValue DAGTypeLegalizer::ExpandIntOp_STORE(StoreSDNode *N, unsigned OpNo) {
2656   if (ISD::isNormalStore(N))
2657     return ExpandOp_NormalStore(N, OpNo);
2658
2659   assert(ISD::isUNINDEXEDStore(N) && "Indexed store during type legalization!");
2660   assert(OpNo == 1 && "Can only expand the stored value so far");
2661
2662   EVT VT = N->getOperand(1).getValueType();
2663   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2664   SDValue Ch  = N->getChain();
2665   SDValue Ptr = N->getBasePtr();
2666   unsigned Alignment = N->getAlignment();
2667   bool isVolatile = N->isVolatile();
2668   bool isNonTemporal = N->isNonTemporal();
2669   DebugLoc dl = N->getDebugLoc();
2670   SDValue Lo, Hi;
2671
2672   assert(NVT.isByteSized() && "Expanded type not byte sized!");
2673
2674   if (N->getMemoryVT().bitsLE(NVT)) {
2675     GetExpandedInteger(N->getValue(), Lo, Hi);
2676     return DAG.getTruncStore(Ch, dl, Lo, Ptr, N->getPointerInfo(),
2677                              N->getMemoryVT(), isVolatile, isNonTemporal,
2678                              Alignment);
2679   }
2680
2681   if (TLI.isLittleEndian()) {
2682     // Little-endian - low bits are at low addresses.
2683     GetExpandedInteger(N->getValue(), Lo, Hi);
2684
2685     Lo = DAG.getStore(Ch, dl, Lo, Ptr, N->getPointerInfo(),
2686                       isVolatile, isNonTemporal, Alignment);
2687
2688     unsigned ExcessBits =
2689       N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
2690     EVT NEVT = EVT::getIntegerVT(*DAG.getContext(), ExcessBits);
2691
2692     // Increment the pointer to the other half.
2693     unsigned IncrementSize = NVT.getSizeInBits()/8;
2694     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
2695                       DAG.getIntPtrConstant(IncrementSize));
2696     Hi = DAG.getTruncStore(Ch, dl, Hi, Ptr,
2697                            N->getPointerInfo().getWithOffset(IncrementSize),
2698                            NEVT, isVolatile, isNonTemporal,
2699                            MinAlign(Alignment, IncrementSize));
2700     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
2701   }
2702
2703   // Big-endian - high bits are at low addresses.  Favor aligned stores at
2704   // the cost of some bit-fiddling.
2705   GetExpandedInteger(N->getValue(), Lo, Hi);
2706
2707   EVT ExtVT = N->getMemoryVT();
2708   unsigned EBytes = ExtVT.getStoreSize();
2709   unsigned IncrementSize = NVT.getSizeInBits()/8;
2710   unsigned ExcessBits = (EBytes - IncrementSize)*8;
2711   EVT HiVT = EVT::getIntegerVT(*DAG.getContext(),
2712                                ExtVT.getSizeInBits() - ExcessBits);
2713
2714   if (ExcessBits < NVT.getSizeInBits()) {
2715     // Transfer high bits from the top of Lo to the bottom of Hi.
2716     Hi = DAG.getNode(ISD::SHL, dl, NVT, Hi,
2717                      DAG.getConstant(NVT.getSizeInBits() - ExcessBits,
2718                                      TLI.getPointerTy()));
2719     Hi = DAG.getNode(ISD::OR, dl, NVT, Hi,
2720                      DAG.getNode(ISD::SRL, dl, NVT, Lo,
2721                                  DAG.getConstant(ExcessBits,
2722                                                  TLI.getPointerTy())));
2723   }
2724
2725   // Store both the high bits and maybe some of the low bits.
2726   Hi = DAG.getTruncStore(Ch, dl, Hi, Ptr, N->getPointerInfo(),
2727                          HiVT, isVolatile, isNonTemporal, Alignment);
2728
2729   // Increment the pointer to the other half.
2730   Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
2731                     DAG.getIntPtrConstant(IncrementSize));
2732   // Store the lowest ExcessBits bits in the second half.
2733   Lo = DAG.getTruncStore(Ch, dl, Lo, Ptr,
2734                          N->getPointerInfo().getWithOffset(IncrementSize),
2735                          EVT::getIntegerVT(*DAG.getContext(), ExcessBits),
2736                          isVolatile, isNonTemporal,
2737                          MinAlign(Alignment, IncrementSize));
2738   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
2739 }
2740
2741 SDValue DAGTypeLegalizer::ExpandIntOp_TRUNCATE(SDNode *N) {
2742   SDValue InL, InH;
2743   GetExpandedInteger(N->getOperand(0), InL, InH);
2744   // Just truncate the low part of the source.
2745   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), N->getValueType(0), InL);
2746 }
2747
2748 static const fltSemantics *EVTToAPFloatSemantics(EVT VT) {
2749   switch (VT.getSimpleVT().SimpleTy) {
2750   default: llvm_unreachable("Unknown FP format");
2751   case MVT::f32:     return &APFloat::IEEEsingle;
2752   case MVT::f64:     return &APFloat::IEEEdouble;
2753   case MVT::f80:     return &APFloat::x87DoubleExtended;
2754   case MVT::f128:    return &APFloat::IEEEquad;
2755   case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
2756   }
2757 }
2758
2759 SDValue DAGTypeLegalizer::ExpandIntOp_UINT_TO_FP(SDNode *N) {
2760   SDValue Op = N->getOperand(0);
2761   EVT SrcVT = Op.getValueType();
2762   EVT DstVT = N->getValueType(0);
2763   DebugLoc dl = N->getDebugLoc();
2764
2765   // The following optimization is valid only if every value in SrcVT (when
2766   // treated as signed) is representable in DstVT.  Check that the mantissa
2767   // size of DstVT is >= than the number of bits in SrcVT -1.
2768   const fltSemantics *sem = EVTToAPFloatSemantics(DstVT);
2769   if (APFloat::semanticsPrecision(*sem) >= SrcVT.getSizeInBits()-1 &&
2770       TLI.getOperationAction(ISD::SINT_TO_FP, SrcVT) == TargetLowering::Custom){
2771     // Do a signed conversion then adjust the result.
2772     SDValue SignedConv = DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Op);
2773     SignedConv = TLI.LowerOperation(SignedConv, DAG);
2774
2775     // The result of the signed conversion needs adjusting if the 'sign bit' of
2776     // the incoming integer was set.  To handle this, we dynamically test to see
2777     // if it is set, and, if so, add a fudge factor.
2778
2779     const uint64_t F32TwoE32  = 0x4F800000ULL;
2780     const uint64_t F32TwoE64  = 0x5F800000ULL;
2781     const uint64_t F32TwoE128 = 0x7F800000ULL;
2782
2783     APInt FF(32, 0);
2784     if (SrcVT == MVT::i32)
2785       FF = APInt(32, F32TwoE32);
2786     else if (SrcVT == MVT::i64)
2787       FF = APInt(32, F32TwoE64);
2788     else if (SrcVT == MVT::i128)
2789       FF = APInt(32, F32TwoE128);
2790     else
2791       assert(false && "Unsupported UINT_TO_FP!");
2792
2793     // Check whether the sign bit is set.
2794     SDValue Lo, Hi;
2795     GetExpandedInteger(Op, Lo, Hi);
2796     SDValue SignSet = DAG.getSetCC(dl,
2797                                    TLI.getSetCCResultType(Hi.getValueType()),
2798                                    Hi, DAG.getConstant(0, Hi.getValueType()),
2799                                    ISD::SETLT);
2800
2801     // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
2802     SDValue FudgePtr = DAG.getConstantPool(
2803                                ConstantInt::get(*DAG.getContext(), FF.zext(64)),
2804                                            TLI.getPointerTy());
2805
2806     // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
2807     SDValue Zero = DAG.getIntPtrConstant(0);
2808     SDValue Four = DAG.getIntPtrConstant(4);
2809     if (TLI.isBigEndian()) std::swap(Zero, Four);
2810     SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
2811                                  Zero, Four);
2812     unsigned Alignment = cast<ConstantPoolSDNode>(FudgePtr)->getAlignment();
2813     FudgePtr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), FudgePtr, Offset);
2814     Alignment = std::min(Alignment, 4u);
2815
2816     // Load the value out, extending it from f32 to the destination float type.
2817     // FIXME: Avoid the extend by constructing the right constant pool?
2818     SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, DstVT, DAG.getEntryNode(),
2819                                    FudgePtr,
2820                                    MachinePointerInfo::getConstantPool(),
2821                                    MVT::f32,
2822                                    false, false, Alignment);
2823     return DAG.getNode(ISD::FADD, dl, DstVT, SignedConv, Fudge);
2824   }
2825
2826   // Otherwise, use a libcall.
2827   RTLIB::Libcall LC = RTLIB::getUINTTOFP(SrcVT, DstVT);
2828   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
2829          "Don't know how to expand this UINT_TO_FP!");
2830   return MakeLibCall(LC, DstVT, &Op, 1, true, dl);
2831 }
2832
2833 SDValue DAGTypeLegalizer::ExpandIntOp_ATOMIC_STORE(SDNode *N) {
2834   DebugLoc dl = N->getDebugLoc();
2835   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
2836                                cast<AtomicSDNode>(N)->getMemoryVT(),
2837                                N->getOperand(0),
2838                                N->getOperand(1), N->getOperand(2),
2839                                cast<AtomicSDNode>(N)->getMemOperand(),
2840                                cast<AtomicSDNode>(N)->getOrdering(),
2841                                cast<AtomicSDNode>(N)->getSynchScope());
2842   return Swap.getValue(1);
2843 }
2844
2845
2846 SDValue DAGTypeLegalizer::PromoteIntRes_EXTRACT_SUBVECTOR(SDNode *N) {
2847   SDValue InOp0 = N->getOperand(0);
2848   EVT InVT = InOp0.getValueType();
2849
2850   EVT OutVT = N->getValueType(0);
2851   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2852   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2853   unsigned OutNumElems = OutVT.getVectorNumElements();
2854   EVT NOutVTElem = NOutVT.getVectorElementType();
2855
2856   DebugLoc dl = N->getDebugLoc();
2857   SDValue BaseIdx = N->getOperand(1);
2858
2859   SmallVector<SDValue, 8> Ops;
2860   Ops.reserve(OutNumElems);
2861   for (unsigned i = 0; i != OutNumElems; ++i) {
2862
2863     // Extract the element from the original vector.
2864     SDValue Index = DAG.getNode(ISD::ADD, dl, BaseIdx.getValueType(),
2865       BaseIdx, DAG.getIntPtrConstant(i));
2866     SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
2867       InVT.getVectorElementType(), N->getOperand(0), Index);
2868
2869     SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, Ext);
2870     // Insert the converted element to the new vector.
2871     Ops.push_back(Op);
2872   }
2873
2874   return DAG.getNode(ISD::BUILD_VECTOR, dl, NOutVT, &Ops[0], Ops.size());
2875 }
2876
2877
2878 SDValue DAGTypeLegalizer::PromoteIntRes_VECTOR_SHUFFLE(SDNode *N) {
2879   ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
2880   EVT VT = N->getValueType(0);
2881   DebugLoc dl = N->getDebugLoc();
2882
2883   unsigned NumElts = VT.getVectorNumElements();
2884   SmallVector<int, 8> NewMask;
2885   for (unsigned i = 0; i != NumElts; ++i) {
2886     NewMask.push_back(SV->getMaskElt(i));
2887   }
2888
2889   SDValue V0 = GetPromotedInteger(N->getOperand(0));
2890   SDValue V1 = GetPromotedInteger(N->getOperand(1));
2891   EVT OutVT = V0.getValueType();
2892
2893   return DAG.getVectorShuffle(OutVT, dl, V0, V1, &NewMask[0]);
2894 }
2895
2896
2897 SDValue DAGTypeLegalizer::PromoteIntRes_BUILD_VECTOR(SDNode *N) {
2898   EVT OutVT = N->getValueType(0);
2899   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2900   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2901   unsigned NumElems = N->getNumOperands();
2902   EVT NOutVTElem = NOutVT.getVectorElementType();
2903
2904   DebugLoc dl = N->getDebugLoc();
2905
2906   SmallVector<SDValue, 8> Ops;
2907   Ops.reserve(NumElems);
2908   for (unsigned i = 0; i != NumElems; ++i) {
2909     SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, N->getOperand(i));
2910     Ops.push_back(Op);
2911   }
2912
2913   return DAG.getNode(ISD::BUILD_VECTOR, dl, NOutVT, &Ops[0], Ops.size());
2914 }
2915
2916 SDValue DAGTypeLegalizer::PromoteIntRes_SCALAR_TO_VECTOR(SDNode *N) {
2917
2918   DebugLoc dl = N->getDebugLoc();
2919
2920   assert(!N->getOperand(0).getValueType().isVector() &&
2921          "Input must be a scalar");
2922
2923   EVT OutVT = N->getValueType(0);
2924   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2925   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2926   EVT NOutVTElem = NOutVT.getVectorElementType();
2927
2928   SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, N->getOperand(0));
2929
2930   return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NOutVT, Op);
2931 }
2932
2933 SDValue DAGTypeLegalizer::PromoteIntRes_CONCAT_VECTORS(SDNode *N) {
2934   DebugLoc dl = N->getDebugLoc();
2935
2936   EVT OutVT = N->getValueType(0);
2937   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2938   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2939
2940   EVT InElemTy = OutVT.getVectorElementType();
2941   EVT OutElemTy = NOutVT.getVectorElementType();
2942
2943   unsigned NumElem = N->getOperand(0).getValueType().getVectorNumElements();
2944   unsigned NumOutElem = NOutVT.getVectorNumElements();
2945   unsigned NumOperands = N->getNumOperands();
2946   assert(NumElem * NumOperands == NumOutElem &&
2947          "Unexpected number of elements");
2948
2949   // Take the elements from the first vector.
2950   SmallVector<SDValue, 8> Ops(NumOutElem);
2951   for (unsigned i = 0; i < NumOperands; ++i) {
2952     SDValue Op = N->getOperand(i);
2953     for (unsigned j = 0; j < NumElem; ++j) {
2954       SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
2955                                 InElemTy, Op, DAG.getIntPtrConstant(j));
2956       Ops[i * NumElem + j] = DAG.getNode(ISD::ANY_EXTEND, dl, OutElemTy, Ext);
2957     }
2958   }
2959
2960   return DAG.getNode(ISD::BUILD_VECTOR, dl, NOutVT, &Ops[0], Ops.size());
2961 }
2962
2963 SDValue DAGTypeLegalizer::PromoteIntRes_INSERT_VECTOR_ELT(SDNode *N) {
2964   EVT OutVT = N->getValueType(0);
2965   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2966   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2967
2968   EVT NOutVTElem = NOutVT.getVectorElementType();
2969
2970   DebugLoc dl = N->getDebugLoc();
2971   SDValue V0 = GetPromotedInteger(N->getOperand(0));
2972
2973   SDValue ConvElem = DAG.getNode(ISD::ANY_EXTEND, dl,
2974     NOutVTElem, N->getOperand(1));
2975   return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, NOutVT,
2976     V0, ConvElem, N->getOperand(2));
2977 }
2978
2979 SDValue DAGTypeLegalizer::PromoteIntOp_EXTRACT_VECTOR_ELT(SDNode *N) {
2980   DebugLoc dl = N->getDebugLoc();
2981   SDValue V0 = GetPromotedInteger(N->getOperand(0));
2982   SDValue V1 = N->getOperand(1);
2983   SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
2984     V0->getValueType(0).getScalarType(), V0, V1);
2985
2986   // EXTRACT_VECTOR_ELT can return types which are wider than the incoming
2987   // element types. If this is the case then we need to expand the outgoing
2988   // value and not truncate it.
2989   return DAG.getAnyExtOrTrunc(Ext, dl, N->getValueType(0));
2990 }
2991
2992 SDValue DAGTypeLegalizer::PromoteIntOp_CONCAT_VECTORS(SDNode *N) {
2993   DebugLoc dl = N->getDebugLoc();
2994   unsigned NumElems = N->getNumOperands();
2995
2996   EVT RetSclrTy = N->getValueType(0).getVectorElementType();
2997
2998   SmallVector<SDValue, 8> NewOps;
2999   NewOps.reserve(NumElems);
3000
3001   // For each incoming vector
3002   for (unsigned VecIdx = 0; VecIdx != NumElems; ++VecIdx) {
3003     SDValue Incoming = GetPromotedInteger(N->getOperand(VecIdx));
3004     EVT SclrTy = Incoming->getValueType(0).getVectorElementType();
3005     unsigned NumElem = Incoming->getValueType(0).getVectorNumElements();
3006
3007     for (unsigned i=0; i<NumElem; ++i) {
3008       // Extract element from incoming vector
3009       SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SclrTy,
3010       Incoming, DAG.getIntPtrConstant(i));
3011       SDValue Tr = DAG.getNode(ISD::TRUNCATE, dl, RetSclrTy, Ex);
3012       NewOps.push_back(Tr);
3013     }
3014   }
3015
3016   return DAG.getNode(ISD::BUILD_VECTOR, dl,  N->getValueType(0),
3017     &NewOps[0], NewOps.size());
3018   }