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