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