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