Convert more SelectionDAG functions to use ArrayRef.
[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 #define DEBUG_TYPE "legalize-types"
28
29 //===----------------------------------------------------------------------===//
30 //  Integer Result Promotion
31 //===----------------------------------------------------------------------===//
32
33 /// PromoteIntegerResult - This method is called when a result of a node is
34 /// found to be in need of promotion to a larger type.  At this point, the node
35 /// may also have invalid operands or may have other results that need
36 /// expansion, we just know that (at least) one result needs promotion.
37 void DAGTypeLegalizer::PromoteIntegerResult(SDNode *N, unsigned ResNo) {
38   DEBUG(dbgs() << "Promote integer result: "; N->dump(&DAG); dbgs() << "\n");
39   SDValue Res = SDValue();
40
41   // See if the target wants to custom expand this node.
42   if (CustomLowerNode(N, N->getValueType(ResNo), true))
43     return;
44
45   switch (N->getOpcode()) {
46   default:
47 #ifndef NDEBUG
48     dbgs() << "PromoteIntegerResult #" << ResNo << ": ";
49     N->dump(&DAG); dbgs() << "\n";
50 #endif
51     llvm_unreachable("Do not know how to promote this operator!");
52   case ISD::MERGE_VALUES:Res = PromoteIntRes_MERGE_VALUES(N, ResNo); break;
53   case ISD::AssertSext:  Res = PromoteIntRes_AssertSext(N); break;
54   case ISD::AssertZext:  Res = PromoteIntRes_AssertZext(N); break;
55   case ISD::BITCAST:     Res = PromoteIntRes_BITCAST(N); break;
56   case ISD::BSWAP:       Res = PromoteIntRes_BSWAP(N); break;
57   case ISD::BUILD_PAIR:  Res = PromoteIntRes_BUILD_PAIR(N); break;
58   case ISD::Constant:    Res = PromoteIntRes_Constant(N); break;
59   case ISD::CONVERT_RNDSAT:
60                          Res = PromoteIntRes_CONVERT_RNDSAT(N); break;
61   case ISD::CTLZ_ZERO_UNDEF:
62   case ISD::CTLZ:        Res = PromoteIntRes_CTLZ(N); break;
63   case ISD::CTPOP:       Res = PromoteIntRes_CTPOP(N); break;
64   case ISD::CTTZ_ZERO_UNDEF:
65   case ISD::CTTZ:        Res = PromoteIntRes_CTTZ(N); break;
66   case ISD::EXTRACT_VECTOR_ELT:
67                          Res = PromoteIntRes_EXTRACT_VECTOR_ELT(N); break;
68   case ISD::LOAD:        Res = PromoteIntRes_LOAD(cast<LoadSDNode>(N));break;
69   case ISD::SELECT:      Res = PromoteIntRes_SELECT(N); break;
70   case ISD::VSELECT:     Res = PromoteIntRes_VSELECT(N); break;
71   case ISD::SELECT_CC:   Res = PromoteIntRes_SELECT_CC(N); break;
72   case ISD::SETCC:       Res = PromoteIntRes_SETCC(N); break;
73   case ISD::SHL:         Res = PromoteIntRes_SHL(N); break;
74   case ISD::SIGN_EXTEND_INREG:
75                          Res = PromoteIntRes_SIGN_EXTEND_INREG(N); break;
76   case ISD::SRA:         Res = PromoteIntRes_SRA(N); break;
77   case ISD::SRL:         Res = PromoteIntRes_SRL(N); break;
78   case ISD::TRUNCATE:    Res = PromoteIntRes_TRUNCATE(N); break;
79   case ISD::UNDEF:       Res = PromoteIntRes_UNDEF(N); break;
80   case ISD::VAARG:       Res = PromoteIntRes_VAARG(N); break;
81
82   case ISD::EXTRACT_SUBVECTOR:
83                          Res = PromoteIntRes_EXTRACT_SUBVECTOR(N); break;
84   case ISD::VECTOR_SHUFFLE:
85                          Res = PromoteIntRes_VECTOR_SHUFFLE(N); break;
86   case ISD::INSERT_VECTOR_ELT:
87                          Res = PromoteIntRes_INSERT_VECTOR_ELT(N); break;
88   case ISD::BUILD_VECTOR:
89                          Res = PromoteIntRes_BUILD_VECTOR(N); break;
90   case ISD::SCALAR_TO_VECTOR:
91                          Res = PromoteIntRes_SCALAR_TO_VECTOR(N); break;
92   case ISD::CONCAT_VECTORS:
93                          Res = PromoteIntRes_CONCAT_VECTORS(N); break;
94
95   case ISD::SIGN_EXTEND:
96   case ISD::ZERO_EXTEND:
97   case ISD::ANY_EXTEND:  Res = PromoteIntRes_INT_EXTEND(N); break;
98
99   case ISD::FP_TO_SINT:
100   case ISD::FP_TO_UINT:  Res = PromoteIntRes_FP_TO_XINT(N); break;
101
102   case ISD::FP32_TO_FP16:Res = PromoteIntRes_FP32_TO_FP16(N); break;
103
104   case ISD::AND:
105   case ISD::OR:
106   case ISD::XOR:
107   case ISD::ADD:
108   case ISD::SUB:
109   case ISD::MUL:         Res = PromoteIntRes_SimpleIntBinOp(N); break;
110
111   case ISD::SDIV:
112   case ISD::SREM:        Res = PromoteIntRes_SDIV(N); break;
113
114   case ISD::UDIV:
115   case ISD::UREM:        Res = PromoteIntRes_UDIV(N); break;
116
117   case ISD::SADDO:
118   case ISD::SSUBO:       Res = PromoteIntRes_SADDSUBO(N, ResNo); break;
119   case ISD::UADDO:
120   case ISD::USUBO:       Res = PromoteIntRes_UADDSUBO(N, ResNo); break;
121   case ISD::SMULO:
122   case ISD::UMULO:       Res = PromoteIntRes_XMULO(N, ResNo); break;
123
124   case ISD::ATOMIC_LOAD:
125     Res = PromoteIntRes_Atomic0(cast<AtomicSDNode>(N)); break;
126
127   case ISD::ATOMIC_LOAD_ADD:
128   case ISD::ATOMIC_LOAD_SUB:
129   case ISD::ATOMIC_LOAD_AND:
130   case ISD::ATOMIC_LOAD_OR:
131   case ISD::ATOMIC_LOAD_XOR:
132   case ISD::ATOMIC_LOAD_NAND:
133   case ISD::ATOMIC_LOAD_MIN:
134   case ISD::ATOMIC_LOAD_MAX:
135   case ISD::ATOMIC_LOAD_UMIN:
136   case ISD::ATOMIC_LOAD_UMAX:
137   case ISD::ATOMIC_SWAP:
138     Res = PromoteIntRes_Atomic1(cast<AtomicSDNode>(N)); break;
139
140   case ISD::ATOMIC_CMP_SWAP:
141     Res = PromoteIntRes_Atomic2(cast<AtomicSDNode>(N)); break;
142   }
143
144   // If the result is null then the sub-method took care of registering it.
145   if (Res.getNode())
146     SetPromotedInteger(SDValue(N, ResNo), Res);
147 }
148
149 SDValue DAGTypeLegalizer::PromoteIntRes_MERGE_VALUES(SDNode *N,
150                                                      unsigned ResNo) {
151   SDValue Op = DisintegrateMERGE_VALUES(N, ResNo);
152   return GetPromotedInteger(Op);
153 }
154
155 SDValue DAGTypeLegalizer::PromoteIntRes_AssertSext(SDNode *N) {
156   // Sign-extend the new bits, and continue the assertion.
157   SDValue Op = SExtPromotedInteger(N->getOperand(0));
158   return DAG.getNode(ISD::AssertSext, SDLoc(N),
159                      Op.getValueType(), Op, N->getOperand(1));
160 }
161
162 SDValue DAGTypeLegalizer::PromoteIntRes_AssertZext(SDNode *N) {
163   // Zero the new bits, and continue the assertion.
164   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
165   return DAG.getNode(ISD::AssertZext, SDLoc(N),
166                      Op.getValueType(), Op, N->getOperand(1));
167 }
168
169 SDValue DAGTypeLegalizer::PromoteIntRes_Atomic0(AtomicSDNode *N) {
170   EVT ResVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
171   SDValue Res = DAG.getAtomic(N->getOpcode(), SDLoc(N),
172                               N->getMemoryVT(), ResVT,
173                               N->getChain(), N->getBasePtr(),
174                               N->getMemOperand(), N->getOrdering(),
175                               N->getSynchScope());
176   // Legalized the chain result - switch anything that used the old chain to
177   // use the new one.
178   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
179   return Res;
180 }
181
182 SDValue DAGTypeLegalizer::PromoteIntRes_Atomic1(AtomicSDNode *N) {
183   SDValue Op2 = GetPromotedInteger(N->getOperand(2));
184   SDValue Res = DAG.getAtomic(N->getOpcode(), SDLoc(N),
185                               N->getMemoryVT(),
186                               N->getChain(), N->getBasePtr(),
187                               Op2, N->getMemOperand(), N->getOrdering(),
188                               N->getSynchScope());
189   // Legalized the chain result - switch anything that used the old chain to
190   // use the new one.
191   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
192   return Res;
193 }
194
195 SDValue DAGTypeLegalizer::PromoteIntRes_Atomic2(AtomicSDNode *N) {
196   SDValue Op2 = GetPromotedInteger(N->getOperand(2));
197   SDValue Op3 = GetPromotedInteger(N->getOperand(3));
198   SDValue Res = DAG.getAtomic(N->getOpcode(), SDLoc(N), N->getMemoryVT(),
199                               N->getChain(), N->getBasePtr(), Op2, Op3,
200                               N->getMemOperand(), N->getSuccessOrdering(),
201                               N->getFailureOrdering(), N->getSynchScope());
202   // Legalized the chain result - switch anything that used the old chain to
203   // use the new one.
204   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
205   return Res;
206 }
207
208 SDValue DAGTypeLegalizer::PromoteIntRes_BITCAST(SDNode *N) {
209   SDValue InOp = N->getOperand(0);
210   EVT InVT = InOp.getValueType();
211   EVT NInVT = TLI.getTypeToTransformTo(*DAG.getContext(), InVT);
212   EVT OutVT = N->getValueType(0);
213   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
214   SDLoc dl(N);
215
216   switch (getTypeAction(InVT)) {
217   case TargetLowering::TypeLegal:
218     break;
219   case TargetLowering::TypePromoteInteger:
220     if (NOutVT.bitsEq(NInVT) && !NOutVT.isVector() && !NInVT.isVector())
221       // The input promotes to the same size.  Convert the promoted value.
222       return DAG.getNode(ISD::BITCAST, dl, NOutVT, GetPromotedInteger(InOp));
223     break;
224   case TargetLowering::TypeSoftenFloat:
225     // Promote the integer operand by hand.
226     return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT, GetSoftenedFloat(InOp));
227   case TargetLowering::TypeExpandInteger:
228   case TargetLowering::TypeExpandFloat:
229     break;
230   case TargetLowering::TypeScalarizeVector:
231     // Convert the element to an integer and promote it by hand.
232     if (!NOutVT.isVector())
233       return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT,
234                          BitConvertToInteger(GetScalarizedVector(InOp)));
235     break;
236   case TargetLowering::TypeSplitVector: {
237     // For example, i32 = BITCAST v2i16 on alpha.  Convert the split
238     // pieces of the input into integers and reassemble in the final type.
239     SDValue Lo, Hi;
240     GetSplitVector(N->getOperand(0), Lo, Hi);
241     Lo = BitConvertToInteger(Lo);
242     Hi = BitConvertToInteger(Hi);
243
244     if (TLI.isBigEndian())
245       std::swap(Lo, Hi);
246
247     InOp = DAG.getNode(ISD::ANY_EXTEND, dl,
248                        EVT::getIntegerVT(*DAG.getContext(),
249                                          NOutVT.getSizeInBits()),
250                        JoinIntegers(Lo, Hi));
251     return DAG.getNode(ISD::BITCAST, dl, NOutVT, InOp);
252   }
253   case TargetLowering::TypeWidenVector:
254     // The input is widened to the same size. Convert to the widened value.
255     // Make sure that the outgoing value is not a vector, because this would
256     // make us bitcast between two vectors which are legalized in different ways.
257     if (NOutVT.bitsEq(NInVT) && !NOutVT.isVector())
258       return DAG.getNode(ISD::BITCAST, dl, NOutVT, GetWidenedVector(InOp));
259   }
260
261   return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT,
262                      CreateStackStoreLoad(InOp, OutVT));
263 }
264
265 SDValue DAGTypeLegalizer::PromoteIntRes_BSWAP(SDNode *N) {
266   SDValue Op = GetPromotedInteger(N->getOperand(0));
267   EVT OVT = N->getValueType(0);
268   EVT NVT = Op.getValueType();
269   SDLoc dl(N);
270
271   unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
272   return DAG.getNode(ISD::SRL, dl, NVT, DAG.getNode(ISD::BSWAP, dl, NVT, Op),
273                      DAG.getConstant(DiffBits, TLI.getPointerTy()));
274 }
275
276 SDValue DAGTypeLegalizer::PromoteIntRes_BUILD_PAIR(SDNode *N) {
277   // The pair element type may be legal, or may not promote to the same type as
278   // the result, for example i14 = BUILD_PAIR (i7, i7).  Handle all cases.
279   return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N),
280                      TLI.getTypeToTransformTo(*DAG.getContext(),
281                      N->getValueType(0)), JoinIntegers(N->getOperand(0),
282                      N->getOperand(1)));
283 }
284
285 SDValue DAGTypeLegalizer::PromoteIntRes_Constant(SDNode *N) {
286   EVT VT = N->getValueType(0);
287   // FIXME there is no actual debug info here
288   SDLoc dl(N);
289   // Zero extend things like i1, sign extend everything else.  It shouldn't
290   // matter in theory which one we pick, but this tends to give better code?
291   unsigned Opc = VT.isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
292   SDValue Result = DAG.getNode(Opc, dl,
293                                TLI.getTypeToTransformTo(*DAG.getContext(), VT),
294                                SDValue(N, 0));
295   assert(isa<ConstantSDNode>(Result) && "Didn't constant fold ext?");
296   return Result;
297 }
298
299 SDValue DAGTypeLegalizer::PromoteIntRes_CONVERT_RNDSAT(SDNode *N) {
300   ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode();
301   assert ((CvtCode == ISD::CVT_SS || CvtCode == ISD::CVT_SU ||
302            CvtCode == ISD::CVT_US || CvtCode == ISD::CVT_UU ||
303            CvtCode == ISD::CVT_SF || CvtCode == ISD::CVT_UF) &&
304           "can only promote integers");
305   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
306   return DAG.getConvertRndSat(OutVT, SDLoc(N), N->getOperand(0),
307                               N->getOperand(1), N->getOperand(2),
308                               N->getOperand(3), N->getOperand(4), CvtCode);
309 }
310
311 SDValue DAGTypeLegalizer::PromoteIntRes_CTLZ(SDNode *N) {
312   // Zero extend to the promoted type and do the count there.
313   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
314   SDLoc dl(N);
315   EVT OVT = N->getValueType(0);
316   EVT NVT = Op.getValueType();
317   Op = DAG.getNode(N->getOpcode(), dl, NVT, Op);
318   // Subtract off the extra leading bits in the bigger type.
319   return DAG.getNode(ISD::SUB, dl, NVT, Op,
320                      DAG.getConstant(NVT.getSizeInBits() -
321                                      OVT.getSizeInBits(), NVT));
322 }
323
324 SDValue DAGTypeLegalizer::PromoteIntRes_CTPOP(SDNode *N) {
325   // Zero extend to the promoted type and do the count there.
326   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
327   return DAG.getNode(ISD::CTPOP, SDLoc(N), Op.getValueType(), Op);
328 }
329
330 SDValue DAGTypeLegalizer::PromoteIntRes_CTTZ(SDNode *N) {
331   SDValue Op = GetPromotedInteger(N->getOperand(0));
332   EVT OVT = N->getValueType(0);
333   EVT NVT = Op.getValueType();
334   SDLoc dl(N);
335   if (N->getOpcode() == ISD::CTTZ) {
336     // The count is the same in the promoted type except if the original
337     // value was zero.  This can be handled by setting the bit just off
338     // the top of the original type.
339     APInt TopBit(NVT.getSizeInBits(), 0);
340     TopBit.setBit(OVT.getSizeInBits());
341     Op = DAG.getNode(ISD::OR, dl, NVT, Op, DAG.getConstant(TopBit, NVT));
342   }
343   return DAG.getNode(N->getOpcode(), dl, NVT, Op);
344 }
345
346 SDValue DAGTypeLegalizer::PromoteIntRes_EXTRACT_VECTOR_ELT(SDNode *N) {
347   SDLoc dl(N);
348   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
349   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, NVT, N->getOperand(0),
350                      N->getOperand(1));
351 }
352
353 SDValue DAGTypeLegalizer::PromoteIntRes_FP_TO_XINT(SDNode *N) {
354   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
355   unsigned NewOpc = N->getOpcode();
356   SDLoc dl(N);
357
358   // If we're promoting a UINT to a larger size and the larger FP_TO_UINT is
359   // not Legal, check to see if we can use FP_TO_SINT instead.  (If both UINT
360   // and SINT conversions are Custom, there is no way to tell which is
361   // preferable. We choose SINT because that's the right thing on PPC.)
362   if (N->getOpcode() == ISD::FP_TO_UINT &&
363       !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
364       TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NVT))
365     NewOpc = ISD::FP_TO_SINT;
366
367   SDValue Res = DAG.getNode(NewOpc, dl, NVT, N->getOperand(0));
368
369   // Assert that the converted value fits in the original type.  If it doesn't
370   // (eg: because the value being converted is too big), then the result of the
371   // original operation was undefined anyway, so the assert is still correct.
372   return DAG.getNode(N->getOpcode() == ISD::FP_TO_UINT ?
373                      ISD::AssertZext : ISD::AssertSext, dl, NVT, Res,
374                      DAG.getValueType(N->getValueType(0).getScalarType()));
375 }
376
377 SDValue DAGTypeLegalizer::PromoteIntRes_FP32_TO_FP16(SDNode *N) {
378   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
379   SDLoc dl(N);
380
381   SDValue Res = DAG.getNode(N->getOpcode(), dl, NVT, N->getOperand(0));
382
383   return DAG.getNode(ISD::AssertZext, dl,
384                      NVT, Res, DAG.getValueType(N->getValueType(0)));
385 }
386
387 SDValue DAGTypeLegalizer::PromoteIntRes_INT_EXTEND(SDNode *N) {
388   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
389   SDLoc dl(N);
390
391   if (getTypeAction(N->getOperand(0).getValueType())
392       == TargetLowering::TypePromoteInteger) {
393     SDValue Res = GetPromotedInteger(N->getOperand(0));
394     assert(Res.getValueType().bitsLE(NVT) && "Extension doesn't make sense!");
395
396     // If the result and operand types are the same after promotion, simplify
397     // to an in-register extension.
398     if (NVT == Res.getValueType()) {
399       // The high bits are not guaranteed to be anything.  Insert an extend.
400       if (N->getOpcode() == ISD::SIGN_EXTEND)
401         return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Res,
402                            DAG.getValueType(N->getOperand(0).getValueType()));
403       if (N->getOpcode() == ISD::ZERO_EXTEND)
404         return DAG.getZeroExtendInReg(Res, dl,
405                       N->getOperand(0).getValueType().getScalarType());
406       assert(N->getOpcode() == ISD::ANY_EXTEND && "Unknown integer extension!");
407       return Res;
408     }
409   }
410
411   // Otherwise, just extend the original operand all the way to the larger type.
412   return DAG.getNode(N->getOpcode(), dl, NVT, N->getOperand(0));
413 }
414
415 SDValue DAGTypeLegalizer::PromoteIntRes_LOAD(LoadSDNode *N) {
416   assert(ISD::isUNINDEXEDLoad(N) && "Indexed load during type legalization!");
417   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
418   ISD::LoadExtType ExtType =
419     ISD::isNON_EXTLoad(N) ? ISD::EXTLOAD : N->getExtensionType();
420   SDLoc dl(N);
421   SDValue Res = DAG.getExtLoad(ExtType, dl, NVT, N->getChain(), N->getBasePtr(),
422                                N->getMemoryVT(), N->getMemOperand());
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), Ops);
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);
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   SDLoc dl(N);
1042
1043   SDValue Val = GetPromotedInteger(N->getValue());  // Get promoted value.
1044
1045   // Truncate the value and store the result.
1046   return DAG.getTruncStore(Ch, dl, Val, Ptr,
1047                            N->getMemoryVT(), N->getMemOperand());
1048 }
1049
1050 SDValue DAGTypeLegalizer::PromoteIntOp_TRUNCATE(SDNode *N) {
1051   SDValue Op = GetPromotedInteger(N->getOperand(0));
1052   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), Op);
1053 }
1054
1055 SDValue DAGTypeLegalizer::PromoteIntOp_UINT_TO_FP(SDNode *N) {
1056   return SDValue(DAG.UpdateNodeOperands(N,
1057                                 ZExtPromotedInteger(N->getOperand(0))), 0);
1058 }
1059
1060 SDValue DAGTypeLegalizer::PromoteIntOp_ZERO_EXTEND(SDNode *N) {
1061   SDLoc dl(N);
1062   SDValue Op = GetPromotedInteger(N->getOperand(0));
1063   Op = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Op);
1064   return DAG.getZeroExtendInReg(Op, dl,
1065                                 N->getOperand(0).getValueType().getScalarType());
1066 }
1067
1068
1069 //===----------------------------------------------------------------------===//
1070 //  Integer Result Expansion
1071 //===----------------------------------------------------------------------===//
1072
1073 /// ExpandIntegerResult - This method is called when the specified result of the
1074 /// specified node is found to need expansion.  At this point, the node may also
1075 /// have invalid operands or may have other results that need promotion, we just
1076 /// know that (at least) one result needs expansion.
1077 void DAGTypeLegalizer::ExpandIntegerResult(SDNode *N, unsigned ResNo) {
1078   DEBUG(dbgs() << "Expand integer result: "; N->dump(&DAG); dbgs() << "\n");
1079   SDValue Lo, Hi;
1080   Lo = Hi = SDValue();
1081
1082   // See if the target wants to custom expand this node.
1083   if (CustomLowerNode(N, N->getValueType(ResNo), true))
1084     return;
1085
1086   switch (N->getOpcode()) {
1087   default:
1088 #ifndef NDEBUG
1089     dbgs() << "ExpandIntegerResult #" << ResNo << ": ";
1090     N->dump(&DAG); dbgs() << "\n";
1091 #endif
1092     llvm_unreachable("Do not know how to expand the result of this operator!");
1093
1094   case ISD::MERGE_VALUES: SplitRes_MERGE_VALUES(N, ResNo, Lo, Hi); break;
1095   case ISD::SELECT:       SplitRes_SELECT(N, Lo, Hi); break;
1096   case ISD::SELECT_CC:    SplitRes_SELECT_CC(N, Lo, Hi); break;
1097   case ISD::UNDEF:        SplitRes_UNDEF(N, Lo, Hi); break;
1098
1099   case ISD::BITCAST:            ExpandRes_BITCAST(N, Lo, Hi); break;
1100   case ISD::BUILD_PAIR:         ExpandRes_BUILD_PAIR(N, Lo, Hi); break;
1101   case ISD::EXTRACT_ELEMENT:    ExpandRes_EXTRACT_ELEMENT(N, Lo, Hi); break;
1102   case ISD::EXTRACT_VECTOR_ELT: ExpandRes_EXTRACT_VECTOR_ELT(N, Lo, Hi); break;
1103   case ISD::VAARG:              ExpandRes_VAARG(N, Lo, Hi); break;
1104
1105   case ISD::ANY_EXTEND:  ExpandIntRes_ANY_EXTEND(N, Lo, Hi); break;
1106   case ISD::AssertSext:  ExpandIntRes_AssertSext(N, Lo, Hi); break;
1107   case ISD::AssertZext:  ExpandIntRes_AssertZext(N, Lo, Hi); break;
1108   case ISD::BSWAP:       ExpandIntRes_BSWAP(N, Lo, Hi); break;
1109   case ISD::Constant:    ExpandIntRes_Constant(N, Lo, Hi); break;
1110   case ISD::CTLZ_ZERO_UNDEF:
1111   case ISD::CTLZ:        ExpandIntRes_CTLZ(N, Lo, Hi); break;
1112   case ISD::CTPOP:       ExpandIntRes_CTPOP(N, Lo, Hi); break;
1113   case ISD::CTTZ_ZERO_UNDEF:
1114   case ISD::CTTZ:        ExpandIntRes_CTTZ(N, Lo, Hi); break;
1115   case ISD::FP_TO_SINT:  ExpandIntRes_FP_TO_SINT(N, Lo, Hi); break;
1116   case ISD::FP_TO_UINT:  ExpandIntRes_FP_TO_UINT(N, Lo, Hi); break;
1117   case ISD::LOAD:        ExpandIntRes_LOAD(cast<LoadSDNode>(N), Lo, Hi); break;
1118   case ISD::MUL:         ExpandIntRes_MUL(N, Lo, Hi); break;
1119   case ISD::SDIV:        ExpandIntRes_SDIV(N, Lo, Hi); break;
1120   case ISD::SIGN_EXTEND: ExpandIntRes_SIGN_EXTEND(N, Lo, Hi); break;
1121   case ISD::SIGN_EXTEND_INREG: ExpandIntRes_SIGN_EXTEND_INREG(N, Lo, Hi); break;
1122   case ISD::SREM:        ExpandIntRes_SREM(N, Lo, Hi); break;
1123   case ISD::TRUNCATE:    ExpandIntRes_TRUNCATE(N, Lo, Hi); break;
1124   case ISD::UDIV:        ExpandIntRes_UDIV(N, Lo, Hi); break;
1125   case ISD::UREM:        ExpandIntRes_UREM(N, Lo, Hi); break;
1126   case ISD::ZERO_EXTEND: ExpandIntRes_ZERO_EXTEND(N, Lo, Hi); break;
1127   case ISD::ATOMIC_LOAD: ExpandIntRes_ATOMIC_LOAD(N, Lo, Hi); break;
1128
1129   case ISD::ATOMIC_LOAD_ADD:
1130   case ISD::ATOMIC_LOAD_SUB:
1131   case ISD::ATOMIC_LOAD_AND:
1132   case ISD::ATOMIC_LOAD_OR:
1133   case ISD::ATOMIC_LOAD_XOR:
1134   case ISD::ATOMIC_LOAD_NAND:
1135   case ISD::ATOMIC_LOAD_MIN:
1136   case ISD::ATOMIC_LOAD_MAX:
1137   case ISD::ATOMIC_LOAD_UMIN:
1138   case ISD::ATOMIC_LOAD_UMAX:
1139   case ISD::ATOMIC_SWAP:
1140   case ISD::ATOMIC_CMP_SWAP: {
1141     std::pair<SDValue, SDValue> Tmp = ExpandAtomic(N);
1142     SplitInteger(Tmp.first, Lo, Hi);
1143     ReplaceValueWith(SDValue(N, 1), Tmp.second);
1144     break;
1145   }
1146
1147   case ISD::AND:
1148   case ISD::OR:
1149   case ISD::XOR: ExpandIntRes_Logical(N, Lo, Hi); break;
1150
1151   case ISD::ADD:
1152   case ISD::SUB: ExpandIntRes_ADDSUB(N, Lo, Hi); break;
1153
1154   case ISD::ADDC:
1155   case ISD::SUBC: ExpandIntRes_ADDSUBC(N, Lo, Hi); break;
1156
1157   case ISD::ADDE:
1158   case ISD::SUBE: ExpandIntRes_ADDSUBE(N, Lo, Hi); break;
1159
1160   case ISD::SHL:
1161   case ISD::SRA:
1162   case ISD::SRL: ExpandIntRes_Shift(N, Lo, Hi); break;
1163
1164   case ISD::SADDO:
1165   case ISD::SSUBO: ExpandIntRes_SADDSUBO(N, Lo, Hi); break;
1166   case ISD::UADDO:
1167   case ISD::USUBO: ExpandIntRes_UADDSUBO(N, Lo, Hi); break;
1168   case ISD::UMULO:
1169   case ISD::SMULO: ExpandIntRes_XMULO(N, Lo, Hi); break;
1170   }
1171
1172   // If Lo/Hi is null, the sub-method took care of registering results etc.
1173   if (Lo.getNode())
1174     SetExpandedInteger(SDValue(N, ResNo), Lo, Hi);
1175 }
1176
1177 /// Lower an atomic node to the appropriate builtin call.
1178 std::pair <SDValue, SDValue> DAGTypeLegalizer::ExpandAtomic(SDNode *Node) {
1179   unsigned Opc = Node->getOpcode();
1180   MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
1181   RTLIB::Libcall LC;
1182
1183   switch (Opc) {
1184   default:
1185     llvm_unreachable("Unhandled atomic intrinsic Expand!");
1186   case ISD::ATOMIC_SWAP:
1187     switch (VT.SimpleTy) {
1188     default: llvm_unreachable("Unexpected value type for atomic!");
1189     case MVT::i8:  LC = RTLIB::SYNC_LOCK_TEST_AND_SET_1; break;
1190     case MVT::i16: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_2; break;
1191     case MVT::i32: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_4; break;
1192     case MVT::i64: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_8; break;
1193     case MVT::i128:LC = RTLIB::SYNC_LOCK_TEST_AND_SET_16;break;
1194     }
1195     break;
1196   case ISD::ATOMIC_CMP_SWAP:
1197     switch (VT.SimpleTy) {
1198     default: llvm_unreachable("Unexpected value type for atomic!");
1199     case MVT::i8:  LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_1; break;
1200     case MVT::i16: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_2; break;
1201     case MVT::i32: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_4; break;
1202     case MVT::i64: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_8; break;
1203     case MVT::i128:LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_16;break;
1204     }
1205     break;
1206   case ISD::ATOMIC_LOAD_ADD:
1207     switch (VT.SimpleTy) {
1208     default: llvm_unreachable("Unexpected value type for atomic!");
1209     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_ADD_1; break;
1210     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_ADD_2; break;
1211     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_ADD_4; break;
1212     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_ADD_8; break;
1213     case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_ADD_16;break;
1214     }
1215     break;
1216   case ISD::ATOMIC_LOAD_SUB:
1217     switch (VT.SimpleTy) {
1218     default: llvm_unreachable("Unexpected value type for atomic!");
1219     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_SUB_1; break;
1220     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_SUB_2; break;
1221     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_SUB_4; break;
1222     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_SUB_8; break;
1223     case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_SUB_16;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     case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_AND_16;break;
1234     }
1235     break;
1236   case ISD::ATOMIC_LOAD_OR:
1237     switch (VT.SimpleTy) {
1238     default: llvm_unreachable("Unexpected value type for atomic!");
1239     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_OR_1; break;
1240     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_OR_2; break;
1241     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_OR_4; break;
1242     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_OR_8; break;
1243     case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_OR_16;break;
1244     }
1245     break;
1246   case ISD::ATOMIC_LOAD_XOR:
1247     switch (VT.SimpleTy) {
1248     default: llvm_unreachable("Unexpected value type for atomic!");
1249     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_XOR_1; break;
1250     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_XOR_2; break;
1251     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_XOR_4; break;
1252     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_XOR_8; break;
1253     case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_XOR_16;break;
1254     }
1255     break;
1256   case ISD::ATOMIC_LOAD_NAND:
1257     switch (VT.SimpleTy) {
1258     default: llvm_unreachable("Unexpected value type for atomic!");
1259     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_NAND_1; break;
1260     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_NAND_2; break;
1261     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_NAND_4; break;
1262     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_NAND_8; break;
1263     case MVT::i128:LC = RTLIB::SYNC_FETCH_AND_NAND_16;break;
1264     }
1265     break;
1266   }
1267
1268   return ExpandChainLibCall(LC, Node, false);
1269 }
1270
1271 /// ExpandShiftByConstant - N is a shift by a value that needs to be expanded,
1272 /// and the shift amount is a constant 'Amt'.  Expand the operation.
1273 void DAGTypeLegalizer::ExpandShiftByConstant(SDNode *N, unsigned Amt,
1274                                              SDValue &Lo, SDValue &Hi) {
1275   assert(Amt && "Expected zero shifts to be already optimized away.");
1276   SDLoc DL(N);
1277   // Expand the incoming operand to be shifted, so that we have its parts
1278   SDValue InL, InH;
1279   GetExpandedInteger(N->getOperand(0), InL, InH);
1280
1281   EVT NVT = InL.getValueType();
1282   unsigned VTBits = N->getValueType(0).getSizeInBits();
1283   unsigned NVTBits = NVT.getSizeInBits();
1284   EVT ShTy = N->getOperand(1).getValueType();
1285
1286   if (N->getOpcode() == ISD::SHL) {
1287     if (Amt > VTBits) {
1288       Lo = Hi = DAG.getConstant(0, NVT);
1289     } else if (Amt > NVTBits) {
1290       Lo = DAG.getConstant(0, NVT);
1291       Hi = DAG.getNode(ISD::SHL, DL,
1292                        NVT, InL, DAG.getConstant(Amt-NVTBits, ShTy));
1293     } else if (Amt == NVTBits) {
1294       Lo = DAG.getConstant(0, NVT);
1295       Hi = InL;
1296     } else if (Amt == 1 &&
1297                TLI.isOperationLegalOrCustom(ISD::ADDC,
1298                               TLI.getTypeToExpandTo(*DAG.getContext(), NVT))) {
1299       // Emit this X << 1 as X+X.
1300       SDVTList VTList = DAG.getVTList(NVT, MVT::Glue);
1301       SDValue LoOps[2] = { InL, InL };
1302       Lo = DAG.getNode(ISD::ADDC, DL, VTList, LoOps);
1303       SDValue HiOps[3] = { InH, InH, Lo.getValue(1) };
1304       Hi = DAG.getNode(ISD::ADDE, DL, VTList, HiOps);
1305     } else {
1306       Lo = DAG.getNode(ISD::SHL, DL, NVT, InL, DAG.getConstant(Amt, ShTy));
1307       Hi = DAG.getNode(ISD::OR, DL, NVT,
1308                        DAG.getNode(ISD::SHL, DL, NVT, InH,
1309                                    DAG.getConstant(Amt, ShTy)),
1310                        DAG.getNode(ISD::SRL, DL, NVT, InL,
1311                                    DAG.getConstant(NVTBits-Amt, ShTy)));
1312     }
1313     return;
1314   }
1315
1316   if (N->getOpcode() == ISD::SRL) {
1317     if (Amt > VTBits) {
1318       Lo = DAG.getConstant(0, NVT);
1319       Hi = DAG.getConstant(0, NVT);
1320     } else if (Amt > NVTBits) {
1321       Lo = DAG.getNode(ISD::SRL, DL,
1322                        NVT, InH, DAG.getConstant(Amt-NVTBits,ShTy));
1323       Hi = DAG.getConstant(0, NVT);
1324     } else if (Amt == NVTBits) {
1325       Lo = InH;
1326       Hi = DAG.getConstant(0, NVT);
1327     } else {
1328       Lo = DAG.getNode(ISD::OR, DL, NVT,
1329                        DAG.getNode(ISD::SRL, DL, NVT, InL,
1330                                    DAG.getConstant(Amt, ShTy)),
1331                        DAG.getNode(ISD::SHL, DL, NVT, InH,
1332                                    DAG.getConstant(NVTBits-Amt, ShTy)));
1333       Hi = DAG.getNode(ISD::SRL, DL, NVT, InH, DAG.getConstant(Amt, ShTy));
1334     }
1335     return;
1336   }
1337
1338   assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
1339   if (Amt > VTBits) {
1340     Hi = Lo = DAG.getNode(ISD::SRA, DL, NVT, InH,
1341                           DAG.getConstant(NVTBits-1, ShTy));
1342   } else if (Amt > NVTBits) {
1343     Lo = DAG.getNode(ISD::SRA, DL, NVT, InH,
1344                      DAG.getConstant(Amt-NVTBits, ShTy));
1345     Hi = DAG.getNode(ISD::SRA, DL, NVT, InH,
1346                      DAG.getConstant(NVTBits-1, ShTy));
1347   } else if (Amt == NVTBits) {
1348     Lo = InH;
1349     Hi = DAG.getNode(ISD::SRA, DL, NVT, InH,
1350                      DAG.getConstant(NVTBits-1, ShTy));
1351   } else {
1352     Lo = DAG.getNode(ISD::OR, DL, NVT,
1353                      DAG.getNode(ISD::SRL, DL, NVT, InL,
1354                                  DAG.getConstant(Amt, ShTy)),
1355                      DAG.getNode(ISD::SHL, DL, NVT, InH,
1356                                  DAG.getConstant(NVTBits-Amt, ShTy)));
1357     Hi = DAG.getNode(ISD::SRA, DL, NVT, InH, DAG.getConstant(Amt, ShTy));
1358   }
1359 }
1360
1361 /// ExpandShiftWithKnownAmountBit - Try to determine whether we can simplify
1362 /// this shift based on knowledge of the high bit of the shift amount.  If we
1363 /// can tell this, we know that it is >= 32 or < 32, without knowing the actual
1364 /// shift amount.
1365 bool DAGTypeLegalizer::
1366 ExpandShiftWithKnownAmountBit(SDNode *N, SDValue &Lo, SDValue &Hi) {
1367   SDValue Amt = N->getOperand(1);
1368   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1369   EVT ShTy = Amt.getValueType();
1370   unsigned ShBits = ShTy.getScalarType().getSizeInBits();
1371   unsigned NVTBits = NVT.getScalarType().getSizeInBits();
1372   assert(isPowerOf2_32(NVTBits) &&
1373          "Expanded integer type size not a power of two!");
1374   SDLoc dl(N);
1375
1376   APInt HighBitMask = APInt::getHighBitsSet(ShBits, ShBits - Log2_32(NVTBits));
1377   APInt KnownZero, KnownOne;
1378   DAG.ComputeMaskedBits(N->getOperand(1), KnownZero, KnownOne);
1379
1380   // If we don't know anything about the high bits, exit.
1381   if (((KnownZero|KnownOne) & HighBitMask) == 0)
1382     return false;
1383
1384   // Get the incoming operand to be shifted.
1385   SDValue InL, InH;
1386   GetExpandedInteger(N->getOperand(0), InL, InH);
1387
1388   // If we know that any of the high bits of the shift amount are one, then we
1389   // can do this as a couple of simple shifts.
1390   if (KnownOne.intersects(HighBitMask)) {
1391     // Mask out the high bit, which we know is set.
1392     Amt = DAG.getNode(ISD::AND, dl, ShTy, Amt,
1393                       DAG.getConstant(~HighBitMask, ShTy));
1394
1395     switch (N->getOpcode()) {
1396     default: llvm_unreachable("Unknown shift");
1397     case ISD::SHL:
1398       Lo = DAG.getConstant(0, NVT);              // Low part is zero.
1399       Hi = DAG.getNode(ISD::SHL, dl, NVT, InL, Amt); // High part from Lo part.
1400       return true;
1401     case ISD::SRL:
1402       Hi = DAG.getConstant(0, NVT);              // Hi part is zero.
1403       Lo = DAG.getNode(ISD::SRL, dl, NVT, InH, Amt); // Lo part from Hi part.
1404       return true;
1405     case ISD::SRA:
1406       Hi = DAG.getNode(ISD::SRA, dl, NVT, InH,       // Sign extend high part.
1407                        DAG.getConstant(NVTBits-1, ShTy));
1408       Lo = DAG.getNode(ISD::SRA, dl, NVT, InH, Amt); // Lo part from Hi part.
1409       return true;
1410     }
1411   }
1412
1413   // If we know that all of the high bits of the shift amount are zero, then we
1414   // can do this as a couple of simple shifts.
1415   if ((KnownZero & HighBitMask) == HighBitMask) {
1416     // Calculate 31-x. 31 is used instead of 32 to avoid creating an undefined
1417     // shift if x is zero.  We can use XOR here because x is known to be smaller
1418     // than 32.
1419     SDValue Amt2 = DAG.getNode(ISD::XOR, dl, ShTy, Amt,
1420                                DAG.getConstant(NVTBits-1, ShTy));
1421
1422     unsigned Op1, Op2;
1423     switch (N->getOpcode()) {
1424     default: llvm_unreachable("Unknown shift");
1425     case ISD::SHL:  Op1 = ISD::SHL; Op2 = ISD::SRL; break;
1426     case ISD::SRL:
1427     case ISD::SRA:  Op1 = ISD::SRL; Op2 = ISD::SHL; break;
1428     }
1429
1430     // When shifting right the arithmetic for Lo and Hi is swapped.
1431     if (N->getOpcode() != ISD::SHL)
1432       std::swap(InL, InH);
1433
1434     // Use a little trick to get the bits that move from Lo to Hi. First
1435     // shift by one bit.
1436     SDValue Sh1 = DAG.getNode(Op2, dl, NVT, InL, DAG.getConstant(1, ShTy));
1437     // Then compute the remaining shift with amount-1.
1438     SDValue Sh2 = DAG.getNode(Op2, dl, NVT, Sh1, Amt2);
1439
1440     Lo = DAG.getNode(N->getOpcode(), dl, NVT, InL, Amt);
1441     Hi = DAG.getNode(ISD::OR, dl, NVT, DAG.getNode(Op1, dl, NVT, InH, Amt),Sh2);
1442
1443     if (N->getOpcode() != ISD::SHL)
1444       std::swap(Hi, Lo);
1445     return true;
1446   }
1447
1448   return false;
1449 }
1450
1451 /// ExpandShiftWithUnknownAmountBit - Fully general expansion of integer shift
1452 /// of any size.
1453 bool DAGTypeLegalizer::
1454 ExpandShiftWithUnknownAmountBit(SDNode *N, SDValue &Lo, SDValue &Hi) {
1455   SDValue Amt = N->getOperand(1);
1456   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1457   EVT ShTy = Amt.getValueType();
1458   unsigned NVTBits = NVT.getSizeInBits();
1459   assert(isPowerOf2_32(NVTBits) &&
1460          "Expanded integer type size not a power of two!");
1461   SDLoc dl(N);
1462
1463   // Get the incoming operand to be shifted.
1464   SDValue InL, InH;
1465   GetExpandedInteger(N->getOperand(0), InL, InH);
1466
1467   SDValue NVBitsNode = DAG.getConstant(NVTBits, ShTy);
1468   SDValue AmtExcess = DAG.getNode(ISD::SUB, dl, ShTy, Amt, NVBitsNode);
1469   SDValue AmtLack = DAG.getNode(ISD::SUB, dl, ShTy, NVBitsNode, Amt);
1470   SDValue isShort = DAG.getSetCC(dl, getSetCCResultType(ShTy),
1471                                  Amt, NVBitsNode, ISD::SETULT);
1472
1473   SDValue LoS, HiS, LoL, HiL;
1474   switch (N->getOpcode()) {
1475   default: llvm_unreachable("Unknown shift");
1476   case ISD::SHL:
1477     // Short: ShAmt < NVTBits
1478     LoS = DAG.getNode(ISD::SHL, dl, NVT, InL, Amt);
1479     HiS = DAG.getNode(ISD::OR, dl, NVT,
1480                       DAG.getNode(ISD::SHL, dl, NVT, InH, Amt),
1481     // FIXME: If Amt is zero, the following shift generates an undefined result
1482     // on some architectures.
1483                       DAG.getNode(ISD::SRL, dl, NVT, InL, AmtLack));
1484
1485     // Long: ShAmt >= NVTBits
1486     LoL = DAG.getConstant(0, NVT);                        // Lo part is zero.
1487     HiL = DAG.getNode(ISD::SHL, dl, NVT, InL, AmtExcess); // Hi from Lo part.
1488
1489     Lo = DAG.getSelect(dl, NVT, isShort, LoS, LoL);
1490     Hi = DAG.getSelect(dl, NVT, isShort, HiS, HiL);
1491     return true;
1492   case ISD::SRL:
1493     // Short: ShAmt < NVTBits
1494     HiS = DAG.getNode(ISD::SRL, dl, NVT, InH, Amt);
1495     LoS = DAG.getNode(ISD::OR, dl, NVT,
1496                       DAG.getNode(ISD::SRL, dl, NVT, InL, Amt),
1497     // FIXME: If Amt is zero, the following shift generates an undefined result
1498     // on some architectures.
1499                       DAG.getNode(ISD::SHL, dl, NVT, InH, AmtLack));
1500
1501     // Long: ShAmt >= NVTBits
1502     HiL = DAG.getConstant(0, NVT);                        // Hi part is zero.
1503     LoL = DAG.getNode(ISD::SRL, dl, NVT, InH, AmtExcess); // Lo from Hi part.
1504
1505     Lo = DAG.getSelect(dl, NVT, isShort, LoS, LoL);
1506     Hi = DAG.getSelect(dl, NVT, isShort, HiS, HiL);
1507     return true;
1508   case ISD::SRA:
1509     // Short: ShAmt < NVTBits
1510     HiS = DAG.getNode(ISD::SRA, dl, NVT, InH, Amt);
1511     LoS = DAG.getNode(ISD::OR, dl, NVT,
1512                       DAG.getNode(ISD::SRL, dl, NVT, InL, Amt),
1513     // FIXME: If Amt is zero, the following shift generates an undefined result
1514     // on some architectures.
1515                       DAG.getNode(ISD::SHL, dl, NVT, InH, AmtLack));
1516
1517     // Long: ShAmt >= NVTBits
1518     HiL = DAG.getNode(ISD::SRA, dl, NVT, InH,             // Sign of Hi part.
1519                       DAG.getConstant(NVTBits-1, ShTy));
1520     LoL = DAG.getNode(ISD::SRA, dl, NVT, InH, AmtExcess); // Lo from Hi part.
1521
1522     Lo = DAG.getSelect(dl, NVT, isShort, LoS, LoL);
1523     Hi = DAG.getSelect(dl, NVT, isShort, HiS, HiL);
1524     return true;
1525   }
1526 }
1527
1528 void DAGTypeLegalizer::ExpandIntRes_ADDSUB(SDNode *N,
1529                                            SDValue &Lo, SDValue &Hi) {
1530   SDLoc dl(N);
1531   // Expand the subcomponents.
1532   SDValue LHSL, LHSH, RHSL, RHSH;
1533   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1534   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1535
1536   EVT NVT = LHSL.getValueType();
1537   SDValue LoOps[2] = { LHSL, RHSL };
1538   SDValue HiOps[3] = { LHSH, RHSH };
1539
1540   // Do not generate ADDC/ADDE or SUBC/SUBE if the target does not support
1541   // them.  TODO: Teach operation legalization how to expand unsupported
1542   // ADDC/ADDE/SUBC/SUBE.  The problem is that these operations generate
1543   // a carry of type MVT::Glue, but there doesn't seem to be any way to
1544   // generate a value of this type in the expanded code sequence.
1545   bool hasCarry =
1546     TLI.isOperationLegalOrCustom(N->getOpcode() == ISD::ADD ?
1547                                    ISD::ADDC : ISD::SUBC,
1548                                  TLI.getTypeToExpandTo(*DAG.getContext(), NVT));
1549
1550   if (hasCarry) {
1551     SDVTList VTList = DAG.getVTList(NVT, MVT::Glue);
1552     if (N->getOpcode() == ISD::ADD) {
1553       Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps);
1554       HiOps[2] = Lo.getValue(1);
1555       Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps);
1556     } else {
1557       Lo = DAG.getNode(ISD::SUBC, dl, VTList, LoOps);
1558       HiOps[2] = Lo.getValue(1);
1559       Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps);
1560     }
1561     return;
1562   }
1563
1564   if (N->getOpcode() == ISD::ADD) {
1565     Lo = DAG.getNode(ISD::ADD, dl, NVT, LoOps);
1566     Hi = DAG.getNode(ISD::ADD, dl, NVT, ArrayRef<SDValue>(HiOps, 2));
1567     SDValue Cmp1 = DAG.getSetCC(dl, getSetCCResultType(NVT), Lo, LoOps[0],
1568                                 ISD::SETULT);
1569     SDValue Carry1 = DAG.getSelect(dl, NVT, Cmp1,
1570                                    DAG.getConstant(1, NVT),
1571                                    DAG.getConstant(0, NVT));
1572     SDValue Cmp2 = DAG.getSetCC(dl, getSetCCResultType(NVT), Lo, LoOps[1],
1573                                 ISD::SETULT);
1574     SDValue Carry2 = DAG.getSelect(dl, NVT, Cmp2,
1575                                    DAG.getConstant(1, NVT), Carry1);
1576     Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, Carry2);
1577   } else {
1578     Lo = DAG.getNode(ISD::SUB, dl, NVT, LoOps);
1579     Hi = DAG.getNode(ISD::SUB, dl, NVT, ArrayRef<SDValue>(HiOps, 2));
1580     SDValue Cmp =
1581       DAG.getSetCC(dl, getSetCCResultType(LoOps[0].getValueType()),
1582                    LoOps[0], LoOps[1], ISD::SETULT);
1583     SDValue Borrow = DAG.getSelect(dl, NVT, Cmp,
1584                                    DAG.getConstant(1, NVT),
1585                                    DAG.getConstant(0, NVT));
1586     Hi = DAG.getNode(ISD::SUB, dl, NVT, Hi, Borrow);
1587   }
1588 }
1589
1590 void DAGTypeLegalizer::ExpandIntRes_ADDSUBC(SDNode *N,
1591                                             SDValue &Lo, SDValue &Hi) {
1592   // Expand the subcomponents.
1593   SDValue LHSL, LHSH, RHSL, RHSH;
1594   SDLoc dl(N);
1595   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1596   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1597   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Glue);
1598   SDValue LoOps[2] = { LHSL, RHSL };
1599   SDValue HiOps[3] = { LHSH, RHSH };
1600
1601   if (N->getOpcode() == ISD::ADDC) {
1602     Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps);
1603     HiOps[2] = Lo.getValue(1);
1604     Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps);
1605   } else {
1606     Lo = DAG.getNode(ISD::SUBC, dl, VTList, LoOps);
1607     HiOps[2] = Lo.getValue(1);
1608     Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps);
1609   }
1610
1611   // Legalized the flag result - switch anything that used the old flag to
1612   // use the new one.
1613   ReplaceValueWith(SDValue(N, 1), Hi.getValue(1));
1614 }
1615
1616 void DAGTypeLegalizer::ExpandIntRes_ADDSUBE(SDNode *N,
1617                                             SDValue &Lo, SDValue &Hi) {
1618   // Expand the subcomponents.
1619   SDValue LHSL, LHSH, RHSL, RHSH;
1620   SDLoc dl(N);
1621   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1622   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1623   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Glue);
1624   SDValue LoOps[3] = { LHSL, RHSL, N->getOperand(2) };
1625   SDValue HiOps[3] = { LHSH, RHSH };
1626
1627   Lo = DAG.getNode(N->getOpcode(), dl, VTList, LoOps);
1628   HiOps[2] = Lo.getValue(1);
1629   Hi = DAG.getNode(N->getOpcode(), dl, VTList, HiOps);
1630
1631   // Legalized the flag result - switch anything that used the old flag to
1632   // use the new one.
1633   ReplaceValueWith(SDValue(N, 1), Hi.getValue(1));
1634 }
1635
1636 void DAGTypeLegalizer::ExpandIntRes_MERGE_VALUES(SDNode *N, unsigned ResNo,
1637                                                  SDValue &Lo, SDValue &Hi) {
1638   SDValue Res = DisintegrateMERGE_VALUES(N, ResNo);
1639   SplitInteger(Res, Lo, Hi);
1640 }
1641
1642 void DAGTypeLegalizer::ExpandIntRes_ANY_EXTEND(SDNode *N,
1643                                                SDValue &Lo, SDValue &Hi) {
1644   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1645   SDLoc dl(N);
1646   SDValue Op = N->getOperand(0);
1647   if (Op.getValueType().bitsLE(NVT)) {
1648     // The low part is any extension of the input (which degenerates to a copy).
1649     Lo = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Op);
1650     Hi = DAG.getUNDEF(NVT);   // The high part is undefined.
1651   } else {
1652     // For example, extension of an i48 to an i64.  The operand type necessarily
1653     // promotes to the result type, so will end up being expanded too.
1654     assert(getTypeAction(Op.getValueType()) ==
1655            TargetLowering::TypePromoteInteger &&
1656            "Only know how to promote this result!");
1657     SDValue Res = GetPromotedInteger(Op);
1658     assert(Res.getValueType() == N->getValueType(0) &&
1659            "Operand over promoted?");
1660     // Split the promoted operand.  This will simplify when it is expanded.
1661     SplitInteger(Res, Lo, Hi);
1662   }
1663 }
1664
1665 void DAGTypeLegalizer::ExpandIntRes_AssertSext(SDNode *N,
1666                                                SDValue &Lo, SDValue &Hi) {
1667   SDLoc dl(N);
1668   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1669   EVT NVT = Lo.getValueType();
1670   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1671   unsigned NVTBits = NVT.getSizeInBits();
1672   unsigned EVTBits = EVT.getSizeInBits();
1673
1674   if (NVTBits < EVTBits) {
1675     Hi = DAG.getNode(ISD::AssertSext, dl, NVT, Hi,
1676                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
1677                                                         EVTBits - NVTBits)));
1678   } else {
1679     Lo = DAG.getNode(ISD::AssertSext, dl, NVT, Lo, DAG.getValueType(EVT));
1680     // The high part replicates the sign bit of Lo, make it explicit.
1681     Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
1682                      DAG.getConstant(NVTBits-1, TLI.getPointerTy()));
1683   }
1684 }
1685
1686 void DAGTypeLegalizer::ExpandIntRes_AssertZext(SDNode *N,
1687                                                SDValue &Lo, SDValue &Hi) {
1688   SDLoc dl(N);
1689   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1690   EVT NVT = Lo.getValueType();
1691   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1692   unsigned NVTBits = NVT.getSizeInBits();
1693   unsigned EVTBits = EVT.getSizeInBits();
1694
1695   if (NVTBits < EVTBits) {
1696     Hi = DAG.getNode(ISD::AssertZext, dl, NVT, Hi,
1697                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
1698                                                         EVTBits - NVTBits)));
1699   } else {
1700     Lo = DAG.getNode(ISD::AssertZext, dl, NVT, Lo, DAG.getValueType(EVT));
1701     // The high part must be zero, make it explicit.
1702     Hi = DAG.getConstant(0, NVT);
1703   }
1704 }
1705
1706 void DAGTypeLegalizer::ExpandIntRes_BSWAP(SDNode *N,
1707                                           SDValue &Lo, SDValue &Hi) {
1708   SDLoc dl(N);
1709   GetExpandedInteger(N->getOperand(0), Hi, Lo);  // Note swapped operands.
1710   Lo = DAG.getNode(ISD::BSWAP, dl, Lo.getValueType(), Lo);
1711   Hi = DAG.getNode(ISD::BSWAP, dl, Hi.getValueType(), Hi);
1712 }
1713
1714 void DAGTypeLegalizer::ExpandIntRes_Constant(SDNode *N,
1715                                              SDValue &Lo, SDValue &Hi) {
1716   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1717   unsigned NBitWidth = NVT.getSizeInBits();
1718   auto Constant = cast<ConstantSDNode>(N);
1719   const APInt &Cst = Constant->getAPIntValue();
1720   bool IsTarget = Constant->isTargetOpcode();
1721   bool IsOpaque = Constant->isOpaque();
1722   Lo = DAG.getConstant(Cst.trunc(NBitWidth), NVT, IsTarget, IsOpaque);
1723   Hi = DAG.getConstant(Cst.lshr(NBitWidth).trunc(NBitWidth), NVT, IsTarget,
1724                        IsOpaque);
1725 }
1726
1727 void DAGTypeLegalizer::ExpandIntRes_CTLZ(SDNode *N,
1728                                          SDValue &Lo, SDValue &Hi) {
1729   SDLoc dl(N);
1730   // ctlz (HiLo) -> Hi != 0 ? ctlz(Hi) : (ctlz(Lo)+32)
1731   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1732   EVT NVT = Lo.getValueType();
1733
1734   SDValue HiNotZero = DAG.getSetCC(dl, getSetCCResultType(NVT), Hi,
1735                                    DAG.getConstant(0, NVT), ISD::SETNE);
1736
1737   SDValue LoLZ = DAG.getNode(N->getOpcode(), dl, NVT, Lo);
1738   SDValue HiLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, NVT, Hi);
1739
1740   Lo = DAG.getSelect(dl, NVT, HiNotZero, HiLZ,
1741                      DAG.getNode(ISD::ADD, dl, NVT, LoLZ,
1742                                  DAG.getConstant(NVT.getSizeInBits(), NVT)));
1743   Hi = DAG.getConstant(0, NVT);
1744 }
1745
1746 void DAGTypeLegalizer::ExpandIntRes_CTPOP(SDNode *N,
1747                                           SDValue &Lo, SDValue &Hi) {
1748   SDLoc dl(N);
1749   // ctpop(HiLo) -> ctpop(Hi)+ctpop(Lo)
1750   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1751   EVT NVT = Lo.getValueType();
1752   Lo = DAG.getNode(ISD::ADD, dl, NVT, DAG.getNode(ISD::CTPOP, dl, NVT, Lo),
1753                    DAG.getNode(ISD::CTPOP, dl, NVT, Hi));
1754   Hi = DAG.getConstant(0, NVT);
1755 }
1756
1757 void DAGTypeLegalizer::ExpandIntRes_CTTZ(SDNode *N,
1758                                          SDValue &Lo, SDValue &Hi) {
1759   SDLoc dl(N);
1760   // cttz (HiLo) -> Lo != 0 ? cttz(Lo) : (cttz(Hi)+32)
1761   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1762   EVT NVT = Lo.getValueType();
1763
1764   SDValue LoNotZero = DAG.getSetCC(dl, getSetCCResultType(NVT), Lo,
1765                                    DAG.getConstant(0, NVT), ISD::SETNE);
1766
1767   SDValue LoLZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, NVT, Lo);
1768   SDValue HiLZ = DAG.getNode(N->getOpcode(), dl, NVT, Hi);
1769
1770   Lo = DAG.getSelect(dl, NVT, LoNotZero, LoLZ,
1771                      DAG.getNode(ISD::ADD, dl, NVT, HiLZ,
1772                                  DAG.getConstant(NVT.getSizeInBits(), NVT)));
1773   Hi = DAG.getConstant(0, NVT);
1774 }
1775
1776 void DAGTypeLegalizer::ExpandIntRes_FP_TO_SINT(SDNode *N, SDValue &Lo,
1777                                                SDValue &Hi) {
1778   SDLoc dl(N);
1779   EVT VT = N->getValueType(0);
1780   SDValue Op = N->getOperand(0);
1781   RTLIB::Libcall LC = RTLIB::getFPTOSINT(Op.getValueType(), VT);
1782   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-sint conversion!");
1783   SplitInteger(TLI.makeLibCall(DAG, LC, VT, &Op, 1, true/*irrelevant*/,
1784                                dl).first,
1785                Lo, Hi);
1786 }
1787
1788 void DAGTypeLegalizer::ExpandIntRes_FP_TO_UINT(SDNode *N, SDValue &Lo,
1789                                                SDValue &Hi) {
1790   SDLoc dl(N);
1791   EVT VT = N->getValueType(0);
1792   SDValue Op = N->getOperand(0);
1793   RTLIB::Libcall LC = RTLIB::getFPTOUINT(Op.getValueType(), VT);
1794   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-uint conversion!");
1795   SplitInteger(TLI.makeLibCall(DAG, LC, VT, &Op, 1, false/*irrelevant*/,
1796                                dl).first,
1797                Lo, Hi);
1798 }
1799
1800 void DAGTypeLegalizer::ExpandIntRes_LOAD(LoadSDNode *N,
1801                                          SDValue &Lo, SDValue &Hi) {
1802   if (ISD::isNormalLoad(N)) {
1803     ExpandRes_NormalLoad(N, Lo, Hi);
1804     return;
1805   }
1806
1807   assert(ISD::isUNINDEXEDLoad(N) && "Indexed load during type legalization!");
1808
1809   EVT VT = N->getValueType(0);
1810   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
1811   SDValue Ch  = N->getChain();
1812   SDValue Ptr = N->getBasePtr();
1813   ISD::LoadExtType ExtType = N->getExtensionType();
1814   unsigned Alignment = N->getAlignment();
1815   bool isVolatile = N->isVolatile();
1816   bool isNonTemporal = N->isNonTemporal();
1817   bool isInvariant = N->isInvariant();
1818   const MDNode *TBAAInfo = N->getTBAAInfo();
1819   SDLoc dl(N);
1820
1821   assert(NVT.isByteSized() && "Expanded type not byte sized!");
1822
1823   if (N->getMemoryVT().bitsLE(NVT)) {
1824     EVT MemVT = N->getMemoryVT();
1825
1826     Lo = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr, N->getPointerInfo(),
1827                         MemVT, isVolatile, isNonTemporal, Alignment, TBAAInfo);
1828
1829     // Remember the chain.
1830     Ch = Lo.getValue(1);
1831
1832     if (ExtType == ISD::SEXTLOAD) {
1833       // The high part is obtained by SRA'ing all but one of the bits of the
1834       // lo part.
1835       unsigned LoSize = Lo.getValueType().getSizeInBits();
1836       Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
1837                        DAG.getConstant(LoSize-1, TLI.getPointerTy()));
1838     } else if (ExtType == ISD::ZEXTLOAD) {
1839       // The high part is just a zero.
1840       Hi = DAG.getConstant(0, NVT);
1841     } else {
1842       assert(ExtType == ISD::EXTLOAD && "Unknown extload!");
1843       // The high part is undefined.
1844       Hi = DAG.getUNDEF(NVT);
1845     }
1846   } else if (TLI.isLittleEndian()) {
1847     // Little-endian - low bits are at low addresses.
1848     Lo = DAG.getLoad(NVT, dl, Ch, Ptr, N->getPointerInfo(),
1849                      isVolatile, isNonTemporal, isInvariant, Alignment,
1850                      TBAAInfo);
1851
1852     unsigned ExcessBits =
1853       N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
1854     EVT NEVT = EVT::getIntegerVT(*DAG.getContext(), ExcessBits);
1855
1856     // Increment the pointer to the other half.
1857     unsigned IncrementSize = NVT.getSizeInBits()/8;
1858     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
1859                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
1860     Hi = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr,
1861                         N->getPointerInfo().getWithOffset(IncrementSize), NEVT,
1862                         isVolatile, isNonTemporal,
1863                         MinAlign(Alignment, IncrementSize), TBAAInfo);
1864
1865     // Build a factor node to remember that this load is independent of the
1866     // other one.
1867     Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1868                      Hi.getValue(1));
1869   } else {
1870     // Big-endian - high bits are at low addresses.  Favor aligned loads at
1871     // the cost of some bit-fiddling.
1872     EVT MemVT = N->getMemoryVT();
1873     unsigned EBytes = MemVT.getStoreSize();
1874     unsigned IncrementSize = NVT.getSizeInBits()/8;
1875     unsigned ExcessBits = (EBytes - IncrementSize)*8;
1876
1877     // Load both the high bits and maybe some of the low bits.
1878     Hi = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr, N->getPointerInfo(),
1879                         EVT::getIntegerVT(*DAG.getContext(),
1880                                           MemVT.getSizeInBits() - ExcessBits),
1881                         isVolatile, isNonTemporal, Alignment, TBAAInfo);
1882
1883     // Increment the pointer to the other half.
1884     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
1885                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
1886     // Load the rest of the low bits.
1887     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, NVT, Ch, Ptr,
1888                         N->getPointerInfo().getWithOffset(IncrementSize),
1889                         EVT::getIntegerVT(*DAG.getContext(), ExcessBits),
1890                         isVolatile, isNonTemporal,
1891                         MinAlign(Alignment, IncrementSize), TBAAInfo);
1892
1893     // Build a factor node to remember that this load is independent of the
1894     // other one.
1895     Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1896                      Hi.getValue(1));
1897
1898     if (ExcessBits < NVT.getSizeInBits()) {
1899       // Transfer low bits from the bottom of Hi to the top of Lo.
1900       Lo = DAG.getNode(ISD::OR, dl, NVT, Lo,
1901                        DAG.getNode(ISD::SHL, dl, NVT, Hi,
1902                                    DAG.getConstant(ExcessBits,
1903                                                    TLI.getPointerTy())));
1904       // Move high bits to the right position in Hi.
1905       Hi = DAG.getNode(ExtType == ISD::SEXTLOAD ? ISD::SRA : ISD::SRL, dl,
1906                        NVT, Hi,
1907                        DAG.getConstant(NVT.getSizeInBits() - ExcessBits,
1908                                        TLI.getPointerTy()));
1909     }
1910   }
1911
1912   // Legalized the chain result - switch anything that used the old chain to
1913   // use the new one.
1914   ReplaceValueWith(SDValue(N, 1), Ch);
1915 }
1916
1917 void DAGTypeLegalizer::ExpandIntRes_Logical(SDNode *N,
1918                                             SDValue &Lo, SDValue &Hi) {
1919   SDLoc dl(N);
1920   SDValue LL, LH, RL, RH;
1921   GetExpandedInteger(N->getOperand(0), LL, LH);
1922   GetExpandedInteger(N->getOperand(1), RL, RH);
1923   Lo = DAG.getNode(N->getOpcode(), dl, LL.getValueType(), LL, RL);
1924   Hi = DAG.getNode(N->getOpcode(), dl, LL.getValueType(), LH, RH);
1925 }
1926
1927 void DAGTypeLegalizer::ExpandIntRes_MUL(SDNode *N,
1928                                         SDValue &Lo, SDValue &Hi) {
1929   EVT VT = N->getValueType(0);
1930   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
1931   SDLoc dl(N);
1932
1933   SDValue LL, LH, RL, RH;
1934   GetExpandedInteger(N->getOperand(0), LL, LH);
1935   GetExpandedInteger(N->getOperand(1), RL, RH);
1936
1937   if (TLI.expandMUL(N, Lo, Hi, NVT, DAG, LL, LH, RL, RH))
1938     return;
1939
1940   // If nothing else, we can make a libcall.
1941   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1942   if (VT == MVT::i16)
1943     LC = RTLIB::MUL_I16;
1944   else if (VT == MVT::i32)
1945     LC = RTLIB::MUL_I32;
1946   else if (VT == MVT::i64)
1947     LC = RTLIB::MUL_I64;
1948   else if (VT == MVT::i128)
1949     LC = RTLIB::MUL_I128;
1950   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported MUL!");
1951
1952   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1953   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, 2, true/*irrelevant*/,
1954                                dl).first,
1955                Lo, Hi);
1956 }
1957
1958 void DAGTypeLegalizer::ExpandIntRes_SADDSUBO(SDNode *Node,
1959                                              SDValue &Lo, SDValue &Hi) {
1960   SDValue LHS = Node->getOperand(0);
1961   SDValue RHS = Node->getOperand(1);
1962   SDLoc dl(Node);
1963
1964   // Expand the result by simply replacing it with the equivalent
1965   // non-overflow-checking operation.
1966   SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
1967                             ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
1968                             LHS, RHS);
1969   SplitInteger(Sum, Lo, Hi);
1970
1971   // Compute the overflow.
1972   //
1973   //   LHSSign -> LHS >= 0
1974   //   RHSSign -> RHS >= 0
1975   //   SumSign -> Sum >= 0
1976   //
1977   //   Add:
1978   //   Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
1979   //   Sub:
1980   //   Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
1981   //
1982   EVT OType = Node->getValueType(1);
1983   SDValue Zero = DAG.getConstant(0, LHS.getValueType());
1984
1985   SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
1986   SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
1987   SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
1988                                     Node->getOpcode() == ISD::SADDO ?
1989                                     ISD::SETEQ : ISD::SETNE);
1990
1991   SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
1992   SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
1993
1994   SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
1995
1996   // Use the calculated overflow everywhere.
1997   ReplaceValueWith(SDValue(Node, 1), Cmp);
1998 }
1999
2000 void DAGTypeLegalizer::ExpandIntRes_SDIV(SDNode *N,
2001                                          SDValue &Lo, SDValue &Hi) {
2002   EVT VT = N->getValueType(0);
2003   SDLoc dl(N);
2004
2005   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2006   if (VT == MVT::i16)
2007     LC = RTLIB::SDIV_I16;
2008   else if (VT == MVT::i32)
2009     LC = RTLIB::SDIV_I32;
2010   else if (VT == MVT::i64)
2011     LC = RTLIB::SDIV_I64;
2012   else if (VT == MVT::i128)
2013     LC = RTLIB::SDIV_I128;
2014   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
2015
2016   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2017   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, 2, true, dl).first, Lo, Hi);
2018 }
2019
2020 void DAGTypeLegalizer::ExpandIntRes_Shift(SDNode *N,
2021                                           SDValue &Lo, SDValue &Hi) {
2022   EVT VT = N->getValueType(0);
2023   SDLoc dl(N);
2024
2025   // If we can emit an efficient shift operation, do so now.  Check to see if
2026   // the RHS is a constant.
2027   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2028     return ExpandShiftByConstant(N, CN->getZExtValue(), Lo, Hi);
2029
2030   // If we can determine that the high bit of the shift is zero or one, even if
2031   // the low bits are variable, emit this shift in an optimized form.
2032   if (ExpandShiftWithKnownAmountBit(N, Lo, Hi))
2033     return;
2034
2035   // If this target supports shift_PARTS, use it.  First, map to the _PARTS opc.
2036   unsigned PartsOpc;
2037   if (N->getOpcode() == ISD::SHL) {
2038     PartsOpc = ISD::SHL_PARTS;
2039   } else if (N->getOpcode() == ISD::SRL) {
2040     PartsOpc = ISD::SRL_PARTS;
2041   } else {
2042     assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
2043     PartsOpc = ISD::SRA_PARTS;
2044   }
2045
2046   // Next check to see if the target supports this SHL_PARTS operation or if it
2047   // will custom expand it.
2048   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2049   TargetLowering::LegalizeAction Action = TLI.getOperationAction(PartsOpc, NVT);
2050   if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
2051       Action == TargetLowering::Custom) {
2052     // Expand the subcomponents.
2053     SDValue LHSL, LHSH;
2054     GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
2055     EVT VT = LHSL.getValueType();
2056
2057     // If the shift amount operand is coming from a vector legalization it may
2058     // have an illegal type.  Fix that first by casting the operand, otherwise
2059     // the new SHL_PARTS operation would need further legalization.
2060     SDValue ShiftOp = N->getOperand(1);
2061     EVT ShiftTy = TLI.getShiftAmountTy(VT);
2062     assert(ShiftTy.getScalarType().getSizeInBits() >=
2063            Log2_32_Ceil(VT.getScalarType().getSizeInBits()) &&
2064            "ShiftAmountTy is too small to cover the range of this type!");
2065     if (ShiftOp.getValueType() != ShiftTy)
2066       ShiftOp = DAG.getZExtOrTrunc(ShiftOp, dl, ShiftTy);
2067
2068     SDValue Ops[] = { LHSL, LHSH, ShiftOp };
2069     Lo = DAG.getNode(PartsOpc, dl, DAG.getVTList(VT, VT), Ops);
2070     Hi = Lo.getValue(1);
2071     return;
2072   }
2073
2074   // Otherwise, emit a libcall.
2075   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2076   bool isSigned;
2077   if (N->getOpcode() == ISD::SHL) {
2078     isSigned = false; /*sign irrelevant*/
2079     if (VT == MVT::i16)
2080       LC = RTLIB::SHL_I16;
2081     else if (VT == MVT::i32)
2082       LC = RTLIB::SHL_I32;
2083     else if (VT == MVT::i64)
2084       LC = RTLIB::SHL_I64;
2085     else if (VT == MVT::i128)
2086       LC = RTLIB::SHL_I128;
2087   } else if (N->getOpcode() == ISD::SRL) {
2088     isSigned = false;
2089     if (VT == MVT::i16)
2090       LC = RTLIB::SRL_I16;
2091     else if (VT == MVT::i32)
2092       LC = RTLIB::SRL_I32;
2093     else if (VT == MVT::i64)
2094       LC = RTLIB::SRL_I64;
2095     else if (VT == MVT::i128)
2096       LC = RTLIB::SRL_I128;
2097   } else {
2098     assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
2099     isSigned = true;
2100     if (VT == MVT::i16)
2101       LC = RTLIB::SRA_I16;
2102     else if (VT == MVT::i32)
2103       LC = RTLIB::SRA_I32;
2104     else if (VT == MVT::i64)
2105       LC = RTLIB::SRA_I64;
2106     else if (VT == MVT::i128)
2107       LC = RTLIB::SRA_I128;
2108   }
2109
2110   if (LC != RTLIB::UNKNOWN_LIBCALL && TLI.getLibcallName(LC)) {
2111     SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2112     SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, 2, isSigned, dl).first, Lo,
2113                  Hi);
2114     return;
2115   }
2116
2117   if (!ExpandShiftWithUnknownAmountBit(N, Lo, Hi))
2118     llvm_unreachable("Unsupported shift!");
2119 }
2120
2121 void DAGTypeLegalizer::ExpandIntRes_SIGN_EXTEND(SDNode *N,
2122                                                 SDValue &Lo, SDValue &Hi) {
2123   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2124   SDLoc dl(N);
2125   SDValue Op = N->getOperand(0);
2126   if (Op.getValueType().bitsLE(NVT)) {
2127     // The low part is sign extension of the input (degenerates to a copy).
2128     Lo = DAG.getNode(ISD::SIGN_EXTEND, dl, NVT, N->getOperand(0));
2129     // The high part is obtained by SRA'ing all but one of the bits of low part.
2130     unsigned LoSize = NVT.getSizeInBits();
2131     Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
2132                      DAG.getConstant(LoSize-1, TLI.getPointerTy()));
2133   } else {
2134     // For example, extension of an i48 to an i64.  The operand type necessarily
2135     // promotes to the result type, so will end up being expanded too.
2136     assert(getTypeAction(Op.getValueType()) ==
2137            TargetLowering::TypePromoteInteger &&
2138            "Only know how to promote this result!");
2139     SDValue Res = GetPromotedInteger(Op);
2140     assert(Res.getValueType() == N->getValueType(0) &&
2141            "Operand over promoted?");
2142     // Split the promoted operand.  This will simplify when it is expanded.
2143     SplitInteger(Res, Lo, Hi);
2144     unsigned ExcessBits =
2145       Op.getValueType().getSizeInBits() - NVT.getSizeInBits();
2146     Hi = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Hi.getValueType(), Hi,
2147                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
2148                                                         ExcessBits)));
2149   }
2150 }
2151
2152 void DAGTypeLegalizer::
2153 ExpandIntRes_SIGN_EXTEND_INREG(SDNode *N, SDValue &Lo, SDValue &Hi) {
2154   SDLoc dl(N);
2155   GetExpandedInteger(N->getOperand(0), Lo, Hi);
2156   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
2157
2158   if (EVT.bitsLE(Lo.getValueType())) {
2159     // sext_inreg the low part if needed.
2160     Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Lo.getValueType(), Lo,
2161                      N->getOperand(1));
2162
2163     // The high part gets the sign extension from the lo-part.  This handles
2164     // things like sextinreg V:i64 from i8.
2165     Hi = DAG.getNode(ISD::SRA, dl, Hi.getValueType(), Lo,
2166                      DAG.getConstant(Hi.getValueType().getSizeInBits()-1,
2167                                      TLI.getPointerTy()));
2168   } else {
2169     // For example, extension of an i48 to an i64.  Leave the low part alone,
2170     // sext_inreg the high part.
2171     unsigned ExcessBits =
2172       EVT.getSizeInBits() - Lo.getValueType().getSizeInBits();
2173     Hi = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Hi.getValueType(), Hi,
2174                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
2175                                                         ExcessBits)));
2176   }
2177 }
2178
2179 void DAGTypeLegalizer::ExpandIntRes_SREM(SDNode *N,
2180                                          SDValue &Lo, SDValue &Hi) {
2181   EVT VT = N->getValueType(0);
2182   SDLoc dl(N);
2183
2184   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2185   if (VT == MVT::i16)
2186     LC = RTLIB::SREM_I16;
2187   else if (VT == MVT::i32)
2188     LC = RTLIB::SREM_I32;
2189   else if (VT == MVT::i64)
2190     LC = RTLIB::SREM_I64;
2191   else if (VT == MVT::i128)
2192     LC = RTLIB::SREM_I128;
2193   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
2194
2195   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2196   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, 2, true, dl).first, Lo, Hi);
2197 }
2198
2199 void DAGTypeLegalizer::ExpandIntRes_TRUNCATE(SDNode *N,
2200                                              SDValue &Lo, SDValue &Hi) {
2201   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2202   SDLoc dl(N);
2203   Lo = DAG.getNode(ISD::TRUNCATE, dl, NVT, N->getOperand(0));
2204   Hi = DAG.getNode(ISD::SRL, dl,
2205                    N->getOperand(0).getValueType(), N->getOperand(0),
2206                    DAG.getConstant(NVT.getSizeInBits(), TLI.getPointerTy()));
2207   Hi = DAG.getNode(ISD::TRUNCATE, dl, NVT, Hi);
2208 }
2209
2210 void DAGTypeLegalizer::ExpandIntRes_UADDSUBO(SDNode *N,
2211                                              SDValue &Lo, SDValue &Hi) {
2212   SDValue LHS = N->getOperand(0);
2213   SDValue RHS = N->getOperand(1);
2214   SDLoc dl(N);
2215
2216   // Expand the result by simply replacing it with the equivalent
2217   // non-overflow-checking operation.
2218   SDValue Sum = DAG.getNode(N->getOpcode() == ISD::UADDO ?
2219                             ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
2220                             LHS, RHS);
2221   SplitInteger(Sum, Lo, Hi);
2222
2223   // Calculate the overflow: addition overflows iff a + b < a, and subtraction
2224   // overflows iff a - b > a.
2225   SDValue Ofl = DAG.getSetCC(dl, N->getValueType(1), Sum, LHS,
2226                              N->getOpcode () == ISD::UADDO ?
2227                              ISD::SETULT : ISD::SETUGT);
2228
2229   // Use the calculated overflow everywhere.
2230   ReplaceValueWith(SDValue(N, 1), Ofl);
2231 }
2232
2233 void DAGTypeLegalizer::ExpandIntRes_XMULO(SDNode *N,
2234                                           SDValue &Lo, SDValue &Hi) {
2235   EVT VT = N->getValueType(0);
2236   SDLoc dl(N);
2237
2238   // A divide for UMULO should be faster than a function call.
2239   if (N->getOpcode() == ISD::UMULO) {
2240     SDValue LHS = N->getOperand(0), RHS = N->getOperand(1);
2241
2242     SDValue MUL = DAG.getNode(ISD::MUL, dl, LHS.getValueType(), LHS, RHS);
2243     SplitInteger(MUL, Lo, Hi);
2244
2245     // A divide for UMULO will be faster than a function call. Select to
2246     // make sure we aren't using 0.
2247     SDValue isZero = DAG.getSetCC(dl, getSetCCResultType(VT),
2248                                   RHS, DAG.getConstant(0, VT), ISD::SETEQ);
2249     SDValue NotZero = DAG.getSelect(dl, VT, isZero,
2250                                     DAG.getConstant(1, VT), RHS);
2251     SDValue DIV = DAG.getNode(ISD::UDIV, dl, VT, MUL, NotZero);
2252     SDValue Overflow = DAG.getSetCC(dl, N->getValueType(1), DIV, LHS,
2253                                     ISD::SETNE);
2254     Overflow = DAG.getSelect(dl, N->getValueType(1), isZero,
2255                              DAG.getConstant(0, N->getValueType(1)),
2256                              Overflow);
2257     ReplaceValueWith(SDValue(N, 1), Overflow);
2258     return;
2259   }
2260
2261   Type *RetTy = VT.getTypeForEVT(*DAG.getContext());
2262   EVT PtrVT = TLI.getPointerTy();
2263   Type *PtrTy = PtrVT.getTypeForEVT(*DAG.getContext());
2264
2265   // Replace this with a libcall that will check overflow.
2266   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2267   if (VT == MVT::i32)
2268     LC = RTLIB::MULO_I32;
2269   else if (VT == MVT::i64)
2270     LC = RTLIB::MULO_I64;
2271   else if (VT == MVT::i128)
2272     LC = RTLIB::MULO_I128;
2273   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported XMULO!");
2274
2275   SDValue Temp = DAG.CreateStackTemporary(PtrVT);
2276   // Temporary for the overflow value, default it to zero.
2277   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl,
2278                                DAG.getConstant(0, PtrVT), Temp,
2279                                MachinePointerInfo(), false, false, 0);
2280
2281   TargetLowering::ArgListTy Args;
2282   TargetLowering::ArgListEntry Entry;
2283   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2284     EVT ArgVT = N->getOperand(i).getValueType();
2285     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2286     Entry.Node = N->getOperand(i);
2287     Entry.Ty = ArgTy;
2288     Entry.isSExt = true;
2289     Entry.isZExt = false;
2290     Args.push_back(Entry);
2291   }
2292
2293   // Also pass the address of the overflow check.
2294   Entry.Node = Temp;
2295   Entry.Ty = PtrTy->getPointerTo();
2296   Entry.isSExt = true;
2297   Entry.isZExt = false;
2298   Args.push_back(Entry);
2299
2300   SDValue Func = DAG.getExternalSymbol(TLI.getLibcallName(LC), PtrVT);
2301   TargetLowering::
2302   CallLoweringInfo CLI(Chain, RetTy, true, false, false, false,
2303                        0, TLI.getLibcallCallingConv(LC),
2304                        /*isTailCall=*/false,
2305                        /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
2306                        Func, Args, DAG, dl);
2307   std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2308
2309   SplitInteger(CallInfo.first, Lo, Hi);
2310   SDValue Temp2 = DAG.getLoad(PtrVT, dl, CallInfo.second, Temp,
2311                               MachinePointerInfo(), false, false, false, 0);
2312   SDValue Ofl = DAG.getSetCC(dl, N->getValueType(1), Temp2,
2313                              DAG.getConstant(0, PtrVT),
2314                              ISD::SETNE);
2315   // Use the overflow from the libcall everywhere.
2316   ReplaceValueWith(SDValue(N, 1), Ofl);
2317 }
2318
2319 void DAGTypeLegalizer::ExpandIntRes_UDIV(SDNode *N,
2320                                          SDValue &Lo, SDValue &Hi) {
2321   EVT VT = N->getValueType(0);
2322   SDLoc dl(N);
2323
2324   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2325   if (VT == MVT::i16)
2326     LC = RTLIB::UDIV_I16;
2327   else if (VT == MVT::i32)
2328     LC = RTLIB::UDIV_I32;
2329   else if (VT == MVT::i64)
2330     LC = RTLIB::UDIV_I64;
2331   else if (VT == MVT::i128)
2332     LC = RTLIB::UDIV_I128;
2333   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UDIV!");
2334
2335   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2336   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, 2, false, dl).first, Lo, Hi);
2337 }
2338
2339 void DAGTypeLegalizer::ExpandIntRes_UREM(SDNode *N,
2340                                          SDValue &Lo, SDValue &Hi) {
2341   EVT VT = N->getValueType(0);
2342   SDLoc dl(N);
2343
2344   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2345   if (VT == MVT::i16)
2346     LC = RTLIB::UREM_I16;
2347   else if (VT == MVT::i32)
2348     LC = RTLIB::UREM_I32;
2349   else if (VT == MVT::i64)
2350     LC = RTLIB::UREM_I64;
2351   else if (VT == MVT::i128)
2352     LC = RTLIB::UREM_I128;
2353   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UREM!");
2354
2355   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2356   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, 2, false, dl).first, Lo, Hi);
2357 }
2358
2359 void DAGTypeLegalizer::ExpandIntRes_ZERO_EXTEND(SDNode *N,
2360                                                 SDValue &Lo, SDValue &Hi) {
2361   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2362   SDLoc dl(N);
2363   SDValue Op = N->getOperand(0);
2364   if (Op.getValueType().bitsLE(NVT)) {
2365     // The low part is zero extension of the input (degenerates to a copy).
2366     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N->getOperand(0));
2367     Hi = DAG.getConstant(0, NVT);   // The high part is just a zero.
2368   } else {
2369     // For example, extension of an i48 to an i64.  The operand type necessarily
2370     // promotes to the result type, so will end up being expanded too.
2371     assert(getTypeAction(Op.getValueType()) ==
2372            TargetLowering::TypePromoteInteger &&
2373            "Only know how to promote this result!");
2374     SDValue Res = GetPromotedInteger(Op);
2375     assert(Res.getValueType() == N->getValueType(0) &&
2376            "Operand over promoted?");
2377     // Split the promoted operand.  This will simplify when it is expanded.
2378     SplitInteger(Res, Lo, Hi);
2379     unsigned ExcessBits =
2380       Op.getValueType().getSizeInBits() - NVT.getSizeInBits();
2381     Hi = DAG.getZeroExtendInReg(Hi, dl,
2382                                 EVT::getIntegerVT(*DAG.getContext(),
2383                                                   ExcessBits));
2384   }
2385 }
2386
2387 void DAGTypeLegalizer::ExpandIntRes_ATOMIC_LOAD(SDNode *N,
2388                                                 SDValue &Lo, SDValue &Hi) {
2389   SDLoc dl(N);
2390   EVT VT = cast<AtomicSDNode>(N)->getMemoryVT();
2391   SDValue Zero = DAG.getConstant(0, VT);
2392   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
2393                                N->getOperand(0),
2394                                N->getOperand(1), Zero, Zero,
2395                                cast<AtomicSDNode>(N)->getMemOperand(),
2396                                cast<AtomicSDNode>(N)->getOrdering(),
2397                                cast<AtomicSDNode>(N)->getOrdering(),
2398                                cast<AtomicSDNode>(N)->getSynchScope());
2399   ReplaceValueWith(SDValue(N, 0), Swap.getValue(0));
2400   ReplaceValueWith(SDValue(N, 1), Swap.getValue(1));
2401 }
2402
2403 //===----------------------------------------------------------------------===//
2404 //  Integer Operand Expansion
2405 //===----------------------------------------------------------------------===//
2406
2407 /// ExpandIntegerOperand - This method is called when the specified operand of
2408 /// the specified node is found to need expansion.  At this point, all of the
2409 /// result types of the node are known to be legal, but other operands of the
2410 /// node may need promotion or expansion as well as the specified one.
2411 bool DAGTypeLegalizer::ExpandIntegerOperand(SDNode *N, unsigned OpNo) {
2412   DEBUG(dbgs() << "Expand integer operand: "; N->dump(&DAG); dbgs() << "\n");
2413   SDValue Res = SDValue();
2414
2415   if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
2416     return false;
2417
2418   switch (N->getOpcode()) {
2419   default:
2420   #ifndef NDEBUG
2421     dbgs() << "ExpandIntegerOperand Op #" << OpNo << ": ";
2422     N->dump(&DAG); dbgs() << "\n";
2423   #endif
2424     llvm_unreachable("Do not know how to expand this operator's operand!");
2425
2426   case ISD::BITCAST:           Res = ExpandOp_BITCAST(N); break;
2427   case ISD::BR_CC:             Res = ExpandIntOp_BR_CC(N); break;
2428   case ISD::BUILD_VECTOR:      Res = ExpandOp_BUILD_VECTOR(N); break;
2429   case ISD::EXTRACT_ELEMENT:   Res = ExpandOp_EXTRACT_ELEMENT(N); break;
2430   case ISD::INSERT_VECTOR_ELT: Res = ExpandOp_INSERT_VECTOR_ELT(N); break;
2431   case ISD::SCALAR_TO_VECTOR:  Res = ExpandOp_SCALAR_TO_VECTOR(N); break;
2432   case ISD::SELECT_CC:         Res = ExpandIntOp_SELECT_CC(N); break;
2433   case ISD::SETCC:             Res = ExpandIntOp_SETCC(N); break;
2434   case ISD::SINT_TO_FP:        Res = ExpandIntOp_SINT_TO_FP(N); break;
2435   case ISD::STORE:   Res = ExpandIntOp_STORE(cast<StoreSDNode>(N), OpNo); break;
2436   case ISD::TRUNCATE:          Res = ExpandIntOp_TRUNCATE(N); break;
2437   case ISD::UINT_TO_FP:        Res = ExpandIntOp_UINT_TO_FP(N); break;
2438
2439   case ISD::SHL:
2440   case ISD::SRA:
2441   case ISD::SRL:
2442   case ISD::ROTL:
2443   case ISD::ROTR:              Res = ExpandIntOp_Shift(N); break;
2444   case ISD::RETURNADDR:
2445   case ISD::FRAMEADDR:         Res = ExpandIntOp_RETURNADDR(N); break;
2446
2447   case ISD::ATOMIC_STORE:      Res = ExpandIntOp_ATOMIC_STORE(N); break;
2448   }
2449
2450   // If the result is null, the sub-method took care of registering results etc.
2451   if (!Res.getNode()) return false;
2452
2453   // If the result is N, the sub-method updated N in place.  Tell the legalizer
2454   // core about this.
2455   if (Res.getNode() == N)
2456     return true;
2457
2458   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
2459          "Invalid operand expansion");
2460
2461   ReplaceValueWith(SDValue(N, 0), Res);
2462   return false;
2463 }
2464
2465 /// IntegerExpandSetCCOperands - Expand the operands of a comparison.  This code
2466 /// is shared among BR_CC, SELECT_CC, and SETCC handlers.
2467 void DAGTypeLegalizer::IntegerExpandSetCCOperands(SDValue &NewLHS,
2468                                                   SDValue &NewRHS,
2469                                                   ISD::CondCode &CCCode,
2470                                                   SDLoc dl) {
2471   SDValue LHSLo, LHSHi, RHSLo, RHSHi;
2472   GetExpandedInteger(NewLHS, LHSLo, LHSHi);
2473   GetExpandedInteger(NewRHS, RHSLo, RHSHi);
2474
2475   if (CCCode == ISD::SETEQ || CCCode == ISD::SETNE) {
2476     if (RHSLo == RHSHi) {
2477       if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo)) {
2478         if (RHSCST->isAllOnesValue()) {
2479           // Equality comparison to -1.
2480           NewLHS = DAG.getNode(ISD::AND, dl,
2481                                LHSLo.getValueType(), LHSLo, LHSHi);
2482           NewRHS = RHSLo;
2483           return;
2484         }
2485       }
2486     }
2487
2488     NewLHS = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSLo, RHSLo);
2489     NewRHS = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSHi, RHSHi);
2490     NewLHS = DAG.getNode(ISD::OR, dl, NewLHS.getValueType(), NewLHS, NewRHS);
2491     NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2492     return;
2493   }
2494
2495   // If this is a comparison of the sign bit, just look at the top part.
2496   // X > -1,  x < 0
2497   if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(NewRHS))
2498     if ((CCCode == ISD::SETLT && CST->isNullValue()) ||     // X < 0
2499         (CCCode == ISD::SETGT && CST->isAllOnesValue())) {  // X > -1
2500       NewLHS = LHSHi;
2501       NewRHS = RHSHi;
2502       return;
2503     }
2504
2505   // FIXME: This generated code sucks.
2506   ISD::CondCode LowCC;
2507   switch (CCCode) {
2508   default: llvm_unreachable("Unknown integer setcc!");
2509   case ISD::SETLT:
2510   case ISD::SETULT: LowCC = ISD::SETULT; break;
2511   case ISD::SETGT:
2512   case ISD::SETUGT: LowCC = ISD::SETUGT; break;
2513   case ISD::SETLE:
2514   case ISD::SETULE: LowCC = ISD::SETULE; break;
2515   case ISD::SETGE:
2516   case ISD::SETUGE: LowCC = ISD::SETUGE; break;
2517   }
2518
2519   // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
2520   // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
2521   // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
2522
2523   // NOTE: on targets without efficient SELECT of bools, we can always use
2524   // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
2525   TargetLowering::DAGCombinerInfo DagCombineInfo(DAG, AfterLegalizeTypes, true,
2526                                                  nullptr);
2527   SDValue Tmp1, Tmp2;
2528   if (TLI.isTypeLegal(LHSLo.getValueType()) &&
2529       TLI.isTypeLegal(RHSLo.getValueType()))
2530     Tmp1 = TLI.SimplifySetCC(getSetCCResultType(LHSLo.getValueType()),
2531                              LHSLo, RHSLo, LowCC, false, DagCombineInfo, dl);
2532   if (!Tmp1.getNode())
2533     Tmp1 = DAG.getSetCC(dl, getSetCCResultType(LHSLo.getValueType()),
2534                         LHSLo, RHSLo, LowCC);
2535   if (TLI.isTypeLegal(LHSHi.getValueType()) &&
2536       TLI.isTypeLegal(RHSHi.getValueType()))
2537     Tmp2 = TLI.SimplifySetCC(getSetCCResultType(LHSHi.getValueType()),
2538                              LHSHi, RHSHi, CCCode, false, DagCombineInfo, dl);
2539   if (!Tmp2.getNode())
2540     Tmp2 = DAG.getNode(ISD::SETCC, dl,
2541                        getSetCCResultType(LHSHi.getValueType()),
2542                        LHSHi, RHSHi, DAG.getCondCode(CCCode));
2543
2544   ConstantSDNode *Tmp1C = dyn_cast<ConstantSDNode>(Tmp1.getNode());
2545   ConstantSDNode *Tmp2C = dyn_cast<ConstantSDNode>(Tmp2.getNode());
2546   if ((Tmp1C && Tmp1C->isNullValue()) ||
2547       (Tmp2C && Tmp2C->isNullValue() &&
2548        (CCCode == ISD::SETLE || CCCode == ISD::SETGE ||
2549         CCCode == ISD::SETUGE || CCCode == ISD::SETULE)) ||
2550       (Tmp2C && Tmp2C->getAPIntValue() == 1 &&
2551        (CCCode == ISD::SETLT || CCCode == ISD::SETGT ||
2552         CCCode == ISD::SETUGT || CCCode == ISD::SETULT))) {
2553     // low part is known false, returns high part.
2554     // For LE / GE, if high part is known false, ignore the low part.
2555     // For LT / GT, if high part is known true, ignore the low part.
2556     NewLHS = Tmp2;
2557     NewRHS = SDValue();
2558     return;
2559   }
2560
2561   NewLHS = TLI.SimplifySetCC(getSetCCResultType(LHSHi.getValueType()),
2562                              LHSHi, RHSHi, ISD::SETEQ, false,
2563                              DagCombineInfo, dl);
2564   if (!NewLHS.getNode())
2565     NewLHS = DAG.getSetCC(dl, getSetCCResultType(LHSHi.getValueType()),
2566                           LHSHi, RHSHi, ISD::SETEQ);
2567   NewLHS = DAG.getSelect(dl, Tmp1.getValueType(),
2568                          NewLHS, Tmp1, Tmp2);
2569   NewRHS = SDValue();
2570 }
2571
2572 SDValue DAGTypeLegalizer::ExpandIntOp_BR_CC(SDNode *N) {
2573   SDValue NewLHS = N->getOperand(2), NewRHS = N->getOperand(3);
2574   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(1))->get();
2575   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, SDLoc(N));
2576
2577   // If ExpandSetCCOperands returned a scalar, we need to compare the result
2578   // against zero to select between true and false values.
2579   if (!NewRHS.getNode()) {
2580     NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2581     CCCode = ISD::SETNE;
2582   }
2583
2584   // Update N to have the operands specified.
2585   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
2586                                 DAG.getCondCode(CCCode), NewLHS, NewRHS,
2587                                 N->getOperand(4)), 0);
2588 }
2589
2590 SDValue DAGTypeLegalizer::ExpandIntOp_SELECT_CC(SDNode *N) {
2591   SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
2592   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(4))->get();
2593   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, SDLoc(N));
2594
2595   // If ExpandSetCCOperands returned a scalar, we need to compare the result
2596   // against zero to select between true and false values.
2597   if (!NewRHS.getNode()) {
2598     NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2599     CCCode = ISD::SETNE;
2600   }
2601
2602   // Update N to have the operands specified.
2603   return SDValue(DAG.UpdateNodeOperands(N, NewLHS, NewRHS,
2604                                 N->getOperand(2), N->getOperand(3),
2605                                 DAG.getCondCode(CCCode)), 0);
2606 }
2607
2608 SDValue DAGTypeLegalizer::ExpandIntOp_SETCC(SDNode *N) {
2609   SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
2610   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(2))->get();
2611   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, SDLoc(N));
2612
2613   // If ExpandSetCCOperands returned a scalar, use it.
2614   if (!NewRHS.getNode()) {
2615     assert(NewLHS.getValueType() == N->getValueType(0) &&
2616            "Unexpected setcc expansion!");
2617     return NewLHS;
2618   }
2619
2620   // Otherwise, update N to have the operands specified.
2621   return SDValue(DAG.UpdateNodeOperands(N, NewLHS, NewRHS,
2622                                 DAG.getCondCode(CCCode)), 0);
2623 }
2624
2625 SDValue DAGTypeLegalizer::ExpandIntOp_Shift(SDNode *N) {
2626   // The value being shifted is legal, but the shift amount is too big.
2627   // It follows that either the result of the shift is undefined, or the
2628   // upper half of the shift amount is zero.  Just use the lower half.
2629   SDValue Lo, Hi;
2630   GetExpandedInteger(N->getOperand(1), Lo, Hi);
2631   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0), Lo), 0);
2632 }
2633
2634 SDValue DAGTypeLegalizer::ExpandIntOp_RETURNADDR(SDNode *N) {
2635   // The argument of RETURNADDR / FRAMEADDR builtin is 32 bit contant.  This
2636   // surely makes pretty nice problems on 8/16 bit targets. Just truncate this
2637   // constant to valid type.
2638   SDValue Lo, Hi;
2639   GetExpandedInteger(N->getOperand(0), Lo, Hi);
2640   return SDValue(DAG.UpdateNodeOperands(N, Lo), 0);
2641 }
2642
2643 SDValue DAGTypeLegalizer::ExpandIntOp_SINT_TO_FP(SDNode *N) {
2644   SDValue Op = N->getOperand(0);
2645   EVT DstVT = N->getValueType(0);
2646   RTLIB::Libcall LC = RTLIB::getSINTTOFP(Op.getValueType(), DstVT);
2647   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
2648          "Don't know how to expand this SINT_TO_FP!");
2649   return TLI.makeLibCall(DAG, LC, DstVT, &Op, 1, true, SDLoc(N)).first;
2650 }
2651
2652 SDValue DAGTypeLegalizer::ExpandIntOp_STORE(StoreSDNode *N, unsigned OpNo) {
2653   if (ISD::isNormalStore(N))
2654     return ExpandOp_NormalStore(N, OpNo);
2655
2656   assert(ISD::isUNINDEXEDStore(N) && "Indexed store during type legalization!");
2657   assert(OpNo == 1 && "Can only expand the stored value so far");
2658
2659   EVT VT = N->getOperand(1).getValueType();
2660   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2661   SDValue Ch  = N->getChain();
2662   SDValue Ptr = N->getBasePtr();
2663   unsigned Alignment = N->getAlignment();
2664   bool isVolatile = N->isVolatile();
2665   bool isNonTemporal = N->isNonTemporal();
2666   const MDNode *TBAAInfo = N->getTBAAInfo();
2667   SDLoc dl(N);
2668   SDValue Lo, Hi;
2669
2670   assert(NVT.isByteSized() && "Expanded type not byte sized!");
2671
2672   if (N->getMemoryVT().bitsLE(NVT)) {
2673     GetExpandedInteger(N->getValue(), Lo, Hi);
2674     return DAG.getTruncStore(Ch, dl, Lo, Ptr, N->getPointerInfo(),
2675                              N->getMemoryVT(), isVolatile, isNonTemporal,
2676                              Alignment, TBAAInfo);
2677   }
2678
2679   if (TLI.isLittleEndian()) {
2680     // Little-endian - low bits are at low addresses.
2681     GetExpandedInteger(N->getValue(), Lo, Hi);
2682
2683     Lo = DAG.getStore(Ch, dl, Lo, Ptr, N->getPointerInfo(),
2684                       isVolatile, isNonTemporal, Alignment, TBAAInfo);
2685
2686     unsigned ExcessBits =
2687       N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
2688     EVT NEVT = EVT::getIntegerVT(*DAG.getContext(), ExcessBits);
2689
2690     // Increment the pointer to the other half.
2691     unsigned IncrementSize = NVT.getSizeInBits()/8;
2692     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
2693                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
2694     Hi = DAG.getTruncStore(Ch, dl, Hi, Ptr,
2695                            N->getPointerInfo().getWithOffset(IncrementSize),
2696                            NEVT, isVolatile, isNonTemporal,
2697                            MinAlign(Alignment, IncrementSize), TBAAInfo);
2698     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
2699   }
2700
2701   // Big-endian - high bits are at low addresses.  Favor aligned stores at
2702   // the cost of some bit-fiddling.
2703   GetExpandedInteger(N->getValue(), Lo, Hi);
2704
2705   EVT ExtVT = N->getMemoryVT();
2706   unsigned EBytes = ExtVT.getStoreSize();
2707   unsigned IncrementSize = NVT.getSizeInBits()/8;
2708   unsigned ExcessBits = (EBytes - IncrementSize)*8;
2709   EVT HiVT = EVT::getIntegerVT(*DAG.getContext(),
2710                                ExtVT.getSizeInBits() - ExcessBits);
2711
2712   if (ExcessBits < NVT.getSizeInBits()) {
2713     // Transfer high bits from the top of Lo to the bottom of Hi.
2714     Hi = DAG.getNode(ISD::SHL, dl, NVT, Hi,
2715                      DAG.getConstant(NVT.getSizeInBits() - ExcessBits,
2716                                      TLI.getPointerTy()));
2717     Hi = DAG.getNode(ISD::OR, dl, NVT, Hi,
2718                      DAG.getNode(ISD::SRL, dl, NVT, Lo,
2719                                  DAG.getConstant(ExcessBits,
2720                                                  TLI.getPointerTy())));
2721   }
2722
2723   // Store both the high bits and maybe some of the low bits.
2724   Hi = DAG.getTruncStore(Ch, dl, Hi, Ptr, N->getPointerInfo(),
2725                          HiVT, isVolatile, isNonTemporal, Alignment, TBAAInfo);
2726
2727   // Increment the pointer to the other half.
2728   Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
2729                     DAG.getConstant(IncrementSize, Ptr.getValueType()));
2730   // Store the lowest ExcessBits bits in the second half.
2731   Lo = DAG.getTruncStore(Ch, dl, Lo, Ptr,
2732                          N->getPointerInfo().getWithOffset(IncrementSize),
2733                          EVT::getIntegerVT(*DAG.getContext(), ExcessBits),
2734                          isVolatile, isNonTemporal,
2735                          MinAlign(Alignment, IncrementSize), TBAAInfo);
2736   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
2737 }
2738
2739 SDValue DAGTypeLegalizer::ExpandIntOp_TRUNCATE(SDNode *N) {
2740   SDValue InL, InH;
2741   GetExpandedInteger(N->getOperand(0), InL, InH);
2742   // Just truncate the low part of the source.
2743   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), InL);
2744 }
2745
2746 SDValue DAGTypeLegalizer::ExpandIntOp_UINT_TO_FP(SDNode *N) {
2747   SDValue Op = N->getOperand(0);
2748   EVT SrcVT = Op.getValueType();
2749   EVT DstVT = N->getValueType(0);
2750   SDLoc dl(N);
2751
2752   // The following optimization is valid only if every value in SrcVT (when
2753   // treated as signed) is representable in DstVT.  Check that the mantissa
2754   // size of DstVT is >= than the number of bits in SrcVT -1.
2755   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(DstVT);
2756   if (APFloat::semanticsPrecision(sem) >= SrcVT.getSizeInBits()-1 &&
2757       TLI.getOperationAction(ISD::SINT_TO_FP, SrcVT) == TargetLowering::Custom){
2758     // Do a signed conversion then adjust the result.
2759     SDValue SignedConv = DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Op);
2760     SignedConv = TLI.LowerOperation(SignedConv, DAG);
2761
2762     // The result of the signed conversion needs adjusting if the 'sign bit' of
2763     // the incoming integer was set.  To handle this, we dynamically test to see
2764     // if it is set, and, if so, add a fudge factor.
2765
2766     const uint64_t F32TwoE32  = 0x4F800000ULL;
2767     const uint64_t F32TwoE64  = 0x5F800000ULL;
2768     const uint64_t F32TwoE128 = 0x7F800000ULL;
2769
2770     APInt FF(32, 0);
2771     if (SrcVT == MVT::i32)
2772       FF = APInt(32, F32TwoE32);
2773     else if (SrcVT == MVT::i64)
2774       FF = APInt(32, F32TwoE64);
2775     else if (SrcVT == MVT::i128)
2776       FF = APInt(32, F32TwoE128);
2777     else
2778       llvm_unreachable("Unsupported UINT_TO_FP!");
2779
2780     // Check whether the sign bit is set.
2781     SDValue Lo, Hi;
2782     GetExpandedInteger(Op, Lo, Hi);
2783     SDValue SignSet = DAG.getSetCC(dl,
2784                                    getSetCCResultType(Hi.getValueType()),
2785                                    Hi, DAG.getConstant(0, Hi.getValueType()),
2786                                    ISD::SETLT);
2787
2788     // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
2789     SDValue FudgePtr = DAG.getConstantPool(
2790                                ConstantInt::get(*DAG.getContext(), FF.zext(64)),
2791                                            TLI.getPointerTy());
2792
2793     // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
2794     SDValue Zero = DAG.getIntPtrConstant(0);
2795     SDValue Four = DAG.getIntPtrConstant(4);
2796     if (TLI.isBigEndian()) std::swap(Zero, Four);
2797     SDValue Offset = DAG.getSelect(dl, Zero.getValueType(), SignSet,
2798                                    Zero, Four);
2799     unsigned Alignment = cast<ConstantPoolSDNode>(FudgePtr)->getAlignment();
2800     FudgePtr = DAG.getNode(ISD::ADD, dl, FudgePtr.getValueType(),
2801                            FudgePtr, Offset);
2802     Alignment = std::min(Alignment, 4u);
2803
2804     // Load the value out, extending it from f32 to the destination float type.
2805     // FIXME: Avoid the extend by constructing the right constant pool?
2806     SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, DstVT, DAG.getEntryNode(),
2807                                    FudgePtr,
2808                                    MachinePointerInfo::getConstantPool(),
2809                                    MVT::f32,
2810                                    false, false, Alignment);
2811     return DAG.getNode(ISD::FADD, dl, DstVT, SignedConv, Fudge);
2812   }
2813
2814   // Otherwise, use a libcall.
2815   RTLIB::Libcall LC = RTLIB::getUINTTOFP(SrcVT, DstVT);
2816   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
2817          "Don't know how to expand this UINT_TO_FP!");
2818   return TLI.makeLibCall(DAG, LC, DstVT, &Op, 1, true, dl).first;
2819 }
2820
2821 SDValue DAGTypeLegalizer::ExpandIntOp_ATOMIC_STORE(SDNode *N) {
2822   SDLoc dl(N);
2823   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
2824                                cast<AtomicSDNode>(N)->getMemoryVT(),
2825                                N->getOperand(0),
2826                                N->getOperand(1), N->getOperand(2),
2827                                cast<AtomicSDNode>(N)->getMemOperand(),
2828                                cast<AtomicSDNode>(N)->getOrdering(),
2829                                cast<AtomicSDNode>(N)->getSynchScope());
2830   return Swap.getValue(1);
2831 }
2832
2833
2834 SDValue DAGTypeLegalizer::PromoteIntRes_EXTRACT_SUBVECTOR(SDNode *N) {
2835   SDValue InOp0 = N->getOperand(0);
2836   EVT InVT = InOp0.getValueType();
2837
2838   EVT OutVT = N->getValueType(0);
2839   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2840   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2841   unsigned OutNumElems = OutVT.getVectorNumElements();
2842   EVT NOutVTElem = NOutVT.getVectorElementType();
2843
2844   SDLoc dl(N);
2845   SDValue BaseIdx = N->getOperand(1);
2846
2847   SmallVector<SDValue, 8> Ops;
2848   Ops.reserve(OutNumElems);
2849   for (unsigned i = 0; i != OutNumElems; ++i) {
2850
2851     // Extract the element from the original vector.
2852     SDValue Index = DAG.getNode(ISD::ADD, dl, BaseIdx.getValueType(),
2853       BaseIdx, DAG.getConstant(i, BaseIdx.getValueType()));
2854     SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
2855       InVT.getVectorElementType(), N->getOperand(0), Index);
2856
2857     SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, Ext);
2858     // Insert the converted element to the new vector.
2859     Ops.push_back(Op);
2860   }
2861
2862   return DAG.getNode(ISD::BUILD_VECTOR, dl, NOutVT, Ops);
2863 }
2864
2865
2866 SDValue DAGTypeLegalizer::PromoteIntRes_VECTOR_SHUFFLE(SDNode *N) {
2867   ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
2868   EVT VT = N->getValueType(0);
2869   SDLoc dl(N);
2870
2871   unsigned NumElts = VT.getVectorNumElements();
2872   SmallVector<int, 8> NewMask;
2873   for (unsigned i = 0; i != NumElts; ++i) {
2874     NewMask.push_back(SV->getMaskElt(i));
2875   }
2876
2877   SDValue V0 = GetPromotedInteger(N->getOperand(0));
2878   SDValue V1 = GetPromotedInteger(N->getOperand(1));
2879   EVT OutVT = V0.getValueType();
2880
2881   return DAG.getVectorShuffle(OutVT, dl, V0, V1, &NewMask[0]);
2882 }
2883
2884
2885 SDValue DAGTypeLegalizer::PromoteIntRes_BUILD_VECTOR(SDNode *N) {
2886   EVT OutVT = N->getValueType(0);
2887   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2888   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2889   unsigned NumElems = N->getNumOperands();
2890   EVT NOutVTElem = NOutVT.getVectorElementType();
2891
2892   SDLoc dl(N);
2893
2894   SmallVector<SDValue, 8> Ops;
2895   Ops.reserve(NumElems);
2896   for (unsigned i = 0; i != NumElems; ++i) {
2897     SDValue Op;
2898     // BUILD_VECTOR integer operand types are allowed to be larger than the
2899     // result's element type. This may still be true after the promotion. For
2900     // example, we might be promoting (<v?i1> = BV <i32>, <i32>, ...) to
2901     // (v?i16 = BV <i32>, <i32>, ...), and we can't any_extend <i32> to <i16>.
2902     if (N->getOperand(i).getValueType().bitsLT(NOutVTElem))
2903       Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, N->getOperand(i));
2904     else
2905       Op = N->getOperand(i);
2906     Ops.push_back(Op);
2907   }
2908
2909   return DAG.getNode(ISD::BUILD_VECTOR, dl, NOutVT, Ops);
2910 }
2911
2912 SDValue DAGTypeLegalizer::PromoteIntRes_SCALAR_TO_VECTOR(SDNode *N) {
2913
2914   SDLoc dl(N);
2915
2916   assert(!N->getOperand(0).getValueType().isVector() &&
2917          "Input must be a scalar");
2918
2919   EVT OutVT = N->getValueType(0);
2920   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2921   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2922   EVT NOutVTElem = NOutVT.getVectorElementType();
2923
2924   SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, N->getOperand(0));
2925
2926   return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NOutVT, Op);
2927 }
2928
2929 SDValue DAGTypeLegalizer::PromoteIntRes_CONCAT_VECTORS(SDNode *N) {
2930   SDLoc dl(N);
2931
2932   EVT OutVT = N->getValueType(0);
2933   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2934   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2935
2936   EVT InElemTy = OutVT.getVectorElementType();
2937   EVT OutElemTy = NOutVT.getVectorElementType();
2938
2939   unsigned NumElem = N->getOperand(0).getValueType().getVectorNumElements();
2940   unsigned NumOutElem = NOutVT.getVectorNumElements();
2941   unsigned NumOperands = N->getNumOperands();
2942   assert(NumElem * NumOperands == NumOutElem &&
2943          "Unexpected number of elements");
2944
2945   // Take the elements from the first vector.
2946   SmallVector<SDValue, 8> Ops(NumOutElem);
2947   for (unsigned i = 0; i < NumOperands; ++i) {
2948     SDValue Op = N->getOperand(i);
2949     for (unsigned j = 0; j < NumElem; ++j) {
2950       SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
2951                                 InElemTy, Op, DAG.getConstant(j,
2952                                               TLI.getVectorIdxTy()));
2953       Ops[i * NumElem + j] = DAG.getNode(ISD::ANY_EXTEND, dl, OutElemTy, Ext);
2954     }
2955   }
2956
2957   return DAG.getNode(ISD::BUILD_VECTOR, dl, NOutVT, Ops);
2958 }
2959
2960 SDValue DAGTypeLegalizer::PromoteIntRes_INSERT_VECTOR_ELT(SDNode *N) {
2961   EVT OutVT = N->getValueType(0);
2962   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2963   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2964
2965   EVT NOutVTElem = NOutVT.getVectorElementType();
2966
2967   SDLoc dl(N);
2968   SDValue V0 = GetPromotedInteger(N->getOperand(0));
2969
2970   SDValue ConvElem = DAG.getNode(ISD::ANY_EXTEND, dl,
2971     NOutVTElem, N->getOperand(1));
2972   return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, NOutVT,
2973     V0, ConvElem, N->getOperand(2));
2974 }
2975
2976 SDValue DAGTypeLegalizer::PromoteIntOp_EXTRACT_VECTOR_ELT(SDNode *N) {
2977   SDLoc dl(N);
2978   SDValue V0 = GetPromotedInteger(N->getOperand(0));
2979   SDValue V1 = DAG.getZExtOrTrunc(N->getOperand(1), dl, TLI.getVectorIdxTy());
2980   SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
2981     V0->getValueType(0).getScalarType(), V0, V1);
2982
2983   // EXTRACT_VECTOR_ELT can return types which are wider than the incoming
2984   // element types. If this is the case then we need to expand the outgoing
2985   // value and not truncate it.
2986   return DAG.getAnyExtOrTrunc(Ext, dl, N->getValueType(0));
2987 }
2988
2989 SDValue DAGTypeLegalizer::PromoteIntOp_CONCAT_VECTORS(SDNode *N) {
2990   SDLoc dl(N);
2991   unsigned NumElems = N->getNumOperands();
2992
2993   EVT RetSclrTy = N->getValueType(0).getVectorElementType();
2994
2995   SmallVector<SDValue, 8> NewOps;
2996   NewOps.reserve(NumElems);
2997
2998   // For each incoming vector
2999   for (unsigned VecIdx = 0; VecIdx != NumElems; ++VecIdx) {
3000     SDValue Incoming = GetPromotedInteger(N->getOperand(VecIdx));
3001     EVT SclrTy = Incoming->getValueType(0).getVectorElementType();
3002     unsigned NumElem = Incoming->getValueType(0).getVectorNumElements();
3003
3004     for (unsigned i=0; i<NumElem; ++i) {
3005       // Extract element from incoming vector
3006       SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SclrTy,
3007       Incoming, DAG.getConstant(i, TLI.getVectorIdxTy()));
3008       SDValue Tr = DAG.getNode(ISD::TRUNCATE, dl, RetSclrTy, Ex);
3009       NewOps.push_back(Tr);
3010     }
3011   }
3012
3013   return DAG.getNode(ISD::BUILD_VECTOR, dl,  N->getValueType(0), NewOps);
3014 }