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