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